Compare commits

..
2678 Commits
Author SHA1 Message Date
Marc-André Bombeck 643e1b3c25 Merge pull request #1163 from MBombeck/release/v1.40.2
chore(release): v1.40.2
2026-10-05 10:03:51 +02:00
Marc-André Bombeck fd895bfd5f chore(release): v1.40.2 2026-10-05 08:44:10 +02:00
Marc-André Bombeck f42a28b7f6 chore(bundle): re-measure the aggregate client budget for the Coach redesign and the Today overview 2026-10-05 08:43:46 +02:00
Marc-André Bombeck a1ec3b1264 Merge branch 'fix/v1402-review' into release/v1.40.2 2026-10-05 08:42:28 +02:00
Marc-André Bombeck 4db7fc5113 fix(coach): open the deep-linked sheet only once the viewport is known
/coach?settings=data opened the conversations sheet from the first
render. The server and hydration renders do not know the viewport and
take the narrow layout, so on a desktop the sheet was open until the
docked panel replaced it; only the batching of the hydration re-render
kept it off the screen. The deep link now opens the sheet only once
hydrated on a viewport that does not dock the panel; on a docked one the
panel is revealed as before.

The desktop deep-link spec records every mount of the sheet from the
first byte and expects none; a phone deep-link spec covers the sheet
path and serves as the watcher's positive control.
2026-10-05 08:34:28 +02:00
Marc-André Bombeck 4bb03600b3 perf(dashboard): cache today's cycle read and run the vitals reads together
The digest is polled every 120 seconds. Its cycle line read the whole
cycle history, 90 days of day logs and wrist temperature on every poll,
outside any cache, and the coincident-deviation engine walked its eleven
vitals one after another, two queries each.

The cycle read now rides the digest extras cell, which every cycle write
already hard-evicts; the cycle preferences route evicts it too, and a
module switch does through the health-score invalidator. A record without
a cycle profile stops after one point read. The per-vital reads run
together and are folded in registry order, so the result does not depend
on which finished first.

On a seeded four-year account (1.25M measurements, 52 cycles) under a
792 MB heap, the warm digest went from 9.9 to 5.0 ms and the vitals engine
from 11.1 to 4.6 ms (medians of four interleaved rounds).
2026-10-05 08:34:28 +02:00
Marc-André Bombeck bfcf71b7eb fix(dashboard): keep numbers out of the morning push line
The digest line is the body of the morning push and lands on a locked
phone. It took the briefing's first sentence, the top signal's headline
or the deterministic signal sentence verbatim, so a resting heart rate or
a blood pressure average could sit on the lock screen, and its score
floor stated the score.

A candidate with a figure in it is now passed over for the next, and the
floor says the score is ready instead of what it is. The hero's lead in
the app keeps its numbers. Tests that pinned the numeric line are turned
around, and the push builder is checked on a digest whose lead carries a
reading.
2026-10-05 08:34:28 +02:00
Marc-André Bombeck bd8e05e484 fix(dashboard): drop a lead sentence only when it repeats the score as the score
The lead filter dropped any sentence containing the score's digits, so a
score of 52 threw out "You slept 7 h 52 min" and a resting heart rate of
52 bpm. A sentence now repeats the ring only when it names the score (in
any shipped language, or as "out of 100") and carries the number on its
own, not as part of a time, a decimal or a measurement with a unit.
2026-10-05 08:34:27 +02:00
Marc-André Bombeck 9e647051d5 fix(dashboard): tell a steady score only when its band held, and say at least at the read's edge
The steady line compared the newest stored score with the number on
screen but not with its band, version or composition, so a score whose
band moved overnight at the same number was still called steady. A run
that reached back past the 120 days read was also told as if it started
there.

The newest stored day now has to match the ring in value, band and,
where the digest carries them, algorithm version and composition. A run
the read cannot see the start of is marked as open (steadyAtLeast on the
digest score) and the hero says "at least" in seven locales.
2026-10-05 08:34:27 +02:00
Marc-André Bombeck 13ac27c22d docs(coach): say that older answers may still quote older values
The lookback limit governs what the Coach reads from now on. Answers it
gave earlier in an older conversation stay as written, so the note under
the limit now says they may still quote values from before it.
2026-10-05 08:34:27 +02:00
Marc-André Bombeck 87cf32bc67 fix(coach): leave derived scores out when their window does not fit the limit
The derived block shortened each engine's window to the lookback limit,
so a 7-day limit produced a readiness computed over 7 days instead of the
30 the ring on the dashboard uses, under the same name. A block whose own
window does not fit is now left out, as the lookback rule says, and the
coincident-deviation flag follows its 30-day baseline the same way.
2026-10-05 08:34:27 +02:00
Marc-André Bombeck 8dc34c7691 fix(coach): keep GLP-1 dose changes before the lookback limit out
The GLP-1 block sent every dose change with its decrypted note whatever
the lookback limit said. Dose changes are entries, so only those inside
the limit reach the prompt; the dose in force stays as the current dose.
2026-10-05 08:34:27 +02:00
Marc-André Bombeck 308e154978 fix(coach): move focus to the composer before hiding the jump button
Jumping to the latest message pinned the thread first, which hides the
button behind aria-hidden, and only then moved focus to the composer.
Focus now leaves the button before its state changes.
2026-10-05 08:34:27 +02:00
Marc-André Bombeck 3b283507b5 fix(dashboard): lead with the stored lines for a digest cached before the lead
The hero reads only digest.lead. A digest the service worker cached
before the update carries no such field, so the hero lost its lead line
until the next fetch. Such a digest now falls back to the reaction line
or the briefing lead it was built to show; a current digest whose lead
is null stays silent.
2026-10-05 08:34:27 +02:00
Marc-André Bombeck 94e0da7953 chore(i18n): drop the orphaned Coach window labels
The insights.coach.window labels lost their last caller with the source
chips. No t() call, literal or templated, reads them in any locale.
2026-10-05 08:34:27 +02:00
Marc-André Bombeck 35edc33871 fix(coach): lock the reasoning select while a change saves
The provider and model selects in the Coach's settings already lock while
a write is in flight; the reasoning select did not, so a second PATCH
could race the first and one change could be lost.
2026-10-05 08:34:27 +02:00
Marc-André Bombeck eda0b5831d feat(settings): summarise what the Coach sees beside the link to its settings
Settings → Coach pointed at the gear with a muted paragraph. It now says
how many data areas the Coach reads and how far back it looks, from the
saved preferences, next to an Open Coach settings button that lands on
that section.
2026-10-05 08:11:10 +02:00
Marc-André Bombeck 816269b3ed fix(documents): match the filter triggers to the search field's height
The facet triggers and the clear control were 32 px beside a 44/40 px
search field, below the phone tap floor. They now share its height and
reach 44 px square on a phone, and the browser's own clear button no
longer sits on the search icon when the field shrinks.
2026-10-05 08:11:10 +02:00
Marc-André Bombeck 88406f8e66 fix(dashboard): give the Today overview room under the lead and phone-sized rows
The overview sat 12 px under the lead sentence; it now keeps a section's
distance (16 px, 24 px from md). On a phone each fact row is a link and
now meets the 44 px tap floor.
2026-10-05 08:11:10 +02:00
Marc-André Bombeck 150ee7695c fix(coach): lift toasts clear of the panel's New chat button
Bottom toasts landed on the round New chat button for their whole
lifetime, so the delete Undo blocked the next action. While the
conversations panel is open, docked or as a sheet, bottom toasts rise by
the button's footprint.
2026-10-05 08:11:09 +02:00
Marc-André Bombeck 07f4961f27 fix(coach): label the quick-settings fields alike and give the lookback full width
The model fields carried the form label's colon and the lookback picker
an uppercase section-style label and a fit-content 36 px trigger. All four
fields now share one unadorned label and the full-width 44/40 px control.
2026-10-05 08:11:09 +02:00
Marc-André Bombeck d0b680c277 fix(dashboard): count the last hour of a 25-hour day in today's doses
buildMedsTodayBlock ended the day at local midnight plus 24 hours. On the
day the clocks go back that stops an hour early, so a dose between 23:00
and midnight was neither projected nor counted in the doses tally. The
exclusive end is now the next local day's start, as the digest loader
already computes it.
2026-10-05 07:48:58 +02:00
Marc-André Bombeck 169c7bdfe6 fix(coach): salvage Coach preferences field by field
parseCoachPrefs parsed the stored blob as a whole and returned the
defaults on any invalid field. A lookback value this version does not
know therefore dropped the metric exclusions with it. Each field now
falls back on its own, and the exclusion and cluster lists keep their
known entries, so drift narrows what the Coach reads instead of widening
it.

The deploy runbook's rollback section notes the one case this cannot
cover: v1.40.1 and earlier still parse the blob whole, so an account that
saved the new "Last year" lookback loses its exclusions there.
2026-10-05 07:48:37 +02:00
Marc-André Bombeck 1158ae9ffd fix(coach): keep earlier tables beyond the lookback limit out of the context
The earlier-tables block names each stored table with its window and row
count. The list was filtered by module and exclusion only, so a table
stored before the limit was set or narrowed still told the model how much
history it covered. It now answers to the same range test show_result
uses, and the history-reach guard checks both the filter and that the
call site passes the limit.
2026-10-05 07:47:31 +02:00
Marc-André Bombeck 0c1dd1e967 fix(coach): show the operator's central Codex when it answers
The operator's shared Codex is appended to the resolved chain but is never
a chain entry, so the Coach's provider select had no option for it and
showed its first option as the one answering. The answering provider now
appears as a disabled option, with a note that the operator manages the
connection.
2026-10-05 07:46:29 +02:00
Marc-André Bombeck 2a556b47c3 fix(coach): offer only providers that can answer and say when a switch does not take
The provider-chain summary marked every entry available, so the Coach's
provider select offered entries without a key or sign-in. Choosing one
saved it to the front of the chain, the resolver skipped it, and the
select jumped back without a word.

Availability now comes from the presence probe, which names every chain
type whose credential is present. After a switch the picker reads the
chain back and says so when the server still answers with another
provider.
2026-10-05 07:45:05 +02:00
Marc-André Bombeck a2ef2eec24 test(e2e): scan the sources rail with the rest of the Coach frame
The rail's switched-off rows now meet AA contrast, so the exclusion the
frame's accessibility scan carried for them is gone.
2026-10-05 07:32:01 +02:00
Marc-André Bombeck 359203d09a Merge remote-tracking branch 'origin/feat/coach-lookback-limit' into release/v1.40.2 2026-10-05 07:31:34 +02:00
Marc-André Bombeck 929c0ebaa4 Merge remote-tracking branch 'origin/main' into feat/coach-lookback-limit
# Conflicts:
#	src/lib/ai/coach/snapshot.ts
#	src/lib/ai/coach/tools/executor.ts
#	src/lib/insights/features.ts
2026-10-05 07:31:03 +02:00
Marc-André Bombeck 03c43ef70a Merge remote-tracking branch 'origin/feat/documents-procedure-filter' into release/v1.40.2 2026-10-05 07:17:17 +02:00
Marc-André Bombeck 98ac9c3d80 Merge remote-tracking branch 'origin/feat/dashboard-today-overview' into release/v1.40.2 2026-10-05 07:17:17 +02:00
Marc-André Bombeck 0d6bac8c5c Merge remote-tracking branch 'origin/feat/coach-answers' into release/v1.40.2
# Conflicts:
#	messages/de.json
#	messages/en.json
#	messages/es.json
#	messages/fr.json
#	messages/it.json
#	messages/ko.json
#	messages/pl.json
2026-10-05 07:16:55 +02:00
Marc-André Bombeck 57a889ef3c Merge remote-tracking branch 'origin/feat/coach-frame' into release/v1.40.2 2026-10-05 07:16:09 +02:00
Marc-André Bombeck 324e59914e Merge pull request #1161 from MBombeck/release/v1.40.1
chore(release): v1.40.1
2026-10-05 00:06:19 +02:00
Marc-André Bombeck 4769502a4b fix(backup): check the weekly copy's preview against the schema section by section
Taking the weekly preview from the writer dropped the schema check the
old scanner ran at the end, so a copy that violates the schema was
described as restorable. The collector now checks each section in its
JSON form as the writer shows it, an array section and a bulk table one
element at a time, plus the schema's one whole-document rule (a
canonical copy names every measurement by id). A copy that fails gets
no stored preview, and the preview route reads the copy itself, as it
did before. Nothing is kept beyond one element.

Measured on the preview memory test under --max-old-space-size=524:
held after the producer 3 MB with and without the check, raw peak
heapUsed 293 MB with it (335 MB without). The test now loads the
backup schema before its baseline: a module loaded once per process,
not memory that grows with the record.
2026-10-04 22:17:27 +02:00
Marc-André Bombeck 48ed149ef0 fix(import): leave out a marked Apple Health sample only when this account holds it
A sample carrying the HealthLog origin marker was always dropped from an
export import. After a move to a new instance without a backup, the
export is how the mirrored values come back, and every one of them was
silently left out. A marked sample now counts as written by HealthLog
only when its HKExternalUUID names a row of this account of the same
kind, deleted rows included; a marked cycle sample only when the
account holds a day-log on its day. Every other marked sample is
imported, and still meets the manual-value match. A correlation's own
HKExternalUUID now covers records that carry none.
2026-10-04 22:15:48 +02:00
Marc-André Bombeck 090e3d9a7e perf(measurements): weigh pulse days with window functions over one scan
The day weight joined its source to an hour grouping of itself. With
stale or missing planner statistics, as after a new account imports a
year of pulse below the autoanalyze threshold, the planner ran that
join as a nested loop and the all-time pulse aggregate ran into the
60 s statement timeout. The weight is now two window passes over one
scan: the readings in a row's hour, and one marker per hour summed over
the day for the hour count. The weights are unchanged.

A new integration test seeds over 100k pulse rows with autovacuum off
and no ANALYZE, bounds the all-time reader and a zoned per-source mean
well under the timeout, and compares every row's weight against the
earlier self-join after ANALYZE. The ANALYZE the metric-series snapshot
test needed for the same trap is gone.
2026-10-04 22:14:14 +02:00
Marc-André Bombeck 0219a85e92 feat(documents): filter the archive by procedure or surgery
The vault's filter row gains a procedure facet beside the condition
facet. It lists the record's procedures and surgeries that hold at least
one live document, headed the way the visits page heads them (the
reason, else the practice, else the kind) with the body site and date
beneath, and narrows the list through the existing `encounterId` filter.
Same control, placement and clear behaviour as the condition facet; the
choice rides the URL as `?encounter=`, and an upload dropped into the
filtered view is filed against the procedure.

The usage read publishes the choices as `linkedProcedures` (additive),
decrypting only the label columns, and returns none when a sharing
grant does not cover the visits section.

On a phone an active facet now gives up label width before the search
field does, and the search keeps room for its icon and padding.
2026-10-04 21:59:22 +02:00
Marc-André Bombeck 3681b23d30 test(e2e): mount every overview section before asserting none paints
The AI-optional overview and account journeys asserted zero error cards,
Coach hand-offs and briefings without scrolling the deferred sections
into view, so the sections below the first three never mounted and the
zero counts held whatever they would paint. Both journeys now reveal
every section and wait for the reads those sections fire to land;
waiting on networkidle again resolves at once, because the page reached
that state before.
2026-10-04 21:36:25 +02:00
Marc-André Bombeck 2bbcce73e4 docs: name the memory cap on small hosts and the shared connection pool
Getting started names the APP_MEMORY_LIMIT default and how to lower it
on a 2 GB host; the scaling guide says that web and worker share one
pool in the bundled single-container setup. The rollup comment names
migration 0372, which carries the hourly-mean statistic.
2026-10-04 21:25:28 +02:00
Marc-André Bombeck da56177290 fix(backup): take an interrupted account last for one run only
An account whose last backup attempt never came back was kept behind
every other account for as long as its attempt stayed open. A pass that
regularly stops on its time budget never reached it, so it never got a
copy again. It is now held back only until a later run has started on
another account; if its record kills the process again, its attempt is
the newest once more and it goes last again. A crash loop still leaves
the other accounts their copies, and the account itself is attempted at
least every second run.
2026-10-04 21:21:32 +02:00
Marc-André Bombeck 4261139dfa fix(backup): run the restore drill as a locked long pass
The drill now reads every account's newest off-host object but still ran
on the default fifteen-minute expiry, without a lock and with two
retries, so a large instance could see it killed, run beside itself, and
page every failed account three times. It now carries a four-hour expiry,
stops between accounts on its budget and reports the objects it did not
reach, holds a pass lock at the binding, and is not retried.
2026-10-04 21:19:32 +02:00
Marc-André Bombeck 4be7109a2b fix(medications): refetch an invalidated prefetch on mount
A hover prefetch excused the mount refetch even after a dose logged
elsewhere had invalidated the medication reads, so the page showed the
compliance from before the dose. An invalidated entry now always
refetches.
2026-10-04 21:13:28 +02:00
Marc-André Bombeck 5e5e387fab chore(release): v1.40.1 2026-10-04 20:55:14 +02:00
Marc-André Bombeck dc7061634e Merge pull request #1152 from MBombeck/dependabot/npm_and_yarn/p-limit-7.3.3
chore(deps): bump p-limit from 7.3.1 to 7.3.3
2026-10-04 20:52:41 +02:00
Marc-André Bombeck 92b4a9c103 Merge pull request #1149 from MBombeck/dependabot/npm_and_yarn/testcontainers-12.2.0
chore(deps-dev): bump testcontainers from 12.1.0 to 12.2.0
2026-10-04 20:52:26 +02:00
Marc-André Bombeck 31b7fd0a45 Merge pull request #1148 from MBombeck/dependabot/npm_and_yarn/zod-openapi-6.0.2
chore(deps): bump zod-openapi from 6.0.1 to 6.0.2
2026-10-04 20:52:11 +02:00
Marc-André Bombeck 10e34bcab6 Merge pull request #1150 from MBombeck/dependabot/npm_and_yarn/eslint-config-next-16.3.8
chore(deps-dev): bump eslint-config-next from 16.3.6 to 16.3.8
2026-10-04 20:51:56 +02:00
Marc-André Bombeck 5e267e2ddf Merge pull request #1151 from MBombeck/dependabot/npm_and_yarn/next-16.3.8
chore(deps): bump next from 16.3.6 to 16.3.8
2026-10-04 20:51:40 +02:00
Marc-André Bombeck d23595f924 Merge pull request #1153 from MBombeck/perf/mcp-metrics-slim
perf: single-metric MCP reads from the metric's own rows; load the backup schema on first use
2026-10-04 20:51:28 +02:00
Marc-André Bombeck 393ac955f6 Make the Coach lookback a limit on every read
The saved Coach window only seeded the snapshot and each tool's default.
A tool could still read back to all time, the availability probe reported
counts and means for history outside the window, and several blocks read
fixed windows of their own (labs 12 months, correlations 180 days, the
coarse tail, the all-time extremes) whatever the setting said.

coachPrefs.defaultWindow is now enforced as a limit through one module,
history-reach.ts: the turn context clamps the client window, the snapshot
clamps its window and gives every fixed-window block either the shorter
window or, when the block's own window cannot fit, leaves it out. Every
retrieval tool clamps its window, an earlier period or a stored table that
reaches past the limit answers outside_reach, and the probe reads only
inside the limit and names older history as outside_reach without any
figure. Follow-up chips that would read past the limit are not offered.
The default (allTime) is no limit and reads as before. MCP clients pass no
limit and keep their own window arguments.

Adds the twelve-month option, rewrites the picker text to state what is
read with the numbers the readers use, shows the same options in the
managed-profile settings, counts cluster members with a singular, and
drops the opacity on switched-off rows that put their text below WCAG AA.
2026-10-04 20:45:21 +02:00
Marc-André Bombeck 59311fe401 Merge remote-tracking branch 'origin/main' into perf/mcp-metrics-slim 2026-10-04 20:08:25 +02:00
Marc-André Bombeck d07f5796d7 Seed the demo Coach answer with valid metric tokens, steps and token meta 2026-10-04 20:02:49 +02:00
Marc-André Bombeck d1849eed16 Measure the Coach answer layout at 1440 and 390 px 2026-10-04 20:02:49 +02:00
Marc-André Bombeck a91e1bf0a7 Give each Coach answer one action row and keep its chips in its column
Under an answer: copy, read aloud, try again and the time as text on the
left; tokens and model on the right, on one line down to 390 px. The
thumbs leave the web (the feedback route stays for the native client),
and so does the "What I'm looking at" disclosure: the method line and
the tables the answer read move into the steps list, and an older
message without steps lists the areas it drew on, never a raw key.

Remember becomes a bookmark icon in the question's row and confirms in
place with a toast. Follow-up chips render inside the latest answer's
column at its text size. The answer column takes the full width below
`sm` and a fixed 80 % above, so nothing moves sideways as a reply
streams. A round button fades in when the thread is scrolled away from
the end and brings it back.
2026-10-04 20:02:48 +02:00
Marc-André Bombeck 5cfacba16a feat(dashboard): add a Today overview to the hero
The hero led with the first sentence of the cached briefing, which was
often a greeting ("Good morning.") while the sentence with content was
never shown. Without an AI provider it fell back to "Your health score
today is N.", which the hero then removed because the ring already
shows the number, leaving a ring and "Nothing needs your attention".

The daily digest now publishes the lead resolved on the server and a
short list of facts about the day:

- lead: the reaction line or the first briefing sentence that is not a
  greeting and does not repeat the score while AI text is available,
  otherwise a deterministic sentence about the strongest signal (a vital
  outside its personal range, a night an hour off the usual, vitals in
  range, last night). A fact the lead was built from leaves the list.
- today: up to five statements in priority order (Rest Mode, doses taken
  today, an appointment today or tomorrow that is not already on the
  rail, last night's sleep against the usual, vitals against their
  personal range, cycle day). Module-gated on the server, never padded,
  never asking for anything. A phone shows the first four.
- restMode: passed through while an illness episode is active.
- score.steadyWeeks: how long the score has held, read off the stored
  daily scores, shown under the ring in place of a delta.

briefingLead skips greetings and score sentences the same way, so the
morning push improves with it. Visit times are rendered in the profile
timezone and hour-cycle preference; the cycle day comes from the same
verdict the cycle page uses. The ring, the rail and the charts are
unchanged. OpenAPI regenerated; additive fields only.
2026-10-04 20:00:18 +02:00
Marc-André Bombeck b8d31f945d test(e2e): cover the Coach page frame at 1440, 1280 and 390
Measures that the thread and composer keep the same width with the panel
open and closed, that the choice survives a reload, Escape and focus
return for the panel, the sheet and the settings overlay, rename and
delete with undo from the row menu, the settings deep link, and axe on the
panel and the overlay in both themes. Screenshots are attached to the
report.
2026-10-04 20:00:07 +02:00
Marc-André Bombeck 12153fe143 feat(coach): move conversations into a collapsible right panel
The Coach page gets a conversations panel on the right of the thread. From
1280 px it docks beside the thread and slides open and shut; the reading
column keeps its width either way and only its centring moves. It is open
on a first visit and remembers the last choice per device. Below 1280 px it
is a sheet from the right. The toggle sits at the trailing edge of the top
bar, through a small page-owned slot the top bar now renders.

The panel lists every conversation grouped by recency, with a row menu to
rename in place (Enter saves, Escape cancels without closing the panel) and
delete with the existing undo toast. The undo window now survives the sheet
closing. New chat is the round button at the panel's bottom right, and
picking or starting a conversation keeps ?c= in the URL.

The gear in the panel header opens quick settings: a popover from md up, a
bottom sheet on a phone. It switches the answering provider (chain reordered
through the existing route), the model and reasoning level where the person
owns them, and shows what the Coach can see. Keys, the Codex sign-in and the
fallback chain stay in Settings > AI. The drawer's gear opens the same
overlay. The composer's + menu is gone.

Settings > Coach links to /coach?settings=data, which opens the overlay on
what the Coach can see instead of a rail that no longer exists.
2026-10-04 20:00:07 +02:00
dependabot[bot] 8fd58e9824 chore(deps): bump next from 16.3.6 to 16.3.8
Bumps [next](https://github.com/vercel/next.js) from 16.3.6 to 16.3.8.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/compare/v16.3.6...v16.3.8)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 16.3.8
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-04 17:33:27 +00:00
dependabot[bot] c064210a34 chore(deps): bump p-limit from 7.3.1 to 7.3.3
Bumps [p-limit](https://github.com/sindresorhus/p-limit) from 7.3.1 to 7.3.3.
- [Release notes](https://github.com/sindresorhus/p-limit/releases)
- [Commits](https://github.com/sindresorhus/p-limit/compare/v7.3.1...v7.3.3)

---
updated-dependencies:
- dependency-name: p-limit
  dependency-version: 7.3.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-04 17:33:00 +00:00
dependabot[bot] ddb5c6462a chore(deps-dev): bump eslint-config-next from 16.3.6 to 16.3.8
Bumps [eslint-config-next](https://github.com/vercel/next.js/tree/HEAD/packages/eslint-config-next) from 16.3.6 to 16.3.8.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/commits/v16.3.8/packages/eslint-config-next)

---
updated-dependencies:
- dependency-name: eslint-config-next
  dependency-version: 16.3.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-04 17:32:08 +00:00
dependabot[bot] 10d5b7334e chore(deps): bump zod-openapi from 6.0.1 to 6.0.2
Bumps [zod-openapi](https://github.com/samchungy/zod-openapi) from 6.0.1 to 6.0.2.
- [Release notes](https://github.com/samchungy/zod-openapi/releases)
- [Changelog](https://github.com/samchungy/zod-openapi/blob/master/CHANGELOG.md)
- [Commits](https://github.com/samchungy/zod-openapi/compare/zod-openapi@6.0.1...zod-openapi@6.0.2)

---
updated-dependencies:
- dependency-name: zod-openapi
  dependency-version: 6.0.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-04 17:31:50 +00:00
dependabot[bot] d64cbbaebf chore(deps-dev): bump testcontainers from 12.1.0 to 12.2.0
Bumps [testcontainers](https://github.com/testcontainers/testcontainers-node) from 12.1.0 to 12.2.0.
- [Release notes](https://github.com/testcontainers/testcontainers-node/releases)
- [Commits](https://github.com/testcontainers/testcontainers-node/compare/v12.1.0...v12.2.0)

---
updated-dependencies:
- dependency-name: testcontainers
  dependency-version: 12.2.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-04 17:31:43 +00:00
Marc-André Bombeck 3be83eee22 Merge pull request #1155 from MBombeck/test/zone-offset-reference-cache
test(tz): reuse one reference formatter per zone in the offset parity test
2026-10-04 19:29:19 +02:00
Marc-André Bombeck 016278ba24 test(mcp): analyze the seeded rows before the metric-series golden test
The first case spent 14 s per full-snapshot build in the all-time pulse
aggregate, planned against a table with no statistics, until autovacuum
analyzed it; on a loaded runner that took it past its 60 s budget. Analyze
measurements and rollups after seeding, as a production table would be.
The cases and the comparison they make are unchanged.
2026-10-04 19:21:01 +02:00
Marc-André Bombeck 528ecfbcdc test(tz): reuse one reference formatter per zone in the offset parity test
The parity test built a fresh Intl.DateTimeFormat for each of ~36k
comparisons and crossed the 5 s timeout on CI runners. One formatter per
zone halves its time; it also gets an explicit 20 s budget, since it is
meant to be exhaustive.
2026-10-04 19:07:54 +02:00
Marc-André Bombeck 13ea849188 perf(backup): load the backup payload schema on first use
backupPayloadSchema is built when validations/backup.ts is evaluated and
holds about 12 MB of heap. The restore job, the stored-backup readers and
the export writer import that module, and they sit on the boot path, so
every server process built the schema at start whether or not it ever
touched a backup.

The schema version, the compatibility check and the per-section summary
move to validations/backup-summary.ts, which never builds the schema. The
call sites that validate a file (upload, restore, the summary and download
routes, and the streamed reader's element check) load backup.ts with a
dynamic import at that moment; everything else takes only types. The
OpenAPI registry keeps its static import, since only the spec generator
loads it.

After warm-up on a production build under --max-old-space-size=524, the
used heap drops by about 29 MB, and the schema no longer appears in a heap
snapshot. A structural test refuses a new static value import of the
module outside the registry.
2026-10-04 18:23:14 +02:00
Marc-André Bombeck 546e67475f perf(mcp): build single-metric reads from the metric's own rows
get_metric_series (and get_metrics, the metric resources and the review
prompts, which fan out over it) answered with one section of a Coach
snapshot, but built the whole snapshot to get it: the all-type feature
extraction, the derived wellness layer, trajectory, correlations, memory,
GLP-1, cycle, illness, labs and visits. On a seeded account with about
215k measurements a resting heart rate read ran 208 SQL statements and
blocked the event loop for 175 ms to return under 2 KB.

The MCP surface now asks the executor for a source snapshot. It runs the
same prelude (prefs, module gates, admitted sources, cutoffs, now shared in
snapshot-prelude.ts) and the same block builders over the requested
source's reads only. The core clinical aggregates come from extractFeatures
scoped to the one block, whose bulk read keeps its all-type cap so the rows
a block sees do not change. A section large enough for the full builder's
prompt-budget pass to trim, and the environment cluster, go to the full
builder, so their results are the old ones by construction.

The integration test compares the tool's serialised result with the full
builder's section and grounding for nine sources over four windows, the
get_metrics batch and the metric resource, on a seeded account dense enough
to put the feature row cap into play.
2026-10-04 18:17:24 +02:00
Marc-André Bombeck 1cb50ed21d Merge pull request #1144 from MBombeck/fix/restore-key-probe
fix(backup): restore opens legacy values, drill checks every account, backups hold less memory
2026-10-04 17:44:57 +02:00
Marc-André Bombeck 72ca843fd5 Merge pull request #1147 from MBombeck/perf/dashboard-server
perf(server): one Prisma client, indexed coverage probe, memoised timezone offsets
2026-10-04 17:33:57 +02:00
Marc-André Bombeck 77fece0fa5 Merge pull request #1146 from MBombeck/chore/app-memory-default
chore(compose): default the app to 1536m so Node gets a 792 MB heap
2026-10-04 17:33:54 +02:00
Marc-André Bombeck 006679ed9e Merge pull request #1145 from MBombeck/perf/dashboard-client
perf: faster charts and insights, no sidebar scrollbar flash, Umami events delivered
2026-10-04 17:33:51 +02:00
Marc-André Bombeck 92f17c8ca4 Merge pull request #1140 from MBombeck/ready/pr-1131
fix(import): leave out Apple Health samples HealthLog wrote itself
2026-10-04 17:33:47 +02:00
Marc-André Bombeck 45fafdf096 Merge pull request #1138 from MBombeck/feat/pulse-hourly-mean-complete
fix(pulse): a day of pulse is the mean of its hours' means, everywhere
2026-10-04 17:33:43 +02:00
Marc-André Bombeck 6920694912 chore(compose): give the app 1536m by default so Node gets a 792 MB heap
Node sizes its heap from the container's memory cap. The 1g default gave
524 MB, which a long-used account fills in normal operation: on a live
instance 490 to 507 MB stayed live after a full GC, garbage collection
stalled requests for up to 8.5 s, and the process ran out of heap 26 times
in a week, taking the weekly backup with it. 1536m gives 792 MB. The
example env and the backup runbook say how to lower it on a small host.
2026-10-04 16:38:10 +02:00
Marc-André Bombeck 6c0a606bf3 fix(a11y): give the loading score and vitals grids a role to name
Both grids carry an aria-label while their data loads, on a plain div,
which axe reports as aria-prohibited-attr: the label has no role to
name. A scan that lands while the scores strip is still loading fails on
it. The loading grids now take role=status, the role a loading region
has and which already implies the polite live region; the loaded vitals
grid carries neither.
2026-10-04 16:24:37 +02:00
Marc-André Bombeck 4916a29bbe perf(insights): mount below-the-fold overview sections near the viewport
Entering the Insights overview fired every section's reads at once, about
two dozen requests on a seeded account, and the server worked through
them in a queue: the hero and the first sections waited behind trends,
the period review, cycle, signals, rhythm events, health status,
breathing, labs and ECG, all far below the fold.

The first three sections in the account's own order still mount with
the page. Every later one renders a 1 px sentinel until it comes within
400 px of the visible area of the shell's scroll container, then mounts
and fetches; once mounted it stays. Measured on a seeded account under a
4x CPU slowdown: 24 -> 13 requests on entry, the entry network span
1.3-1.8 s -> 0.5-0.9 s, LCP about 1.35 s -> 0.9 s, blocking time about
550 ms -> 200 ms. Scrolling to the end still loads all 25 and renders
all ten sections.

Specs that assert on, measure or scan the lower sections scroll them in
first through a shared helper, so their coverage is unchanged.
2026-10-04 16:24:37 +02:00
Marc-André Bombeck fa48110875 fix(nav): mark the scroll edge when the sidebar list overflows
On a short window (around 785 px and below) the nav list is taller than
the room between the logo band and the footer group, so it scrolls. With
nothing marking the edge, the last visible entry was cut off right at
the Collapse row and read as the footer covering it; macOS hides the
scrollbar that would have said otherwise.

While the list overflows, the footer group draws the same hairline the
user section does. A ResizeObserver on the nav and its list keeps the
state current as the window or the entries change; with room to spare
the rail is unchanged. The e2e spec checks the edge, that the last entry
scrolls fully clear of the footer, and that a tall window draws no edge.
2026-10-04 16:24:37 +02:00
Marc-André Bombeck 194712c916 Merge pull request #1143 from MBombeck/fix/rest-mode-date
fix(insights): show the Rest Mode onset as a date
2026-10-04 16:15:03 +02:00
Marc-André Bombeck ef14f539de Merge pull request #1142 from MBombeck/ready/pr-1134
fix(series): follow the source priority ladder in the blood-pressure series
2026-10-04 16:15:00 +02:00
Marc-André Bombeck 63a5304e43 Merge pull request #1141 from MBombeck/ready/pr-1132
feat(labs): let the lab list's range bar use a wide card
2026-10-04 16:14:56 +02:00
Marc-André Bombeck dc9b0e3936 test(import): read the note's text without a tag-stripping replace 2026-10-04 16:14:47 +02:00
Marc-André Bombeck 28046f05f7 test(measurements): group the hourly-mean fake once instead of per day
The in-memory day-aggregate fake re-filtered every row for every day,
converting each timestamp to the profile timezone again, so a 1000-day
series took about five seconds and the graded pulse-status test hit its
timeout. It now groups by day and segment in one pass (4.8 s to 85 ms).
2026-10-04 16:14:10 +02:00
Marc-André Bombeck 23961d2280 perf(medications): stop re-sending the read a nav prefetch just made
The medications list and the compliance summary refetch on every mount,
so a take or skip logged on another device shows on return (#316). The
nav link's hover / touch / focus intent and the route-commit preload
prefetch both reads too, so every visit through a link sent each of
them twice: the prefetch, then the identical request from the mount a
few hundred milliseconds after the first answer landed.

The mount now skips its refetch only when the cached data answers a
prefetch that went to the network for this visit: within the last 10 s,
and since the route last left /medications. A direct load, a return
with an older entry, or a quick return whose prefetch found the entry
still fresh keep the refetch on mount.
2026-10-04 16:12:04 +02:00
Marc-André Bombeck c08e049a05 perf(rollups): share an in-flight coverage probe between concurrent readers
A Coach snapshot, a derived-metric batch or the Insights page fans out
into a dozen readers that each probe the same account's rollup coverage
at once. In production one MCP get_metrics call held 59 of these probes
open on the database together, each taking about 320 ms under that
contention, and the same burst repeated every 15 minutes.

Concurrent probes for one account now join the query already running.
Nothing is kept after it settles, each caller gets its own map, and a
measurement write drops the in-flight entry so a probe that starts after
a write always reads afresh. The registry lives on globalThis so every
server bundle shares it.
2026-10-04 16:04:04 +02:00
Marc-André Bombeck 3e08fd0e68 fix(documents): stop queueing a thumbnail that cannot be rendered on every boot
A document whose preview render fails for good (a PDF whose first page
renders blank) was queued by the boot-time backfill, refused, and queued
again at the next boot, without end.

The thumbnail job now keeps the failure with the document
(document_thumbnail_failures, migration 0374): the reason, the attempts
since the last success and when the newest failed. The backfill, both the
boot discovery and the per-account pass, leaves a document out after one
deterministic refusal (raster-failed, empty-render, pixel-cap) or three of
any other kind, until the document changes. A direct enqueue still renders
it, and a preview that is made clears the record.
2026-10-04 15:56:56 +02:00
Marc-André Bombeck f18e6ed34b fix(backup): notice a backup run the process died under, and take its account last
A weekly or nightly backup job whose process died (a restart, a
container out of memory) stayed active until its two- or four-hour
expiry, and its retry walked the accounts in the same order: the account
that killed it has the oldest copy, so it led again, and every account
after it went without a copy for as long as that record stayed too
large.

Both passes now send with a five-minute pg-boss heartbeat, so a dead run
fails within minutes and its retry picks it up. Each pass records when it
started and finished every account (backup_pass_attempts, migration
0373); an account whose last attempt never finished goes behind all the
others. The backups page shows when the run in progress started and names
an account a run died under, for the weekly and the off-host card, and a
heartbeat timeout reads as what it means.
2026-10-04 15:56:56 +02:00
Marc-André Bombeck d55e329c48 perf(backup): take the weekly copy's preview from the writer, not a second parse
Since v1.39.6 the preview scanner parsed the JSON on its way into the
pieces, kept every section but the three bulk tables, and validated the
whole document at the end: a second copy of the record beside the
writer's own, inside the weekly job. On an account with a document vault
that is most of the record.

The writer now shows each section and each bulk row to an observer just
before writing it. The preview collects key uses from that and takes its
counts from the writer's own FullBackupCounts; nothing is parsed or kept.
An upload hands over the summary and key uses it has already validated.
The round trip pins the writer's counts and key uses to a full read of
the copy on an account with a row in every model, and a memory test holds
what the pass keeps once the producer is done.

Measured on 70,000 measurements, 3,000 mood entries and 40 one-megabyte
documents under --max-old-space-size=524: held after the producer
56 MB before, 3 MB after; peak heapUsed 398 MB before, 334 MB after.
2026-10-04 15:56:56 +02:00
Marc-André Bombeck 5345c8be1e fix(backup): check every account of the newest date in the restore drill
The drill read only the alphabetically last object of the newest date, so
one account stood in for all of them. It now checks every object of that
date one at a time, records a failure against the account it belongs to,
keeps going, and pages once per failing object with its key and how many
accounts were checked.
2026-10-04 15:56:55 +02:00
Marc-André Bombeck f67006783c fix(backup): open legacy text ciphertext as a string and probe only counted sections
A text column written before key ids existed holds the bare base64 of
nonce, tag and ciphertext. The key check read such a value as an encoded
Bytes column, decoded it once too often, and accused the v1 key of not
opening a copy it opens. The instance's stored AI key has exactly that
shape and is the shortest v1 value in every disaster-recovery copy, so it
was picked as the probe and refused every restore of an account with v1
values, even with the instance settings left out of the verdict.

A legacy value now reads as a string unless its decoded head is base64
text. Samples are kept per section and only the sections the verdict
counts are probed; a key is unreadable when none of its probes opens.
Binary values open with the label their column is sealed under, taken
from the encrypted-column registry, and are not probed when no label is
known. A preview stored by an earlier release is still read, and its
sample's layout is derived again from the value.
2026-10-04 15:56:55 +02:00
Marc-André Bombeck 76e621b067 perf(tz): memoise zone offsets per hour for wall-clock reads
Day keys and wall-clock fields are computed per row in the analytics,
digest and personal-record loops, and each call ran
Intl.DateTimeFormat#formatToParts plus a resolvedOptions() allocation
to re-validate the zone. In a CPU profile of an Insights page load the
zone helpers were 17-19% of the busy time on the request thread.

Probe the offset once per UTC hour at both ends of the hour and derive
the wall clock arithmetically; an hour that contains a transition, an
instant outside 1971-2199 or an invalid date keeps the formatter path.
Zone validity is memoised per name. userDayKey drops from 9.3 to 1.5 us
per call, wallClockInTz from 6.4 to 0.5 us; a parity test checks the
result against Intl around every 2026 transition in ten zones.
2026-10-04 15:53:48 +02:00
Marc-André Bombeck b25df614f9 fix(insights): show the Rest Mode onset as a date, not a raw timestamp
The health score card passed the episode onset, an ISO instant, straight
into its sentence, so it read "Rest Mode active since
2025-08-04T09:55:00.000Z". It now shows the day that instant falls on in
the profile timezone, in the user's date format. The test that pinned the
raw value now pins the formatted day.
2026-10-04 15:36:04 +02:00
Marc-André Bombeck be69e409af Merge pull request #1139 from MBombeck/docs/readme-screenshots-1400
docs: refresh README screenshots from the 1.40.0 demo
2026-10-04 15:31:02 +02:00
Marc-André Bombeck 4ab2a8be38 perf(rollups): probe coverage with a loose index scan
probeRollupCoverage runs ahead of the dashboard snapshot, the analytics
slices and the comprehensive insights. It read every live row of the
account for SELECT DISTINCT type and counted every DAY bucket per type,
which the planner served with a sequential scan of measurement_rollups.
Walk the distinct types with a recursive CTE along the live index and
test coverage with EXISTS. On a copy of a long-lived account the probe
drops from 24-50 ms to under 2 ms and returns the same map; an
integration test keeps the old query as the oracle.
2026-10-04 15:29:02 +02:00
Marc-André Bombeck 5cbb080262 fix(db): share one Prisma client across the server bundles
A production build loads src/lib/db.ts once per server bundle, and the
client was only parked on globalThis outside production. The running
process held three clients: about 28 MB of query-compiler state each on
a heap capped near 520 MB, and three pg pools each sized to the full
per-process connection budget. Park the client on globalThis in every
environment so each copy of the module resolves the same one.
2026-10-04 15:29:01 +02:00
Marc-André Bombeck 2c1369f01b perf(charts): measure chart text outside <body>
Recharts sizes every tick and label by writing it into one off-screen
span and reading getBoundingClientRect(). Under <body> each read forced
a document-wide style recalc, because the stylesheet's descendant-subject
:has() rules leave Chromium no way to scope the invalidation. A seeded
dashboard made 149 such reads per cold load at about 2.8 ms each, about
1.8 s of main-thread time under a 4x CPU slowdown.

The chart runtime now parks that span in a zero-size, contain: strict
host under <html>, which Recharts finds by id and keeps using. Each read
drops to about 0.01 ms; the dashboard's total blocking time under the
same slowdown falls from about 2.5 s to about 0.75 s. The host copies
<body>'s classes, where the app font is set, so every string measures
exactly as before; an e2e spec checks that parity on the drawn labels
and that the host survives a client-side round trip.
2026-10-04 15:28:28 +02:00
Marc-André Bombeck 1b1da652d3 fix(monitoring): route Umami events to the endpoint the tracker was built with
The tracker posts to `${data-host-url}${collect path}`, and the collect
path is compiled into the operator's Umami build: /api/send by default,
anything else when the instance sets COLLECT_API_ENDPOINT. The tag
pointed data-host-url at the app origin and the proxy listened only on
/api/send, so a renamed endpoint sent every page view and event to an
app path that does not exist and got a full 404 page back each time.

Point data-host-url at /api/monitoring/umami and answer every path under
it with one proxy route. The route reads the collect path from the
configured tracker (cached for an hour), forwards only that path to the
Umami host, and answers anything else, or an unreadable tracker, with an
empty response. The admin test event posts to the same learnt path. The
send-URL resolver lives in one module instead of two copies.
2026-10-04 15:13:52 +02:00
Marc-André Bombeck 2e150e97cf fix(nav): stop the sidebar flashing scrollbars while it expands
The rail animates its width from w-16 to w-64, and the labels laid out
against the growing width: every row overran the nav and multi-word
labels wrapped, so the nav's overflow-y-auto painted a vertical and a
horizontal scrollbar for the length of the transition.

Lay the expanded column out at its final width from the first frame and
let the rail clip it. The final layout is unchanged; the column fills
the expanded rail exactly. A unit test pins the structure and an e2e
spec samples the nav on every frame of a real expand and collapse.
2026-10-04 15:08:42 +02:00
Marc-André Bombeck 2ce9d4651d docs: refresh README screenshots from the 1.40.0 demo
Recapture Insights, resting heart rate, Medications and Coach at the
same 2552x1308 frame. The resting heart rate shot no longer shows the
raw metric enum in the chart legend. Images are palette-quantised, about
a fifth of their previous size.
2026-10-04 14:56:03 +02:00
Marc-André Bombeck 57c7cf8be9 chore(db): number the pulse mean migration after 0371 2026-10-04 14:55:03 +02:00
Marc-André Bombeck 13b8920dd5 Merge remote-tracking branch 'origin/main' into feat/pulse-hourly-mean-complete 2026-10-04 14:54:53 +02:00
Marc-André Bombeck bc0d9f915f test(import): answer the MANUAL-type lookup in the import mocks 2026-10-04 14:49:07 +02:00
Marc-André Bombeck 4cad43e4d5 Merge pull request #1137 from MBombeck/fix/favicon-ico
fix(ui): transparent favicon.ico with the current heart
2026-10-04 14:45:24 +02:00
Marc-André Bombeck 67e8e7c4f2 fix(import): pluralise the note on records HealthLog wrote itself
The note had one form per locale, so a single left-out record read as a
plural. It now resolves One, Few and Other through tCount like the other
counted strings, with the singular in every locale and the Polish few form.
2026-10-04 14:34:42 +02:00
Marc-André Bombeck 4dabc83513 fix(import): match HealthLog's own samples by row id and ask for mirrors per type
A sample the app wrote before the origin marker existed still carries the
HealthLog row id as HKExternalUUID. A hit on one of the account's rows of
the same kind now leaves it out exactly, for Withings and import mirrors as
well as manual ones; either id of a blood pressure pair covers both halves,
since the app stamps both samples of a reading with one id.

The manual-mirror lookup read one OR clause per row on every batch, even
for an account without a single MANUAL row. The types that hold MANUAL rows
are now read once per import; a batch asks nothing for any other type, and
one time window per type for those.

Cycle samples carry the marker too and are now left out like the rest, and
a sample the export repeats (a correlation's records also stand on their
own) is counted once.
2026-10-04 14:34:38 +02:00
Marc-André Bombeck 8add851fb7 docs(import): say what the origin marker is for and who reads it
The comment claimed the app's own sync filters by the marker. It does not:
the app's echo check is HKExternalUUID plus the sample's authoring source
being the app itself, and the marker exists for the deletion path, where
the source is not visible. Say so, and say why the export import reads the
marker and the row id instead.
2026-10-04 14:34:37 +02:00
Marc-André Bombeck 29798a76e3 fix(labs): keep the trend column as wide as its sparkline on a wide list
The wide tier let the trend column grow to 8rem while the sparkline it
holds is a fixed 72px glyph, so at 1920 px an empty 56 px strip opened
between the sparkline and the chevron. The column now stays 72px in both
tiers; the extra width goes to the range bar and the name, as before.

The wide-list spec reads the resolved grid tracks and asserts the trend
track is 72px at every width it covers.
2026-10-04 14:28:04 +02:00
Marc-André Bombeck d1ec6715d9 fix(series): pick one source per day for both halves of a blood-pressure reading
The systolic and diastolic reads each took the ladder's source per day on
their own. Whenever a source held only half of a reading on a day (a deleted
diastolic, an orphaned sample, a sub-floor systolic), the two picks diverged
and the pairing joined one source's systolic to another source's diastolic.
A sub-floor systolic could also claim a day and then contribute nothing,
leaving the day empty although a lower-ranked source had a valid reading.

The source is now picked per day from the systolic rows that pass the floor,
both halves are read from it in one statement, and a pair is only made
within one source, which also covers a reading that straddles midnight.
2026-10-04 14:14:22 +02:00
Marc-André Bombeck 0ae50849d8 Merge remote-tracking branch 'origin/main' into ready/pr-1132 2026-10-04 14:08:29 +02:00
Marc-André Bombeck fbd639d9f1 Merge remote-tracking branch 'origin/main' into ready/pr-1131 2026-10-04 14:08:27 +02:00
Marc-André Bombeck b088e31a0f Merge remote-tracking branch 'origin/main' into ready/pr-1134 2026-10-04 14:08:26 +02:00
Marc-André Bombeck 66be88287f fix(ui): replace the white-backed favicon.ico with the current transparent heart
src/app/favicon.ico was still the filled heart from the first release on a
solid white square. Next serves it next to favicon.svg, and browsers that
pick the ICO (Safari, bookmarks, history, some tab states) showed the old
icon on a white slab. It is now the current logo at 16, 32 and 48 px with a
transparent background.
2026-10-04 14:05:44 +02:00
Marc-André Bombeck c2a3a26537 Merge pull request #1136 from MBombeck/release/v1.40.0
chore(release): v1.40.0
2026-10-04 14:04:56 +02:00
Marc-André Bombeck dee00613d8 Merge remote-tracking branch 'origin/main' into release/v1.40.0 2026-10-04 12:23:40 +02:00
Marc-André Bombeck 32de7ecf37 Merge pull request #1135 from MBombeck/fix/cycle-backup-and-med-put
fix(backup): carry encrypted free text readable in portable backups
2026-10-04 12:23:35 +02:00
Marc-André Bombeck 06f210b56f Guard every pulse mean reader behind the day-mean helper
A structural test lists every file that takes a database or in-memory mean
over measurement values and names pulse, and requires each to use the shared
statistic, hand the type to a fold that does, or state why it never averages
pulse readings. A new plain mean over pulse, or a reader that drops the type,
fails it.
2026-10-04 11:39:33 +02:00
Marc-André Bombeck 8f730484e0 Average pulse by day in the comparison snapshot and Coach inventory
The insights comparison snapshot took its current and baseline pulse figures
from a reading AVG, and the Coach's data inventory told the model a reading
mean of the whole pulse history. Both now read the mean of the user's local
days, each the mean of its hours' means, through the day-mean helper. Every
other type keeps its aggregate.
2026-10-04 11:37:57 +02:00
Marc-André Bombeck 11e35a6ba1 Average pulse by day in the insights, Coach and report trend
The feature extraction, the signals of the day, the status cards, the graded
series, the Coach snapshot, the mood correlations and the report's trend arrow
each still averaged pulse over its readings, so a dense workout hour decided
the day and a workout day the window. They now read a pulse day as the mean of
its hours' means and a window as the mean of its days, through the day-mean
helper. Counts, extremes and spreads stay over every reading; every other type
is unchanged.
2026-10-04 11:33:45 +02:00
Marc-André Bombeck db524ded98 Average pulse by day in the doctor report, correlations and baselines
The doctor report's pulse average and day points, the correlation channels,
the illness correlation, the personal baseline and the Coach's tiered context
each folded pulse readings into a day by plain mean. They now take the day as
the mean of its local hours' means and a window as the mean of its days, in
the zone each reader buckets by. The day aggregates carry the weighted sums for
an hourly-mean type, so every caller reads one day value. Every other type is
unchanged.
2026-10-04 11:33:42 +02:00
Marc-André Bombeck 257d3ef6a5 docs(changelog): add the portable backup fixes to 1.40.0 2026-10-04 11:32:04 +02:00
Marc-André Bombeck 5d28d05004 docs(changelog): add reasoning effort, blood pressure and previews to 1.40.0 2026-10-04 11:30:20 +02:00
Marc-André Bombeck 4e88243075 Merge remote-tracking branch 'origin/main' into release/v1.40.0 2026-10-04 11:29:47 +02:00
Marc-André Bombeck 24786f6549 Merge pull request #1130 from MBombeck/feat/provider-reasoning-effort
feat(ai): per-provider reasoning effort for Local and gateway models
2026-10-04 11:29:44 +02:00
BernhardBuckel 1763ac85d9 fix(import): honour the origin marker on a blood pressure correlation
A blood pressure reading is a <Correlation> wrapping its systolic and diastolic
records, and the marker can sit on the correlation instead of on each record.
The import only read it from a record's own metadata, so a marked correlation
would have come back in full.

A correlation's records are now held until it closes, then all kept or all left
out together: the marker on the correlation, before or after its records, or on
a record, applies. Tests cover each, the marker not spilling onto the next
record, and a self-closing record.
2026-10-04 11:28:08 +02:00
Marc-André Bombeck 3634f6c520 Average pulse by day in the dashboard, insights and series stats
The dashboard summaries, the insights aggregate and the series stats strip
still took a plain mean over pulse readings for their 7-day, 30-day, prior-month
and all-time figures, while the year-ago figure and the chart already weighed
each day once, so the year delta compared two different statistics. They now
go through the day-mean helper: each day is the mean of its hours' means and a
window the mean of its days, in the frame each reader buckets its days by.
Count, min, max, the median and the spread stay over every reading; every other
type is unchanged.
2026-10-04 11:22:17 +02:00
BernhardBuckel 12e202958f fix(series): follow the source priority ladder in the blood-pressure series
The blood-pressure branch of /api/measurements/series still read systolic and
diastolic with an unranked findMany, so with a second provider the pairs blended
both sources and a reading present in both showed twice, while the other kinds
already follow the ladder since the dense and raw reads were moved onto the
shared helper.

Each of the two types now reads the ladder-winning source per day through the
same helper. The physiological floors (systolic 40, diastolic 20) and the
five-minute pairing are unchanged.
2026-10-04 11:17:00 +02:00
Marc-André Bombeck ad0f35eadd Merge remote-tracking branch 'origin/main' into release/v1.40.0
# Conflicts:
#	CHANGELOG.md
2026-10-04 11:13:49 +02:00
Marc-André Bombeck ecddcb3fa5 Merge pull request #1128 from MBombeck/fix/pdf-raster-ocrmypdf
fix(documents): hoist the pinned canvas binary and render PDFs with pdfjs font data
2026-10-04 11:13:29 +02:00
Marc-André Bombeck bb36a2afd5 Merge pull request #1127 from MBombeck/fix/idempotency-body-fingerprint
fix(idempotency): replay a key only for the same request body
2026-10-04 11:13:26 +02:00
Marc-André Bombeck a5ffde31c2 Recompute stored pulse rollup means to the hourly-mean statistic
Rows written before this change keep the reading mean: the boot backfill and
the freshness check fill only missing days, so nothing rewrites them. Migration
0373 recomputes the mean of every stored PULSE row from the readings, DAY as
the mean of its hours' means and WEEK / MONTH / YEAR as the mean of their days,
and leaves count, min, max and the sums alone. The writer stores the coarse
rows the same way, so a refold and the migration agree.
2026-10-04 11:10:55 +02:00
BernhardBuckel 841d4e559c test(import): add a synthetic export.xml fixture for the origin marker
The fixture is invented, in the shape Apple's DTD documents, and says so in its
header and its file name. It shows the parser reads a file laid out like an
export; it cannot show that Apple writes a custom metadata key verbatim.
2026-10-04 11:10:49 +02:00
Marc-André Bombeck c755a42d93 Add one day-mean helper for the hourly-mean types
A day of pulse is the mean of its hours' means and a window the mean of its
days, but only the rollup tier and the chart knew it. The helper gives every
other reader the same statistic in both shapes it needs: in TypeScript over
readings it holds, and in SQL as a per-reading day weight whose sums give the
mean of the day values over any window. Every other type keeps its plain mean.
2026-10-04 11:05:35 +02:00
BernhardBuckel a1a84f924b feat(labs): let the lab list's range bar use a wide card
On a wide window the compact lab list was one five-column row whose only
flexible column was the name: the name column sat mostly empty while the range
bar and the trend stayed small at the right edge.

The list's card is now a container, and the columns follow its width instead of
the window's. Below 64 rem of card the row is the lg table it was, with the
range bar at 12 rem; from 64 rem the bar column grows from 12 to 18 rem and the
trend column from 72 px to 8 rem, and the bar fills its column. The two tiers
exclude each other, so the result does not depend on the order the CSS is
emitted in. The trend sparkline itself is unchanged.

From lg up a long analyte name wraps instead of being cut off; a phone keeps the
single line with an ellipsis, and the bar keeps its own 12 rem cap there.

The shared 1280 px frame is untouched; a Playwright spec measures it on /labs,
/measurements and /mood at 1280, 1920 and 3440 px.

Fixes #1057
2026-10-04 10:56:43 +02:00
BernhardBuckel a5e98c9e71 fix(import): leave out Apple Health samples HealthLog wrote itself
The iOS app writes manual entries into Apple Health, and mirrors Withings and
import rows into it, each stamped with dev.healthlog.app.origin = healthlog.
The server already holds those readings under their own source, so the same
sample arriving through an Apple Health export is a second copy: the series
shows it twice and the rollups count it twice.

The export import now leaves out a record carrying that marker. The marker is a
child <MetadataEntry>, read after the record's open tag, so a record is
committed at its close tag. As a fallback for manual entries mirrored before the
app set the marker, a record is also left out when a MANUAL row of the same
type and value sits within 2 s (same rule and tolerance as the sync path).
Withings and import rows are not matched by value and time: they reach Apple
Health only through the mirror, which always sets the marker.

The import summary says how many records were left out for this reason.

Fixes #1109
2026-10-04 10:53:23 +02:00
Marc-André Bombeck a0fa4783c0 fix(ai): keep JSON mode when an endpoint rejects only reasoning_effort
An endpoint that does not know reasoning_effort answers with an unknown
parameter error, which the JSON-mode probe read as a refusal of
response_format and switched that base URL to plain prompts.
2026-10-04 10:48:35 +02:00
Marc-André Bombeck 39a5862d54 feat(settings): add a Reasoning select to the Local and gateway forms
One select under the model field of the Local and OpenAI-compatible
provider forms: Default, Off, Low, Medium, High, with a one-line hint
that Off leaves the answer budget for the answer itself. It reuses the
NativeSelect, label and hint layout of the field above it, seeds from
the stored entry, and saves with the form. Strings in all seven
locales.

Refs #1126
2026-10-04 10:43:04 +02:00
Marc-André Bombeck 9cb06ec44d fix(idempotency): read a rebuilt multipart form as the same request
A client that rebuilds a form for a retry picks a fresh random boundary,
so the raw bytes differ and a repeated document upload ran a second time
instead of replaying. The boundary named in Content-Type is replaced by a
fixed token before hashing.
2026-10-04 10:43:00 +02:00
Marc-André Bombeck befac59576 feat(ai): send a per-entry reasoning effort to Local and gateway providers
Reasoning models on Ollama and similar servers think by default and can
spend the whole max_tokens budget before the visible answer starts, so
the call comes back empty or times out. The Local and OpenAI-compatible
chain entries now carry an optional reasoning setting: Default sends
nothing, Off sends reasoning_effort "none", Low / Medium / High send
their own value. It is stored on the entry in aiProviderChain, so a
chain can mix a thinking model with one that does not know the field.

- Every exported resolver binds the entry's value onto the client, the
  connection test included, keyed on the instance type so the operator
  provider, OpenAI, Anthropic and Codex never carry it.
- PATCH /api/user/ai-provider accepts localReasoningEffort and
  compatReasoningEffort and GET reports them. A provider absent from
  the chain holds its value on a disabled entry; restating Default on a
  chain that was never customised writes nothing.
- PUT /api/insights/provider-chain accepts reasoningEffort on local and
  openai-compatible entries, refuses it on any other, and keeps the
  stored value when the body leaves it out. Its schema is now shared
  with the OpenAPI registry.
- A Default request body is byte-identical to the one sent before.

Refs #1126
2026-10-04 10:42:59 +02:00
BernhardBuckel 497da7ca8b fix(pulse): make a day of pulse the mean of its hours' means
A watch samples pulse about every 5 to 10 minutes at rest and about every
5 seconds in a workout. The daily value was the plain mean over a day's
readings, so a workout hour of several hundred readings outweighed the other
23 hours: a day with one hard hour and 23 resting hours (60 bpm) read about
128 bpm, not 64.

A day of pulse is now the mean of its per-hour means, in the rollup DAY
bucket, the live per-day read the chart serves, and the series route's day
grain. Windows over several days weigh each day once instead of by its
reading count, so the bias does not return one level up. Reading counts,
min/max, and the regression sums still run over every reading. The chart
tooltip and the data table name the statistic, in all seven locales.

The statistic is limited to pulse; HRV, SpO2 and glucose keep the plain mean
(see src/lib/measurements/day-statistic.ts). Stored DAY rows are rewritten by
the next rollup recompute (admin recompute route), not on read.

Fixes #1107
2026-10-04 10:41:08 +02:00
Marc-André Bombeck 8cf1210bad fix(documents): log why a document got no thumbnail
Refs #1124. The thumbnail job opened no wide event, so every annotation
it made went nowhere: one instance ran it hundreds of times, left sixteen
PDFs without a preview, and the log never said so.

Each run is now a `job.document_thumbnail` background event. A run that
should have produced a preview and did not is raised to warn and names
the reason; a type that never has a preview stays at info.
2026-10-04 10:37:24 +02:00
Marc-André Bombeck 4b73099e75 fix(documents): render PDFs with pdfjs font data and refuse blank pages
Refs #1124. The rasterizer opened pdfjs without its standard font, CMap
and wasm directories and told it to use system fonts. The runtime image
has none, so any text pdfjs could not draw from an embedded program (a
non-embedded standard font, or an embedded one it cannot parse) came out
as nothing, and an image-only provider was sent the page background. A
workstation hides this because its own fonts stand in.

pdfjs now gets the directories from its own package, resolved at runtime
from the working directory, and Liberation Sans from that package is
registered as the canvas' sans-serif, serif and monospace faces for the
text pdfjs draws with a substitute.

A document whose every rendered page is blank now reports render-failed,
so the read records raster-failed instead of indexing a transcript of an
empty page as a success.
2026-10-04 10:37:24 +02:00
Marc-André Bombeck b63fa317f3 fix(docker): hoist the canvas binary of the pinned version
Refs #1124. The store holds two @napi-rs/canvas versions, the pinned one
and an older one that pdf-parse's own pdfjs-dist pulls in. The runner
stage took the musl binary with `find | head -1`, got the old one, and
copied it into the new loader's directory, where the loader looks first.
Rendering still worked, but `loadImage` calls `Image.decode`, which the
old binary lacks, so every preview thumbnail failed with "image.decode is
not a function" on both architectures.

The builder now records the resolved canvas version and the runner hoists
that version by name, as it already does for pdfjs-dist. The build stops
when the binary it copies belongs to another version.
2026-10-04 10:37:23 +02:00
Marc-André Bombeck bf35779db7 Fail the round trip when a portable file carries ciphertext
With every sealed column filled, the column round trip now also builds
the portable file of the same account and fails on any section that
carries a sealed column as stored ciphertext, unless the section is named
with a reason. The disaster-recovery file of the same account is the
floor, so a matcher that finds nothing cannot pass the check.
2026-10-04 10:19:32 +02:00
Marc-André Bombeck b36190b2df Restore custom mood tags without mood entries
The account's own mood categories, tags and hidden set were written only
inside the restore's mood-entry branch, so a vocabulary set up before the
first entry did not come back. They are written whether or not the file
carries an entry.
2026-10-04 10:19:32 +02:00
Marc-André Bombeck 8ac3fddc3b Carry visit and vaccination free text readable in a portable backup
A practitioner's note, a visit's reason, outcome and body site and a
vaccination's note travelled as stored ciphertext in a portable file, the
same defect the cycle and mood sections had. They now go through the
shared sealed-text helpers: readable in a portable file, sealed under the
receiving host's key on restore, ciphertext kept only where this host
opens it and otherwise reported as visitCiphertext or
vaccinationCiphertext. The practitioner address and phone ciphertext of a
disaster-recovery file gets the same check, since the key preflight now
leaves these sections to it.
2026-10-04 10:19:31 +02:00
Marc-André Bombeck 2798cc953f refactor(workouts): drop the unused clock arguments of the blank draft 2026-10-04 10:18:16 +02:00
Marc-André Bombeck 183b7ce2c5 Merge remote-tracking branch 'origin/main' into release/v1.40.0 2026-10-04 10:16:56 +02:00
Marc-André Bombeck b55850967d fix(idempotency): replay a key only for the same request body
The replay cell was keyed on (user, key, method, path). A client that sends
two different writes under one key got the first write's cached response for
the second, and the second was never saved. Native clients up to 1.1.0 post
the two halves of a manual blood pressure exactly that way, so the diastolic
value was silently dropped.

Each cell now stores a SHA-256 fingerprint of the request body (JSON with
recursively sorted keys, otherwise the raw bytes; scoped by method and path;
at most the first MiB is read). Lookup replays, or refuses as in flight, only
when the fingerprint matches. A different body, or a row written before the
column existed, runs the handler without claiming or caching and leaves the
existing cell for its own retries; a lost claim race re-checks the winner's
fingerprint the same way. The body itself is never stored.

Migration 0371 adds the nullable idempotency_keys.request_fingerprint column.
The OpenAPI parameter description, the client notes and the Home Assistant
guide say what a replay now requires. docs/ops gains a read-only query that
lists systolic readings left without their diastolic half, held to the
schema by an integration test.
2026-10-04 10:14:22 +02:00
Marc-André Bombeck 808b2672cd Merge pull request #1125 from MBombeck/fix/manual-workout-blank-start
Read a blank workout start as now minus the duration
2026-10-04 09:30:20 +02:00
Marc-André Bombeck 17b653b819 feat(workouts): read a blank start as now minus the duration
Refs #1085. Logging a workout right after finishing it meant changing the
start first, or the form refused it as ending in the future. The start field
now opens blank; left blank, the workout is saved as starting the duration
before now. A start the person enters is validated as before.
2026-10-04 09:07:39 +02:00
Marc-André Bombeck c7a2eec078 Drop the column fallback around the medication update
The update retried without pausedAt and notificationsEnabled for a
database that lacked the columns. Migrations guarantee both, and inside
the transaction a failed statement aborts it, so the retry could not
work anyway.
2026-10-04 08:31:11 +02:00
Marc-André Bombeck 43a53255c9 Carry custom mood labels readable in a portable backup
The labels of the mood tags and mood categories an account created
travelled as the stored ciphertext in a portable file, so a restore onto
a host with another key refused the file or wrote labels nobody could
open. They now follow the cycle note: readable in a portable file, sealed
under the receiving host's key on restore, ciphertext kept only where
this host opens it and otherwise reported as moodLabelCiphertext.

The sealing helpers move to one module both sections share.
2026-10-04 08:31:11 +02:00
Marc-André Bombeck 715df7d5d3 docs(readme): keep the contributor list without a separate line for one person 2026-10-04 08:29:43 +02:00
Marc-André Bombeck b3e18739fb docs(readme): name the people whose reports shaped HealthLog 2026-10-04 08:24:07 +02:00
Marc-André Bombeck 6bc764fa28 Write a medication PUT and its course in one transaction
The row update (name, schedule, oneShot) committed before the course
write. When a concurrent course made the course write refuse, the client
got the refusal while the rest was already written. The schedule replace,
the row update, the pause era and the course write now commit together,
so a refusal leaves the medication unchanged. The rollup recompute runs
after the commit.
2026-10-04 08:17:34 +02:00
Marc-André Bombeck 8121935642 Carry cycle free text readable in a portable backup
A portable file carried the day-log note, the sensitive-category envelope
and custom symptom labels as the stored ciphertext, so a restore onto a
host with another key either refused the file or wrote values nobody
could open. The portable file now carries them readable and the restore
seals them under the receiving host's key; a disaster-recovery file keeps
the ciphertext.

A file written before this still restores: each ciphertext value is
opened with this host's keys first, and one that does not open is kept
out of the row and reported in the skip summary as cycleCiphertext. The
key preflight leaves the cycle sections to that per-value check.
2026-10-04 08:17:34 +02:00
Marc-André Bombeck 964a3d050c Merge pull request #1123 from MBombeck/fix/key-check-newest
Never refuse a key that opens the newest data
2026-10-04 02:22:13 +02:00
Marc-André Bombeck 2f3da10317 Ask the newest values before the key check refuses
The probe decided on the eight oldest values alone. An install
reinstalled under a fresh key long ago holds old rows sealed under a key
that is gone and all current data under the key it runs with; it works
today, and the check would refuse it with 503 on every request.

When every oldest value fails, the newest values of the same columns are
now sampled in reverse order. One that opens makes the verdict
inconclusive (mixed): the process serves, warns and probes again at the
next start. Only old and newest values that all fail are a mismatch. A
newest-only open never seals; sealing stays with the oldest-first rule.

Every probe query now runs in its own transaction under a
transaction-local statement_timeout (2 s), so a large or locked table
ends that column with an error and the probe as incomplete instead of
holding up the boot. The newest order is the exact mirror of the oldest,
so an index on the timestamp serves both directions.

The module comment lists the three conditions that still yield a
mismatch.
2026-10-04 01:58:04 +02:00
Marc-André Bombeck f685cbe460 chore(release): v1.40.0 — back up the encryption key, medication courses and categories, your own symptoms, document reads in the background 2026-10-04 01:26:37 +02:00
Marc-André Bombeck 2c2e3fcc72 Merge pull request #1122 from MBombeck/feat/medication-categories-courses
Custom medication categories and several courses per medication
2026-10-04 01:25:33 +02:00
Marc-André Bombeck db9618ee7b Merge remote-tracking branch 'origin/main' into wip/v140-H 2026-10-04 00:43:10 +02:00
Marc-André Bombeck 4317eb91ca Make the rolling course anchor opt-in
The rule that keeps an earlier course's intake from anchoring a rolling
cadence applied to every caller unless one opted out, which is how a
booster reminder picked it up. It now applies only when the context
declares rollingAnchor: "courseStart"; the four medication context
builders declare it, and every other caller keeps the previous
behaviour, where the last intake always anchors. A guard enumerates
every RecurrenceContext builder in src, requires each to be listed as a
medication or a non-medication builder, and checks the declaration on
both sides.
2026-10-04 00:42:54 +02:00
Marc-André Bombeck df85fd62c9 Drop the unused built-in category list export 2026-10-04 00:33:34 +02:00
Marc-André Bombeck b930ab80ff Keep booster and measurement reminders anchored on the last satisfaction
The course rule that stops an old intake from anchoring a rolling
cadence read a reminder's anchor date as a course start, so a booster
fourteen years past on a ten-year cadence came due later today instead
of staying overdue. Measurement and booster reminders now opt out with
rollingAnchor: "lastIntake"; the rule stays on medications.
2026-10-04 00:33:34 +02:00
Marc-André Bombeck bc41dfb1b3 Merge pull request #1121 from MBombeck/fix/key-check-hardening
Make the encryption key check unable to lock out a correct key
2026-10-04 00:30:28 +02:00
Marc-André Bombeck 363070540b Merge remote-tracking branch 'origin/main' into fix/key-check-hardening 2026-10-04 00:01:07 +02:00
Marc-André Bombeck e04daed904 Merge pull request #1120 from MBombeck/fix/v140-review-ui
Keep the glucose card in mg/dL and fix pre-release review findings
2026-10-04 00:00:53 +02:00
Marc-André Bombeck 69bae8bdb4 Add ENCRYPTION_KEY_CHECK=warn as an escape hatch for the boot key check
At a first start there is no recorded key yet, so an operator facing a
refusal they are certain is false has no row to delete. With
ENCRYPTION_KEY_CHECK=warn (default enforce) the check still runs and logs
its full outcome, /api/health names a mismatch as a warning field without
failing, requests are served, and no key is recorded unless every key id
passes.

The variable is on the compose whitelist, in both example files, the env
manifest, the Unraid and Portainer templates and the published-env guard.
The log block, the mismatch page and the self-hosting pages offer it as the
last resort after the three real fixes, and say that it disables a safety
check.
2026-10-03 23:46:40 +02:00
Marc-André Bombeck 2c2151ae70 Keep the rolling anchor when a start only moved forward
An intake before startsOn stopped anchoring a rolling cadence, which
also moved the next dose of a single-course medication whose start had
merely been pushed forward a few days. The intake is now ignored only
when the dose it implies would fall before the course starts (a new
course after a gap); otherwise it anchors as before.
2026-10-03 23:42:29 +02:00
Marc-André Bombeck 17bced4fdf docs(self-hosting): an Apple Health import from a web-only container is queued, not refused 2026-10-03 23:38:13 +02:00
Marc-André Bombeck b74c6de7ce fix(cycle): give the custom-symptom popover the shared symptom icon picker 2026-10-03 23:38:12 +02:00
Marc-André Bombeck eada82f61e Derive a backfilled course in the account's time zone
The backfill and the restore of an older file read the creation day of
an end-only window in UTC while every reader of the window uses the
account's zone; both now use the account's zone (the default zone when
the stored one is unknown to Postgres). A window whose start lies after
its end, which the API refuses but older rows hold, becomes a one-day
course on the end day: every reader treated it as empty and ended, and
a swap would have invented expected doses. One shared rule
(courseFromWindow) serves the restore and the course writer.
2026-10-03 23:36:08 +02:00
Marc-André Bombeck 4783711651 Refuse MCP and its OAuth endpoints while the encryption key does not match
apiHandler answers 503 encryption.key_mismatch before auth, but the remote
MCP endpoint and the OAuth authorize, token and register routes wrap in
withBackgroundEvent instead and never checked. An MCP write tool could seal
new rows under the wrong key, and those rows would open under it at the
next boot.

The refusal moves into one helper used by apiHandler, /mcp (same envelope)
and the OAuth routes (RFC 6749 temporarily_unavailable with the error code
as an extension member). A structural test fails when a route outside
apiHandler, or a server action, lacks the refusal in every exported handler
and is not on a short allowlist of routes that never touch the database.
2026-10-03 23:32:07 +02:00
Marc-André Bombeck c809a811e6 docs(self-hosting): say which reads run on the worker and why a split worker must match the web version 2026-10-03 23:32:04 +02:00
Marc-André Bombeck 2c295bbea8 Probe the oldest stored values before recording an encryption key
The boot key check recorded whatever key was configured whenever its probe
found nothing to try. It only read string columns, so an install whose
ciphertext sat in Bytes columns (notes, documents, ECG, symptoms) read as
empty; a probe that ran out of time did the same; and rows written by a
process that served under a wrong key could open on the next boot and get
that key recorded as the right one.

The probe now reads every registered column, string and Bytes, in all four
stored layouts, and tries the oldest values first, ordered by the row's
updatedAt (else createdAt, else primary key). A key is recorded only when
the oldest value that opens is preceded by at most one that does not, or
when no column holds a single value under the key id. A time-out, an
unreadable table, oversized values or mixed results are inconclusive: the
process serves, records nothing and checks again at the next start.

When the first insert loses a race, the stored record is read back and must
open under this process's key, else the outcome is a mismatch.

A rotation that walked every column without errors removes the record of
each previous key id that no longer holds any value. The refusal log block
and the self-hosting pages explain how to reset the check for a key id.
2026-10-03 23:29:55 +02:00
Marc-André Bombeck 6c262f2099 fix(documents): compare a confirmed lab fact's unit with the shared spelling normaliser 2026-10-03 23:29:13 +02:00
Marc-André Bombeck 510d4b1d04 Write a medication's window and its course in one transaction
The PUT wrote startsOn/endsOn on the row and then rewrote the latest
course in a second transaction, so a failure between the two left the
row and its courses disagreeing. The window now reaches the row only
through the course writer, which writes both under one lock.
2026-10-03 23:29:12 +02:00
Marc-André Bombeck 62d47d7056 fix(workouts): drop a hand-entered workout's paragraph when an edit changes its values
The paragraph described the old values. It is deleted with them, its generation claim is detached the way a delete detaches it (the day's slot stays spent), and the workout's arrival is raised again so the paragraph is written from the corrected values through the ordinary path, under the same daily cap.
2026-10-03 23:26:48 +02:00
Marc-André Bombeck e811c64bfb fix(i18n): name the thermometer icon the German way 2026-10-03 23:26:48 +02:00
Marc-André Bombeck 9f865a9456 Show every course in the dose history
The history minted bands only from the latest course, so misses in an
earlier course counted in the rate and appeared nowhere in the history.
It now mints over the span of every course and keeps the slots on a
course day. The compliance ledger and the cadence missed tally drop the
gap slots before the reconstruction instead of after it, so a dose
logged between courses stays visible as an off-schedule take in both.
2026-10-03 23:24:23 +02:00
Marc-André Bombeck 8aa2e33435 Walk every course in the streak and the cadence timeline
The rate counted misses in earlier courses while the streak and the
cadence chart's missed tally minted only the latest course, so a miss
in a previous course never broke the streak. The cadence engine context
now carries the courses and expands over their span, keeping only course
days, the same rule as the compliance ledger.
2026-10-03 23:16:16 +02:00
Marc-André Bombeck 0100256c60 test(labs): pin the lab scan's waiting line to the copy that does not promise the page can be left 2026-10-03 23:13:59 +02:00
Marc-André Bombeck 16c16000e7 Refuse a first course beside a medication taken continuously
A medication with no course rows and no window is running since its
creation; a course added beside it projected the medication into ending,
which stopped its reminders and dropped its history from compliance. The
create now refuses that (medications.course.currentOpen; End course
writes the first course). A window the rows never recorded is
materialised as the first course before the new one is checked.
2026-10-03 23:11:28 +02:00
Marc-André Bombeck 367a1bb4b4 fix(symptoms): size the icon pickers for touch and name each icon in the reader's language 2026-10-03 23:10:56 +02:00
Marc-André Bombeck 1eab6145a9 fix(symptoms): show the load error in the quick entry instead of the empty hint 2026-10-03 23:07:16 +02:00
Marc-André Bombeck d644db1975 Revert "feat(dashboard): send the glucose card in the owner's glucose unit"
This reverts commit 9455b64375.
2026-10-03 23:03:02 +02:00
Marc-André Bombeck 1494409209 Merge remote-tracking branch 'origin/main' into wip/v140-H
# Conflicts:
#	messages/de.json
#	messages/en.json
#	messages/es.json
#	messages/fr.json
#	messages/it.json
#	messages/ko.json
#	messages/pl.json
#	src/__tests__/sharing-surface-guard.test.ts
#	src/__tests__/v137-wave-zero-fixtures.test.ts
#	tests/integration/sharing-manage-handler-matrix.test.ts
2026-10-03 22:52:49 +02:00
Marc-André Bombeck 50bc0dab5a fix(medications): keep a custom category when a native client sends OTHER back
An iPhone build that predates custom categories decodes an unknown category
as OTHER and sends it back on every edit. A Bearer update sending OTHER over
a custom category now keeps the custom one; the web can still move it back.
2026-10-03 22:52:05 +02:00
Marc-André Bombeck 4d7abdd12b Give a category its own line in the manage sheet
At phone width the three actions left the label a few characters; the
count and the hidden state now sit under it, the course list's row
anatomy.
2026-10-03 22:47:09 +02:00
Marc-André Bombeck 3a99c8cfee Merge pull request #1115 from MBombeck/docs/ideas-board
Point feature ideas to the Ideas category
2026-10-03 22:43:31 +02:00
Marc-André Bombeck 0cb54f1dd4 Merge pull request #1118 from MBombeck/feat/custom-symptoms
Log your own symptoms in one step
2026-10-03 22:43:22 +02:00
Marc-André Bombeck 157002f75d Translate the medication courses into every locale 2026-10-03 22:39:28 +02:00
Marc-André Bombeck a14174fe4d Let a medication have several courses
A medication taken now and then (#1024) keeps one row and gains course
rows: calendar spans, both ends inclusive, an optional encrypted note, no
schedule or dose of their own. Courses never overlap and every course but
the latest has ended, so the latest course is always the one the
medication's startsOn/endsOn project. src/lib/medications/courses.ts is
the only writer of those two columns for a medication with courses; it
writes under a per-medication advisory lock and re-projects in the same
transaction, so reminders, the next-due line and intakeActionable keep
reading the columns and stay right.

- Migration 0368 adds medication_courses and backfills one course per
  medication window (an end-only window starts on the creation day, or
  on its end day when that lies earlier); a medication without a window
  stays course-less. Idempotent, data-preserving.
- GET/POST /api/medications/{id}/courses and PATCH/DELETE
  .../courses/{courseId} (owner-only); create seeds the first course
  from a window; the medication PUT edits the latest course and refuses
  a window that would break the rules (medications.course.*).
- List, detail, create and update carry courses, courseCount,
  previousCourseEndedOn and canStartCourse, resolved on the server.
- Compliance expands over the span of all courses and drops the slots
  between them; every compliance read selects the courses. A rolling
  cadence is not anchored by an intake from a previous course.
- The card names the last course's end and the running course's number;
  the detail Lifecycle group lists the courses with start, edit and
  delete. The Coach compliance block, the MCP resource, the doctor
  report window and table, the clinician view and FHIR (one
  MedicationStatement per course with effectivePeriod and status) read
  the courses.
- Backup carries courses per medication and the restore writes them and
  re-projects; an older file derives the one course its window
  describes. Wipe plan, encrypted columns, rotation and OpenAPI follow.
2026-10-03 22:39:25 +02:00
Marc-André Bombeck ef0028c020 Merge remote-tracking branch 'origin/main' into wip/v140-I
# Conflicts:
#	docs/api/openapi.yaml
2026-10-03 22:16:29 +02:00
Marc-André Bombeck 4a02414e97 Merge pull request #1119 from MBombeck/feat/document-ai-runs-rest
Run document summaries, suggestions and extraction in the background, and add sick notes
2026-10-03 22:16:05 +02:00
Marc-André Bombeck 9c2b57df33 Merge remote-tracking branch 'origin/main' into wip/v140-I 2026-10-03 22:00:18 +02:00
Marc-André Bombeck 1ee6f9005f chore(bundle): lower the eager route baselines and re-base the aggregate for on-demand quick-entry forms 2026-10-03 22:00:16 +02:00
Marc-André Bombeck 9b71231010 Exempt the medication category routes from the module gate
They are raw CRUD over the account's own rows, the data-layer reasoning
every other medication route is exempt on.
2026-10-03 22:00:07 +02:00
Marc-André Bombeck b7458f0607 Stub the custom category read in the export route tests
The full backup now reads the account's own medication categories, and
three route tests that drive the payload builder against a mocked client
had no delegate for it.
2026-10-03 21:59:42 +02:00
Marc-André Bombeck 8068626aa8 Merge remote-tracking branch 'origin/main' into wip/v140-K 2026-10-03 21:48:26 +02:00
Marc-André Bombeck 8d64da2807 Name the sick note kind in every locale
Label SICK_NOTE in all seven bundles and pin that every document kind
the database knows has a label in each locale, a place in the vault's
kind list and a glyph: the kind reaches the screen through a dynamic
key, which the call-site coverage guard cannot see.
2026-10-03 21:43:37 +02:00
Marc-André Bombeck 57a54061be Merge pull request #1112 from BernhardBuckel/fix/series-source-ladder
fix(series): follow the source priority ladder in the dense and raw series reads
2026-10-03 21:41:33 +02:00
Marc-André Bombeck 1564e7c396 Add the sick note document kind
A certificate of incapacity for work (in Germany the
Arbeitsunfähigkeitsbescheinigung) is now its own document kind,
SICK_NOTE, instead of Other. The enum value rides migration 0370.

Uploads, edits, the kind filter, bulk edits, the import script and the
backup format accept it; the vault files it with a thermometer glyph
between prescriptions and referrals; the filing suggestion can propose
it and names the words a sick note carries. The extraction's own kind
field keeps its three values.
2026-10-03 21:40:01 +02:00
Marc-André Bombeck ca4a45ee2c i18n(symptoms): add the symptom strings in all seven locales
The capture picker and Add menu entries, the quick-entry sheet, the
illness page section and the episode card, the activity-feed verbs, the
restore skip label and the symptoms.* API error messages, in de, en, es,
fr, it, ko and pl (German informal).
2026-10-03 21:38:37 +02:00
Marc-André Bombeck 802759df02 Translate the custom medication categories into every locale 2026-10-03 21:38:05 +02:00
Marc-André Bombeck dbbff339f6 test(symptoms): register the new surfaces with the export, destructive and success guards
The full-backup route tests mock the symptom definition read the payload
now makes; the destructive-control registry names the symptom hooks (an
entry or a whole symptom, confirmed by an AlertDialog); the symptom quick
entry's save toast is pinned beside the measurement and mood forms it
mirrors.
2026-10-03 21:38:03 +02:00
Marc-André Bombeck 4cb8118802 Let a person name their own medication categories
A medication can be filed under a category the person named, next to the
built-in ones (#1041). The labels live in medication_category_labels,
encrypted at rest, capped at 20 per account; a medication filed under one
carries its custom:<uuid> key in the category column.

- GET/POST /api/medications/categories (POST idempotent, 30/min per actor,
  admitted at MANAGE like the cycle symptom vocabulary) and owner-only
  PATCH/DELETE /api/medications/categories/{key}. DELETE moves every
  medication filed under the category to OTHER in the same transaction
  and answers movedCount.
- category is widened to a built-in value or custom:<uuid> on the wire,
  the create and update bodies refuse a key that is not the caller's
  (422 medications.category.unknown), and list, detail, the insights
  medication tiles and the MCP medications resource carry categoryLabel.
  A key with no owned label reads as OTHER and is counted on the event.
- The wizard's class step lists the person's categories under the
  built-in rows with an inline add row; the list page gains a category
  filter (session only) and a manage sheet for rename, hide and delete.
- Backup carries customMedicationCategories (decrypted labels) and the
  restore writes them before the medications; wipe plan, encrypted
  column registry, rotation script, sharing guards and OpenAPI follow.
2026-10-03 21:38:03 +02:00
Marc-André Bombeck 65b2f75421 perf(dashboard): load the quick-entry forms when a sheet opens
The dashboard and the bottom bar's capture picker imported all five
quick-entry forms eagerly, so every authenticated paint carried them for
sheets most visits never open. One module now wraps them in next/dynamic
(client-only, a skeleton holding the sheet body while the chunk loads)
and both callers use it. The discard guard stays static. The picker tests
mock the one module instead of five.
2026-10-03 21:30:38 +02:00
Marc-André Bombeck bcbfd87ae9 feat(coach): name the person's own symptoms in the illness block
The Coach illness block now carries the last 14 days of the person's own
symptoms (name sanitised for the prompt, count, highest intensity, last
occurrence; at most ten, most frequent first), and exists when there are
symptoms but no episode. The prompt describes the field in English and
German. The MCP get_illness_recovery result leaves it out in this
release.
2026-10-03 21:24:28 +02:00
Marc-André Bombeck 9272daa59c feat(symptoms): log a symptom in one step and show it on the illness pages
- A new capture kind "symptom" (illness module, illness write grant) in
  the bottom bar's picker and the dashboard Add menu. The sheet follows
  the measurement and mood forms: the person's symptoms as chips with the
  cycle sheet's dashed "new symptom" chip, the 0-10 slider with its
  anchors, the time prefilled with now, an optional note, and a "during"
  selector only while an illness episode is open.
- "Your symptoms" on the illness page: one line per symptom (how often in
  30 days, how strong at worst, when last), the last 30 days grouped by
  day, edit and delete per entry, rename, icon, hide and delete per
  symptom. Renders nothing until a symptom exists.
- "Symptoms logged" on an episode's page: the entries filed against it or
  logged while it ran, the filed ones marked. This is the reader of the
  episode link.
- Query keys live under the illness root, so either side's writes
  refresh both.
2026-10-03 21:24:12 +02:00
Marc-André Bombeck bb58b40b2a Run fact extraction in the background, re-checking under a row lock
The extract route accepts `Prefer: respond-async` for all three inputs
(text, stored, vision) and queues a DOCUMENT_EXTRACT run (added to
migration 0370). The run's result is the count of staged facts and the
document status; the facts themselves are read from the document.
Without the header the route answers with the document detail as
before; both paths run one shared body.

A background read can take minutes, and a review the person finishes in
the meantime must not have its approved facts replaced. Staging now
locks the document row and asks again whether it may stage, refusing
with the route's own alreadyConfirmed / alreadyPartlyConfirmed codes.
The synchronous path gets the same re-check.

The vault's stored-text extract uses the background path and shows the
shared waiting line in place of its hint while the read runs.
2026-10-03 21:14:47 +02:00
Marc-André Bombeck 9d9e1f153c feat(insights): make each person-defined symptom its own correlation channel
Every active symptom definition enters pattern discovery as an outcome
channel SYMPTOM:<id>, labelled with its decrypted name (the data label
the interpretation already prefers over the key). The daily value is the
day's highest intensity in the person's zone; days without an occurrence
count as 0 only between the first and the last logged day. At most eight,
the active-definition cap. The SYMPTOM: prefix resolves to the illness
module in the surface map, so the family leaves the matrix with the
module, and the discovery guard lists the new fetcher.
2026-10-03 21:14:08 +02:00
Marc-André Bombeck d6571c4e9c feat(symptoms): add person-defined symptoms and timestamped occurrences
A symptom of one's own ("aura", "headache") is a definition with an
encrypted name and an icon from the cycle custom-symptom allowlist; each
occurrence carries a time, a 0-10 intensity (the pain score's scale), an
optional encrypted note and an optional link to one of the record's open
illness episodes. Both ride the illness module: every route answers
illness.disabled when it is off.

- Migration 0369 (idempotent): symptom_definitions and symptom_events,
  intensity CHECK 0-10, episode link ON DELETE SET NULL.
- /api/symptoms/definitions{,/[id]} and /api/symptoms/events{,/[id]}:
  eight active definitions per record (a hidden one frees its slot,
  showing it again re-checks), hide or purge, events create/list/edit/
  delete, a new link must name an open episode of the same record
  (422 symptoms.episode.notOpen). Error group symptoms.*.
- Sharing: reads at READ, logging an occurrence at WRITE, defining and
  editing at MANAGE; C1/C3/C4 audit details; frozen lists, the handler
  matrix and the activity verbs updated.
- Both encrypted columns registered and rotated; both models in the wipe
  plan; both carried at both backup ends with occurrences nested in their
  definition, plaintext in a portable file and ciphertext in a recovery
  file, and a link to an episode the file lacks dropped and named
  (symptomEpisodeReference).
- OpenAPI regenerated.
2026-10-03 21:13:45 +02:00
Marc-André Bombeck eda5776886 Run document summaries and filing suggestions in the background
The summary and suggest routes accept `Prefer: respond-async`: after the
same quick refusals they answer 202 with a run id, and the background
document AI worker runs the read under two new run kinds
(DOCUMENT_SUMMARY, DOCUMENT_SUGGEST, migration 0370). Without the header
both routes answer synchronously as before; both paths run one shared
body, so they cannot drift.

The worker asks the capability for the record and re-checks the wire for
the provider it picks before every read. A summary that is to be stored
marks the document PENDING while queued, READY when it lands, and
UNAVAILABLE when the run fails or the write does not land. A second
request attaches to a live run only when it would produce the same thing.

The vault asks for both in the background and shows the same calm
waiting line the index uses, worded so a transient read never promises
that leaving the page keeps it. The egress guard and the route inventory
now hold every run kind to its dispatcher re-check and its capability.
2026-10-03 20:51:57 +02:00
Marc-André Bombeck 350c646463 Adopt the medication category table into the schema
The clinical category lived in a side table the app created at runtime,
after migration 0004 had dropped it as orphaned. It is now the
MedicationCategoryAssignment model. Migration 0368 creates the table
IF NOT EXISTS with the runtime DDL, so an existing table converges with
its rows untouched (verified with prisma migrate diff against a database
holding the runtime table and against a fresh one).

The helpers keep their names and run on the Prisma delegate; the runtime
CREATE TABLE and the pre-transaction ensure call in the restore are gone.
The backup plan judges the table as a schema model (backed up, two-ended,
seeded in the round trip) instead of under RAW_SQL_TABLES, which is now
empty; its guard proves its matcher on a fixture string instead.
2026-10-03 20:45:02 +02:00
Marc-André Bombeck b961e82a71 chore(github): point feature ideas to the upvotable Ideas category 2026-10-03 20:34:51 +02:00
Marc-André Bombeck 7cd323499e Merge pull request #1106 from MBombeck/feat/v140-fixes
Workout insight cap, marker unit lock, natural durations, charts that include today, and display fixes
2026-10-03 20:32:09 +02:00
BernhardBuckel bb1acfab64 fix(series): follow the source priority ladder in the dense and raw series reads
The rollup tier and sleep resolve every (type, day) to the source the person's
ladder picks before they aggregate. The dense and raw reads of
/api/measurements/series filtered on user and type only, so with a second
provider a day's value blended the two, a reading present in both showed
twice, and the configured ladder had no effect on those charts.

Both reads now take the ladder-winning source per day through the shared
canonicalMeasurementsCte helper, as the other live readers do:

- the day and hour bucket read of the dense kinds (pulse, glucose, HRV, SpO2),
  and the stats strip over its rows;
- the generic raw read (weight, body fat, steps, resting heart rate, ...).

The collapse is per day for the hour grain too, as everywhere else. The helper
gains an optional single-type scope so a series scans one metric, not every row
the person has in the window.

Only a type that has a ladder is collapsed. For a type without one (glucose,
body water, bone mass) the helper breaks the tie by source name, which would
silently hide one of two real sources, so those keep every source as before.
A single-source account reads exactly what is stored.

Tests: a real-database test covering the ladder in both directions, the
per-day fallback, a reading mirrored into two sources, the day-bucket, hour-
bucket and raw reads, a type with no ladder and a single-source account. The
route's unit test file reads its fixtures through a small adapter for the new
raw statements, and the dense-read guard drops the exception for the removed
findMany. The OpenAPI description states the rule.

Refs #1108
2026-10-03 20:18:50 +02:00
Marc-André Bombeck cd3c0b7de2 Merge remote-tracking branch 'origin/main' into feat/v140-fixes
# Conflicts:
#	docs/api/openapi.yaml
2026-10-03 20:06:16 +02:00
Marc-André Bombeck af1a6e0b14 Merge pull request #1104 from MBombeck/feat/key-backup-and-transport
Back up the encryption key, refuse a key that cannot open the data, and stop sign-ins that cannot keep their cookie
2026-10-03 20:05:58 +02:00
Marc-André Bombeck 1c2822a67b chore(bundle): re-base the client budget for v1.40 2026-10-03 19:43:40 +02:00
Marc-André Bombeck e132110fcd chore(bundle): re-base the client budget for v1.40 2026-10-03 19:43:39 +02:00
Marc-André Bombeck 816eabb3c3 Merge remote-tracking branch 'origin/main' into feat/v140-fixes
# Conflicts:
#	docs/api/openapi.yaml
2026-10-03 19:22:56 +02:00
Marc-André Bombeck 37793298a8 Merge remote-tracking branch 'origin/main' into feat/key-backup-and-transport
# Conflicts:
#	docs/api/openapi.yaml
2026-10-03 19:22:01 +02:00
Marc-André Bombeck 02b6f06521 Merge pull request #1103 from MBombeck/feat/document-ai-runs
Read documents and lab scans in the background
2026-10-03 19:21:43 +02:00
Marc-André Bombeck d753621bd1 Merge pull request #1105 from MBombeck/fix/lab-list-columns
Keep lab list columns aligned for readings without a range
2026-10-03 19:07:43 +02:00
Marc-André Bombeck dcf3b18c91 Merge pull request #1099 from MBombeck/docs/readme-thanks
Update the thanks section
2026-10-03 18:59:01 +02:00
Marc-André Bombeck f3ccc809a8 Merge remote-tracking branch 'origin/main' into wip/v140-E 2026-10-03 18:56:39 +02:00
Marc-André Bombeck c3525cd02f fix(labs): stop the biomarker backfill on its job budget
The integration-backfill drain handed its job budget only to the
Google Health backfill. The lab-biomarker backfill now takes it too,
asks it before each analyte group and, once it says stop, throws
without touching the rest. Finished groups are linked and drop out of
the next scan, so the retry resumes where the pass stopped instead of
running on past the job's expiry beside its own retry.
2026-10-03 18:53:28 +02:00
Marc-André Bombeck 9455b64375 feat(dashboard): send the glucose card in the owner's glucose unit
/api/dashboard/summary sent the glucose card's value in mg/dL with
unit null and a unitKey that reads mg/dL, so a reader on mmol/L saw
the mg/dL number. The card now carries latestValue, secondaryValue
and sparkline in the record owner's glucose unit and names it in
unit, the field that wins over unitKey, as the sleep card already
does. Applied after the summary cache read, so a unit change shows
on the next request.
2026-10-03 18:50:35 +02:00
Marc-André Bombeck facae940b9 Merge remote-tracking branch 'origin/main' into feat/key-backup-and-transport
# Conflicts:
#	docs/api/openapi.yaml
2026-10-03 18:49:04 +02:00
Marc-André Bombeck a01554bd53 fix(dashboard): give the key backup link a 44 px touch target 2026-10-03 18:48:58 +02:00
Marc-André Bombeck cfddf097c7 fix(documents): file an undated document under the reader's upload day
The archive grouped a document without a stated date by the UTC day
of its upload, so an upload late on the last evening of a month west
of UTC opened next month's section (and early on the first morning
east of UTC, last month's). The upload day is now read in the
profile time zone for the month sections and the year filter.
2026-10-03 18:47:05 +02:00
Marc-André Bombeck 9ecdda6358 fix(dates): show a stated calendar date as that date east of UTC+12
Day keys anchored at noon UTC went through the zone-aware
dateShortSmart, which shows them as the next day in UTC+12..+14. A
dateShortSmartCalendar formatter reads the key in UTC with the same
year rule, and the predictions panel, the illness timeline, the
intraday pulse day label, the nutrient chart and the coach result
chart use it. The lab chart dates a date-only reading by its calendar
date and a timed one in the reader's zone, as the lab lists do. The
timezone formatter guard now fails on a noon anchor handed to a
zone-aware formatter.
2026-10-03 18:44:06 +02:00
Marc-André Bombeck 20470d99f4 Merge remote-tracking branch 'origin/main' into feat/document-ai-runs
# Conflicts:
#	docs/api/openapi.yaml
2026-10-03 18:41:55 +02:00
Marc-André Bombeck 358ef23239 fix(clinician): write the shared view's numbers in the owner's locale
The clinician view rounded numbers and printed them bare, so a German
record showed 24.5 where every other surface shows 24,5. Its number
formatter now goes through the locale formatter it already builds,
at most two decimals.
2026-10-03 18:39:03 +02:00
Marc-André Bombeck 5c300a8d9c fix(labs): keep the range bar and trend in their columns when a reading has no range
The range badge renders nothing for a reading without a reference range, so
that row had four cells instead of five and the range bar and the trend
moved one column to the left. The badge now sits in a cell of its own. The
chevron is hidden from lg up, where the row's hover already says it opens;
a phone keeps it.
2026-10-03 18:38:31 +02:00
Marc-André Bombeck fdd34f2c5e fix(charts): keep a chart's window open to the end of today
A chart showing the last N days fixed its window end at the mount
instant. The query key kept that bound, so the refetch after a new
reading asked for the same old window and the reading stayed hidden
until the range tab was switched. The window now ends at the end of
the current day in the profile time zone (openEndedFetchWindow, keyed
on the day): every reading saved today falls inside it, the cache key
stays the same all day, and it moves on after midnight. The dashboard
batch shares the end-of-day helper.

Refs #1102
2026-10-03 18:35:49 +02:00
Marc-André Bombeck 51e2d68a88 i18n(measurements): say how a duration entry was read
Refs #1101
2026-10-03 18:35:26 +02:00
Marc-André Bombeck 313d8491de feat(measurements): read a sleep duration written as 7:30 or 7h 30m
The sleep field asked for decimal hours only. A shared parser
(parse-duration.ts) now reads a bare number with point or comma,
H:MM, and hours and minutes with unit words (7h, 7h30, 7 h 30 min,
45m), answers in the field's unit, and refuses a negative, unknown or
longer-than-a-day entry. The form shows how the entry was read under
the field and puts a refusal on the field itself. The stored value and
the API are unchanged.

Refs #1101
2026-10-03 18:28:39 +02:00
Marc-André Bombeck d805ccf28b Merge pull request #1100 from MBombeck/ci/trivy-braces
Ignore the braces advisory until a fix is published
2026-10-03 18:28:24 +02:00
Marc-André Bombeck 7b51edcebe Merge pull request #1096 from BernhardBuckel/fix/lab-unit-mismatch
fix(labs): refuse a reading whose unit differs from its marker's
2026-10-03 18:28:20 +02:00
Marc-André Bombeck b04b1f2995 fix(encryption): sample several stored values before declaring a key mismatch
The boot check decided on the first value it found under a key id, so
one damaged or foreign-sealed row could take a correctly keyed server
down with 503 on every request. The probe now samples up to five
values, one per column first. One value that opens clears the key; a
mismatch needs at least two values and none opening. A single value
that does not open is inconclusive: the server keeps serving, writes no
canary, logs a warning and probes again at the next start.

Integration setup truncates encryption_key_canaries between tests.
2026-10-03 18:27:28 +02:00
Marc-André Bombeck 3a35dbcf37 i18n(labs): say why a biomarker's unit cannot change once it has readings 2026-10-03 18:22:55 +02:00
Marc-André Bombeck ced17569bf i18n: login notice for a page whose sign-in cookie cannot stick
Adds auth.insecureTransport in all seven locales.
2026-10-03 18:21:23 +02:00
Marc-André Bombeck b100c73a62 fix(auth): refuse a sign-in over plain http before it spends a factor (#1097)
A server that issues Secure session cookies cannot sign anyone in on a
plain http:// page: the browser drops the cookie. The login request was
still verified, the MFA ticket minted and then claimed, and the next
attempt answered "Invalid or expired challenge".

The web client now sends an optional clientTransport on the browser
sign-in requests (password login, passkey start, both MFA completions).
When the server issues Secure cookies and the page is plain http on a
non-loopback host, the request is refused with 409
auth.session.insecure_transport before the password is checked, a
ticket is minted or claimed, a code is spent, or a passkey challenge is
issued. A request without the field is never refused. The SSO start
takes client_proto/client_host and sends such a page back to the login
page instead of to the provider.

GET /api/auth/registration-status publishes sessionCookieSecure, and the
login page shows the reason with both fixes and disables the sign-in
controls before anything is sent; on localhost it shows a note only.
SESSION_COOKIE_SECURE keeps its meaning; the header heuristic log line
stays.
2026-10-03 18:21:19 +02:00
Marc-André Bombeck 89540a999b i18n(documents): say when a read continues in the background
Seven locales for the background-run copy: the calm line while a document
read or a lab scan runs in the worker, the hint when no worker has picked it
up, and the two failures only a background run can produce.
2026-10-03 18:20:59 +02:00
Marc-André Bombeck dd7636e147 feat(labs): refuse a biomarker unit change while readings are linked
Readers label every linked reading with the marker's unit, so changing
it relabelled stored numbers without converting them. PUT
/api/biomarkers/{id} now answers 422 biomarkers.unit.locked with
meta.readingCount when the unit differs and any reading (tombstoned
ones included) is linked. The marker editor says so under the unit
field.
2026-10-03 18:19:50 +02:00
Marc-André Bombeck 0acf3da575 feat(documents): read documents and lab scans in the background
"Read with AI" and the lab scan used to run their model calls inside the
request. At the default response time a read of three calls outlasted the
100 s a proxy in front of the server commonly allows, and the person saw a
cut connection for a read the server was still doing.

Both now run as a background run (`DocumentAiRun`, migration 0366):

- `POST /api/documents/inbound/{id}/index` with `Prefer: respond-async`
  answers 202 with a run id once every quick refusal has passed. Without
  the header it answers exactly as before, which the iPhone app relies on.
  A second request while a read of the same document is queued or running
  attaches to that run.
- `POST /api/labs/ocr/extract` always answers 202. Only the web client
  calls it.
- `GET /api/ai-runs/{id}` serves the run: the same body the synchronous
  route answers with, or the failure code and status it would have given.
  Scoped to the caller; another account's run is a 404.

The worker (`document-ai-run`, a long queue with a one-hour expiry, one
job per run under `lockedPass`) claims the run, asks the capability again
for the record and re-checks the wire for the provider it picks, sets the
run's deadline from the person's AI response time and refuses a read that
cannot fit the job's expiry. Sync route and worker run one body per kind,
so the two paths cannot drift. Budget is reserved at enqueue and settled
once by whoever ends the run.

Input and result are sealed with labelled AES-256-GCM, registered for key
rotation; the input is dropped when the run ends. A five-minute reaper
fails a run no worker took within fifteen minutes (and hands its
reservation back), fails a run past its deadline, and deletes a finished
run after an hour. Runs are outside backups and inside the data wipe.

The web client polls through the query-key factory and says, calmly, that
the read continues in the background, and when no worker has picked it up.
2026-10-03 18:18:56 +02:00
Marc-André Bombeck 911e642c24 i18n: encryption key backup step, refusal page and dashboard banner
Adds admin.keyBackup, admin.keyMismatch and dashboard.keyBackupBanner in
all seven locales.
2026-10-03 18:06:33 +02:00
Marc-André Bombeck 308470f229 feat(encryption): back up the key, and refuse to serve when it cannot open the database
Every configured key id now has a canary in encryption_key_canaries,
checked at boot. A key that cannot open its canary, or existing data
written before the canary existed, puts the process in a refusal state:
every API route answers 503 encryption.key_mismatch, /api/health reports
reason encryption_key_mismatch, the pages render one explanation, and
neither the queue producer nor the worker starts. The process stays up
so the reason is visible instead of hiding in a crash loop.

The admin Encryption page gains a "Back up your encryption key" step:
key id and fingerprint (never the key), where the key lives per
platform, a check of a pasted copy that is compared and discarded, and
a confirmation bound to the active key id and fingerprint. The overview
gets a tile and admins get a dashboard banner while it is due.

HEALTHLOG_PLATFORM picks the platform the step opens on. Adds the
TrueNAS self-hosting page and key backup sections in the docs.
2026-10-03 18:06:28 +02:00
Marc-André Bombeck 7022b698e7 fix(ai): forget the remembered working provider when the chain is saved
The in-memory memo of the last provider that answered reorders the
chain for up to an hour. Saving a new chain now drops it for that
account, so a provider the person removed or disabled no longer leads
the chain they just arranged.
2026-10-03 18:04:09 +02:00
Marc-André Bombeck 916f918674 feat(workouts): save an edited resubmit of a hand-entered workout
The manual form sends one manual: id per opening and resends it after
an edit. The batch route now treats a MANUAL entry with a manual: id
as an overwrite, the way stats: measurements are: the stored row takes
the new values and the entry reports "updated", or "duplicate" when
nothing changed. Records keyed on the workout are removed under the
personal-records lock and re-derived. Every other id stays
first-write-wins. The status enum gains "updated".
2026-10-03 17:59:20 +02:00
Marc-André Bombeck 87fa2f85fa Merge branch 'main' into ci/trivy-braces 2026-10-03 17:57:51 +02:00
Marc-André Bombeck 3cb98f92e9 Merge branch 'main' into docs/readme-thanks 2026-10-03 17:57:50 +02:00
Marc-André Bombeck 6bb65824bf fix(workouts): serialise record detection with a workout delete
The workout-slot detection reads the best workout and writes its record
inside one transaction under a per-user advisory lock, and the workout
DELETE takes the same lock before removing records and the workout. A
delete can no longer land between the read and the write and leave a
record for a workout that is gone.

The DELETE's match for a legacy record without an external id is scoped
to the slots of the deleted workout's sport, so a record another sport
set at the same instant stays.
2026-10-03 17:54:04 +02:00
Marc-André Bombeck ab081d2a85 fix(workouts): keep a deleted workout's insight slot spent
The insight claim row is now the daily-cap ledger. Its workout_id is
nullable with ON DELETE SET NULL (migration 0367), so deleting a workout
no longer frees the day's slot. The cap counts claims that reached the
provider plus live leases, and drops the separate count of insight rows.
A daily workout-insight-claim-cleanup queue removes claim rows untouched
for seven days.
2026-10-03 17:53:36 +02:00
Marc-André Bombeck ed94e56c5e Merge branch 'main' into fix/lab-unit-mismatch 2026-10-03 17:51:46 +02:00
Marc-André Bombeck b9867caeea Merge pull request #1098 from MBombeck/fix/backup-round-trip-tombstone-age
Keep the backup round-trip tombstone inside the retention window
2026-10-03 17:51:43 +02:00
Marc-André Bombeck 1d86bb8d6d i18n(labs): unit mismatch strings for es, fr, it, ko and pl 2026-10-03 17:45:05 +02:00
Marc-André Bombeck 296ca5d2dc ci(trivy): ignore the braces advisory until a fix is published
braces is reached only by development tooling and never ships in the
production image; no patched version exists yet.
2026-10-03 17:29:51 +02:00
Marc-André Bombeck 1dab2687ab docs(readme): thank contributors, reporters and supporters by what they gave 2026-10-03 17:29:34 +02:00
Marc-André Bombeck 86a6e81fc1 test(backup): keep the tombstone fixture inside the retention window
The round-trip fixture deleted its measurement on a fixed date. The restore
drops a measurement tombstone older than TOMBSTONE_RETENTION_DAYS (75) on
purpose, so on 2026-10-03 the fixture aged out and the suite failed on main
and on every open branch. The deletion is now ten days before the run.
2026-10-03 17:28:50 +02:00
BernhardBuckel d3916036c2 fix(labs): refuse a reading whose unit differs from its marker's
A numeric lab reading was stored with its value as received and the marker's
unit stamped on it, so 5.6 mmol/L against a marker kept in mg/dL became
5.6 mg/dL and read as far below range. Both the manual/API write and the
scan commit did this; nothing compared the two units.

- POST /api/labs returns 422 labs.unit.mismatch, with the marker's unit and
  the reading's unit in meta, and writes nothing. The unit is compared only
  when one was sent: on the biomarkerId path it may be omitted, and the
  marker's unit is then the stated one. A qualitative reading has no unit.
- The scan commit skips such a row with reason unit_mismatch, so the outcome
  reads partial or failed instead of a clean save, and the toast names the
  analytes concerned rather than saying "duplicates".
- The extract response carries the matched marker's unit. The review screen
  shows a calm badge on a row in another unit, starts it unticked like a
  duplicate, and treats it as a blocking error on the unit field if it is
  ticked anyway.
- A small lab-specific normaliser forgives spelling only: spacing, the micro
  prefix, the case of the litre, and a unit printed in capitals for a short
  list where capitals cannot mean another unit. Case is otherwise significant,
  so mIU/L and MIU/L, or g/L and G/L, are never merged.

The document-commit path already refuses a mismatch and is left as it is.
Readings stored wrongly before this cannot be identified, because the
original unit was never kept; they are not touched.

Adds EN and DE strings; the other locales are left to the maintainers. The
OpenAPI spec and the error-code catalogue carry the new code.

Fixes #1094
2026-10-03 15:44:51 +02:00
Marc-André Bombeck 556bd6d6cd Merge pull request #1093 from MBombeck/release/v1.39.9
Release v1.39.9
2026-10-03 00:57:24 +02:00
Marc-André Bombeck e42b3f331f chore(release): v1.39.9 — log a workout by hand, a page for body fat, and the AI response time everywhere 2026-10-03 00:35:27 +02:00
Marc-André Bombeck a14ae57283 fix(workouts): refuse a manual workout that would end in the future
The form's start defaults to the minute it opened, so a workout logged
right after it finished was stored as ending up to a day ahead. The
duration now fails validation when start + duration lies past now, with
the same one-minute slack the start check uses.
2026-10-03 00:35:26 +02:00
Marc-André Bombeck 2cd8b28a22 Merge pull request #1092 from MBombeck/fix/ai-timeout-everywhere
Run every model call under the AI response-timeout setting
2026-10-03 00:23:26 +02:00
Marc-André Bombeck bd2d43e402 Merge remote-tracking branch 'origin/fix/ai-timeout-everywhere' into fix/ai-timeout-everywhere 2026-10-03 00:03:31 +02:00
Marc-André Bombeck 0f6669847c Merge remote-tracking branch 'origin/main' into fix/ai-timeout-everywhere 2026-10-02 23:59:38 +02:00
Marc-André Bombeck 2473d52f19 Merge pull request #1089 from MBombeck/feat/manual-workout-entry
Log a workout by hand
2026-10-02 23:59:11 +02:00
Marc-André Bombeck e6e5bd0adc Merge pull request #1087 from MBombeck/fix/dashboard-tile-links
Every dashboard tile opens its chart; body fat gets its page
2026-10-02 23:50:43 +02:00
Marc-André Bombeck 3b1d503e87 Merge branch 'main' into fix/ai-timeout-everywhere 2026-10-02 23:20:26 +02:00
Marc-André Bombeck 57a99e6cc8 Merge branch 'main' into feat/manual-workout-entry 2026-10-02 23:20:24 +02:00
Marc-André Bombeck 774dff410c Merge branch 'main' into fix/dashboard-tile-links 2026-10-02 23:20:23 +02:00
Marc-André Bombeck 06f69e4408 Merge pull request #1091 from MBombeck/fix/e2e-lab-review-animations
Wait for the lab review sheet to stop sliding before measuring
2026-10-02 23:20:11 +02:00
Marc-André Bombeck ae0bdd0390 fix(settings): name the real response-timeout defaults
The placeholder said "Default (~120)" while most surfaces fall back to
60 s and the briefing to 180 s. The placeholder and the help line now
interpolate both numbers from the constants the server applies
(PROVIDER_DEFAULT_TIMEOUT_MS, AI_BUDGETS.comprehensive.timeoutMs), in
all seven locales, and a test fails if a locale writes a number of its
own.

Refs #1090
2026-10-02 23:17:37 +02:00
Marc-André Bombeck 6207101006 test(ai): guard that every model call runs under the response-timeout setting
Pins the four ways the setting could be skipped again: a wire client
reading params.timeoutMs itself instead of callTimeoutMs, an exported
resolver in provider.ts returning a provider it did not bind, a client
constructed outside provider.ts (the offline evaluation harness is the
named exception), and a surface ceiling not listed with its reason.
Each matcher asserts a non-zero match count.

Refs #1090
2026-10-02 23:03:45 +02:00
Marc-André Bombeck bf7fb9c401 fix(documents): wait as long as the server may on document reads and lab OCR
The browser gave up on its own: 120 s for the document routes, 90 s for
a lab scan, and the 15 s default on the lab text path, while a slow
self-hosted model with a raised response timeout was still allowed to
answer. A five-page report read by a local model failed on the client
side with the server still working.

Each request now sizes its abort from ai.provider.responseTimeoutMs on
the account payload, times the model calls the route can make, plus
30 s: one call for suggest and summary, three for Read with AI (the
transcription, then the lab staging read and its corrective retry), two
for a lab scan (the read and its retry). With the setting unset that is
90 s, 210 s and 150 s.

Refs #1090
2026-10-02 23:01:41 +02:00
Marc-André Bombeck 5ee1b3e28f fix(ai): run every model call under the response-timeout setting
The response-timeout setting reached the briefing, the status notes and
the Coach, which threaded it by hand. Document reads, document
extraction, lab OCR and lab staging called the provider without a
timeout, so every client fell back to its own 60 s literal and a slow
self-hosted model was cut off however high the setting stood.

The setting now rides on the provider instance. resolveProvider,
resolveProviderChain and resolveProviderForTest stamp the record's
aiResponseTimeoutSeconds on everything they return, and each wire
client reads its ceiling through callTimeoutMs: the setting, else the
surface's own timeoutMs, else 60 s. A call site no longer has to pass
it, so a new one cannot forget it. The connection test runs under the
same ceiling a read does.

The Coach nudge tick and the reaction line keep their short ceilings
(timeoutPolicy: "surface-ceiling"): the tick runs accounts one after
another under a shared budget, the reaction line's claim lease is
shorter than the largest setting, and both have deterministic copy
that stands in.

/api/auth/me publishes the effective value as
ai.provider.responseTimeoutMs, so a client can size its own request
timeout from it instead of guessing.

Refs #1090
2026-10-02 23:01:36 +02:00
Marc-André Bombeck c08dfc618f test(e2e): call a lab review field beside the value when it shares its row
The spec compared field tops within 8 px. A field label that wraps onto a
second line, which depends on the runner's font metrics, moves that
field's input down by one line while it stays in the same row, and the
560 px case failed on it. A field is now beside the value when it sits to
its right and starts above the value's bottom edge.
2026-10-02 22:56:27 +02:00
Marc-André Bombeck 4125d08fb4 test(e2e): wait for the lab review sheet to stop sliding before measuring
On a phone and a small tablet the review sheet slides up from the bottom;
its width settles before the slide ends, so waiting on width alone still
compared fields from different frames. The spec now waits for every
running animation to finish and for the surface to hold its position and
width across two frames.
2026-10-02 22:33:17 +02:00
Marc-André Bombeck b079e23a83 Merge remote-tracking branch 'origin/feat/manual-workout-entry' into feat/manual-workout-entry 2026-10-02 22:30:19 +02:00
Marc-André Bombeck 9e239dd6c5 build: re-measure the aggregate client budget for the manual workout entry
Main measured 3718 KB gz after v1.39.7 and v1.39.8, almost all of it new
copy in the seven lazy locale catalogs; the workout form, its sheet, the
delete action and their copy add about 7 KB (3725). The cap moves from
3724 to 3749, the same 24 KB headroom as before; the eager routes stay
inside their drift allowances.

Refs #1085
2026-10-02 22:30:09 +02:00
Marc-André Bombeck 11936ed93c Merge remote-tracking branch 'origin/main' into feat/manual-workout-entry 2026-10-02 22:28:44 +02:00
Marc-André Bombeck 1a403b78f7 Merge pull request #1086 from MBombeck/fix/audit-node-forge
Ignore the node-forge advisory until a fix is published
2026-10-02 22:16:59 +02:00
Marc-André Bombeck e6e1b51918 Merge branch 'main' into feat/manual-workout-entry 2026-10-02 21:49:45 +02:00
Marc-André Bombeck f0abe984b0 Merge branch 'main' into fix/dashboard-tile-links 2026-10-02 21:49:44 +02:00
Marc-André Bombeck 5dde6f785c Merge branch 'main' into fix/audit-node-forge 2026-10-02 21:49:42 +02:00
Marc-André Bombeck 1dd0609535 Merge pull request #1088 from MBombeck/fix/e2e-lab-review-settle
Measure the lab review rows once the dialog has settled
2026-10-02 21:49:31 +02:00
Marc-André Bombeck d9dfa7e5db test(dashboard): type the module cases of the add-menu parity check
Refs #1085
2026-10-02 21:44:37 +02:00
Marc-André Bombeck 69f19ec232 copy(workouts): mention manual entry in the empty workouts list
Refs #1085
2026-10-02 21:38:22 +02:00
Marc-André Bombeck cf678f6ec4 fix(dashboard): gate every add-menu entry on its module, as the capture picker does
The dashboard add menu asked only whether the record's section was
writable, so a switched-off mood or medications module still offered its
entry here while the bottom bar's picker hid it. The menu now renders from
the picker's own visibleCaptureKinds, so the two cannot disagree.

Refs #1085
2026-10-02 21:38:06 +02:00
Marc-André Bombeck 074cccd920 docs(api): regenerate the contract for the workout delete error code
Refs #1085
2026-10-02 21:36:24 +02:00
Marc-André Bombeck 2979b5c4ef test(e2e): measure the lab review rows once the dialog has stopped widening
The review stage widens the sheet and the row grid re-flows from the
container width; on a slow runner the 560 px case measured a half-laid-out
row and failed on the first attempt. The spec now waits until the surface
keeps its width across two frames before it measures.
2026-10-02 21:33:31 +02:00
Marc-André Bombeck 6eb79a1d47 fix(workouts): report manual saves through the outcome module and register the delete
A repeated submit that wrote nothing reads as a neutral notice rather
than a success. The delete control is entered in the destructive-control
registry, and its 409 code in the published error catalogue.

Refs #1085
2026-10-02 21:31:25 +02:00
Marc-André Bombeck cfbb57ab3e test(workouts): format the manual-entry integration suite
Refs #1085
2026-10-02 21:28:07 +02:00
Marc-André Bombeck 92ce699792 test(workouts): drive a hand-entered workout through the real routes
Builds the entry the form sends, posts it through the batch route, reads
it back from the list, re-posts it as a duplicate, and deletes it; a
synced workout is refused.

Refs #1085
2026-10-02 21:25:36 +02:00
Marc-André Bombeck 715268c62b feat(workouts): offer Log workout in the add menu and the capture picker
The dashboard add menu and the bottom bar's capture picker gain a
workout entry next to measurement, mood and medication. It belongs to
the workouts module (capture:workout) and is offered in one's own record
only, because the batch ingest resolves the caller and no grant reaches
it.

Refs #1085
2026-10-02 21:23:01 +02:00
Marc-André Bombeck e0fc879d72 feat(workouts): log a workout by hand from the workouts page
A small sheet with sport, start, duration and optionally distance and
active energy, nothing else. The start is read in the profile timezone,
distance in the reader's unit and stored in metres. It saves through
POST /api/workouts/batch as source MANUAL with an external id minted once
per opened form, so a second tap lands as a duplicate, not a second row.

The workouts page carries the action in its header and in the empty
state; the detail page offers delete for a hand-entered workout.

Refs #1085
2026-10-02 21:22:56 +02:00
Marc-André Bombeck 5e6fd327a5 feat(workouts): delete a workout entered by hand
DELETE /api/workouts/{id} removes a MANUAL workout outright, with its
child rows and the personal records keyed on it, then queues a silent
detection pass so the previous best comes back. Any other source answers
409: the next sync would write it back. Own record only, 404 for another
user's row.

Refs #1085
2026-10-02 21:22:56 +02:00
Marc-André Bombeck 885efaafd9 fix(dashboard): open the body fat page from the body fat tile
The body fat tile was the one strip tile that led nowhere. Its href map
said there was no dedicated sub-page, which was true: body fat percentage
was tiled and charted on the dashboard but never got the Insights page
every body-composition sibling has.

Add /insights/body-fat on the generic metric-page scaffold (body group,
tab-strip pill, seven locales, manual-entry empty state) and link the
tile to it.

Move the tile href map out of the page into tile-destinations.ts, keyed by
the tile-capable widget id and typed against the sub-page slug union, so
a missing or non-existent destination fails to compile. The link passes
the destination's insights-page surface gate, so it never points at a
page a switched-off module hides.

A guard derives the tile set from TILE_CAPABLE_WIDGET_IDS and from the
ids the dashboard actually pushes into its strip, and fails when a tile's
metric has a sub-page the tile does not open, when a destination has no
route, or when a tile links to a page owned by another module. Tiles that
deliberately lead nowhere need a written reason; there are none today.

The reverse-lookup test pinned BODY_FAT as having no page; it now
resolves to body-fat.

Refs #1084
2026-10-02 21:21:38 +02:00
Marc-André Bombeck 0cb193f812 chore(deps): carry the node-forge advisory in the Trivy ignore list too
Same advisory, same reasoning as the pnpm audit entry: the affected
signature verification sits in node-apn's certificate credential path,
which token-authenticated APNs never reaches, and no fix is published.
2026-10-02 21:06:37 +02:00
Marc-André Bombeck 2ea9dc3936 Merge pull request #1059 from BernhardBuckel/feat/ocr-review-wide-dialog
feat(labs): give the lab-scan review stage the width a large screen offers
2026-10-02 21:04:36 +02:00
Marc-André Bombeck 2031b5a722 chore(deps): ignore the node-forge advisory until a fix is published
GHSA-86w9-cpqp-85rv affects RSA PKCS#1 v1.5 signature verification in
node-forge up to 1.4.0, which arrives only through @parse/node-apn for
certificate-based APNs credentials. HealthLog uses token authentication,
so that path never runs, and no patched release exists yet.
2026-10-02 21:03:43 +02:00
BernhardBuckel a2a3414b29 feat(labs): give the lab-scan review stage the width a large screen offers
The review stage is a list of readings to compare and correct, but it sat in
the default 448 px dialog, so with several readings it only grew taller.

- ResponsiveSheet gains an opt-in 6xl width tier (72rem). Nothing else
  changes width; the Sheet branch on phones ignores the tier as before.
- The review stage uses it. The picking stage stays narrow.
- Each row lays out from the width of its container, not the window:
  stacked in a narrow dialog, and once the dialog is wide enough the reading
  sits on the left with its fields on the right.
- The field grid (value, unit, date) is a container of its own, so it takes
  three columns when the fields have room for them, whatever the window
  width. The result-text span follows the same query.
- The dialog-overflow e2e spec covers the review stage at 390, 560, 768,
  1280, 1920 and 3440 px. 560 is wider than a phone's field grid needs but
  below the window sm breakpoint, which is what tells a container query from
  a window one.

Refs #1056
2026-10-02 09:14:51 +02:00
Marc-André Bombeck 23b813f447 Merge pull request #1083 from MBombeck/ci/e2e-three-shards
Run e2e in three shards with a 30-minute cap
2026-10-02 01:23:25 +02:00
Marc-André Bombeck 1d65ffabad Merge pull request #1082 from MBombeck/release/v1.39.8
Release v1.39.8
2026-10-02 00:44:24 +02:00
Marc-André Bombeck 95f8fbb1f2 ci: run e2e in three shards with a 30-minute cap
Two shards took 14 to 19 minutes against a 20-minute cap after the mobile
route sweep landed, and a slow runner cancelled one twice in a week.
2026-10-02 00:28:57 +02:00
Marc-André Bombeck fe9a94c853 chore(release): v1.39.8 — new ECGs from the iPhone get through, resting heart rate by hand, and ranges, decimals and dates as you read them 2026-10-02 00:06:09 +02:00
Marc-André Bombeck 1399cca4d0 Merge pull request #1081 from MBombeck/fix/v1398-polish
Glucose bands, decimals, calendar dates and chart axes as the reader expects
2026-10-01 22:51:34 +02:00
Marc-André Bombeck ba426706be Merge remote-tracking branch 'origin/main' into fix/v1398-polish 2026-10-01 22:23:09 +02:00
Marc-André Bombeck 90e8940a81 Merge pull request #1080 from MBombeck/fix/v1398-ecg-rate-resting
Let a whole ECG sweep through; log a resting heart rate by hand
2026-10-01 22:22:42 +02:00
Marc-André Bombeck debd44a75b fix(charts): keep axis unit labels on one line; 44 px date and time triggers
Recharts word-wraps a tick label that it measures wider than its axis,
and it measures in the page's body font rather than the tick's 11 px.
"62 bpm" on the pulse chart under a workout and "106 mg/dL" on the
glucose page therefore broke onto two lines at every width, and the
pulse chart's second line sat on the first x tick. Axis units are now
joined with a no-break space through `axisUnitSuffix`, so the label is
one word and stays on one line. A guard fails when a chart axis joins a
unit with a plain space.

The calendar and clock buttons in the date and time fields paint at
32 px; a `::before` halo now gives them a 44 px touch target without
changing the field.
2026-10-01 22:18:28 +02:00
Marc-André Bombeck 801295f55a fix(dates): read date-only lab and document dates as calendar dates
A date-only value is stored at 12:00 UTC. The lab list and history, the
document cards and pickers, the document date suggestion, extracted
fact dates, source-picker rows and the compliance and mood heatmaps
formatted that instant in the reader's zone, which is the next day from
UTC+12 to UTC+14.

`useCalendarDate` formats such a value through the UTC-pinned calendar
formatter the vaccination list already uses, with the same field order
and locale as instant dates. Lab readings hold both kinds, so
`useLabDate` reads a noon-UTC anchor as its calendar date and a reading
typed with its time of day in the reader's zone. A document without a
filing date shows its upload day, an instant, in the reader's zone.
2026-10-01 22:14:07 +02:00
Marc-André Bombeck fe13fa966b fix(labs): print range bars and lab values in the reader's number format
Range bars and the lab list, detail rows, chart tooltip and reference
ranges printed numbers with a plain `String()`, so a German reader saw
"1.8 mIU/L" and "61.3 kg" under a German interface. The same was true
of the mean, GMI, eA1C and the advanced indices on the glucose panel.

`RangeBar` now prints value, bounds and delta through the locale number
formatter and takes an optional `formatValue` for surfaces with their
own precision. Lab values keep their trim rule (whole numbers bare, at
most two decimals) in `formatLabValue`, which now hands the digits to a
caller-supplied locale formatter; `useLabNumber` wires it to the
reader's locale for every lab surface. Inputs are unchanged.
2026-10-01 22:09:30 +02:00
Marc-André Bombeck 75361d0666 fix(glucose): state band edges in the reader's glucose unit
The time-in-range labels in the doctor report, the target caption on
the glucose panel, the glucose page description and the fasting
explainer printed fixed mg/dL figures, so a reader on mmol/L saw
"Low (< 70 mg/dL)" beside values in mmol/L.

The cut-points now live in one place (`GLUCOSE_TIR_CUT_POINTS`,
`GLUCOSE_FASTING_CUT_POINTS`) with the SI figure each guideline prints,
the analytics engine counts its bands from the same constants, and
every sentence takes the band edges and unit as parameters through
`glucoseBandParams`, formatted with the reader's number format.

The unit-preference guard now also reads the locale bundles: a string
that names mg/dL or mmol/L fails unless it is allowlisted with a
reason.

Refs #1067
2026-10-01 22:07:07 +02:00
Marc-André Bombeck 4120927a94 fix(workouts): count a bridge's batches apart from the phone's
A workouts:write token and the iPhone app shared one per-account bucket of
60 batches a minute, so a bridge stuck in a retry loop could use up the
allowance the phone needs to sync the same account. Scoped tokens now count
in a bucket of their own, shared by all bridge tokens of the account so
that minting more tokens does not multiply the allowance.

Refs #1054
2026-10-01 22:00:12 +02:00
Marc-André Bombeck 08d5acdcb5 feat(measurements): log a resting heart rate by hand
The entry form offered pulse but not resting heart rate, which has its own
chart and series, so a value read off a watch or taken on waking could only
land among spot pulses. The form now offers it next to pulse. The server
already gates the type on the recovery module (its resting_hr domain), so
the form, the dashboard summary, the resting-pulse page, its trend slot and
its correlation channel now follow that module too.

Refs #1079
2026-10-01 21:53:38 +02:00
Marc-André Bombeck 82ccac2fd0 fix(ecg): let a whole sweep of recordings through the ingest limit
The iPhone app posts every ECG its sweep has not yet consumed and, on a
429, stops and restarts the same sweep on its next wake. With a limit of
60 per minute a sweep of 61 or more could never finish: the same last
recording was refused on every sync, so the newest ECG never arrived. The
limit is 600 per minute now, enough for more than a decade of weekly
strips in one sweep.

Refs #1060
2026-10-01 21:53:37 +02:00
Marc-André Bombeck fc47006c88 Merge pull request #1078 from MBombeck/release/v1.39.7
Release v1.39.7
2026-10-01 15:54:47 +02:00
Marc-André Bombeck 9175aea316 chore(release): v1.39.7 — your units, your day and your phone, everywhere, and backups that keep your settings 2026-10-01 15:34:08 +02:00
Marc-André Bombeck bef17ee570 Merge pull request #1077 from MBombeck/fix/v1397-units2
AI and Coach texts in the reader's units
2026-10-01 14:09:35 +02:00
Marc-André Bombeck 661378bfa9 Merge remote-tracking branch 'origin/main' into fix/v1397-units2 2026-10-01 13:47:10 +02:00
Marc-André Bombeck cd3ab17520 Merge pull request #1076 from MBombeck/fix/v1397-account-backup
Back up account settings and the module selection
2026-10-01 13:47:02 +02:00
Marc-André Bombeck 615f5a8070 test(units): sweep the AI and Coach producers for unit literals
The unit sweep covered the display trees and the insight library; the
prompt and snapshot builders, the text-writing jobs and the target and
digest producers were outside it, which is where a band in mg/dL, a
threshold in kg/week and a distance in metres reached the model. The
sweep now walks those trees too and matches prose units ("kg/week",
"5 metres") as well as symbols. The four allowlist entries for prompts
that stated weight in kilograms are gone with the literals; the new
entries each name why the literal is not a reader-facing unit.

A line scanner cannot see a canonical number printed with no unit at
all, so the guard also names every producer that carries a
preference-dependent figure into a prompt, a snapshot or a stored
sentence and requires each to call a reader-unit resolver. The canonical
weight signal of the day loses its kilogram label; the reader's unit is
attached where the signal is converted.

Refs #1067
2026-10-01 13:23:17 +02:00
Marc-André Bombeck 0028290117 fix(cycle): read basal temperature and the unit-bearing chart titles in the reader's units
The basal body temperature field, its chart and its tooltip were fixed
to degrees Celsius whatever the reader had chosen: the placeholder said
°C, the field accepted only 30-45, the chart plotted Celsius and the
tooltip printed "{temp} °C". Two chart titles carried a fixed unit as
well ("Wrist temperature (°C)", "Walking speed (km/h)") above an axis
already in the reader's unit.

The field now reads and writes in the reader's unit and stores Celsius;
a reading the person did not touch is saved back unchanged rather than
through a round trip of rounding. The chart plots, pads and labels in
the reader's unit, the two titles drop the unit the axis already
names, and the cycle contrast's fixed kg, °C and mg/dL labels, which
the transform had already replaced, leave the bundles.

Refs #1067
2026-10-01 13:23:17 +02:00
Marc-André Bombeck 43be8ebd43 fix(jobs): hand the reaction line its new datum in the reader's units
The reaction line read the arrived weight with its stored unit (kg) and
a workout distance in metres, whatever the reader had chosen, so the
sentence written about the new reading could quote kilograms to a
reader on pounds. The evidence now converts the reading and the
distance into the reader's units before the prompt is built.

Refs #1067
2026-10-01 13:23:17 +02:00
Marc-André Bombeck 7cb1b5ba05 fix(insights): write the weight note and its thresholds in the reader's mass unit
The weight status note had its own generator and never took the unit
preference: its signal, summary, graded series, latest-day figure,
target band and correlation pairs were all in kilograms, and the card
prompt stated the normal day-to-day swing, the plateau line and the
loss pace in kilograms too. A reader on pounds was handed both units.

The generator now converts every weight figure once after the canonical
arithmetic (the correlations are scale-free and stay as computed), the
card prompt states its thresholds in the reader's unit, and the unit
preference joins the input fingerprint so a switch is never answered
with the old note. The shared status-card examples and the briefing's
plateau pattern no longer show a weight in kilograms for the model to
copy.

Refs #1067
2026-10-01 13:23:17 +02:00
Marc-André Bombeck d11c165675 fix(coach): read the cycle contrast and the metric table in the reader's units
The cycle block's headline contrast labelled weight in kg and the
temperatures in °C, and left a glucose contrast without any unit. The
metric table, which the person sees and whose summary the model reads,
listed weight in kilograms, temperatures in degrees Celsius, walking
speed in metres per second and distance in metres.

The cycle contrast now converts both means and the gap into the
reader's units (the gap by the factor alone) and names the unit in its
sentence. The table resolves each column's unit and decimals from the
reader's preferences and converts every folded period value once; the
snapshot carries the preferences it was written in, so the table and
the snapshot of a turn always agree.

Refs #1067
2026-10-01 13:23:17 +02:00
Marc-André Bombeck ca5ce518d8 fix(coach): state the snapshot's weight, body and distance figures in the reader's units
The Coach snapshot carried weight, body composition, temperatures and
walking speed and distance as stored: kilograms, degrees Celsius, metres
per second and metres, with no unit on the block. The evidence-block
rules then listed kg and both glucose units as the units to cite. A
reader on pounds, Fahrenheit or miles was answered in the units they do
not use.

Every value block now converts its timeline (and the weight block its
aggregate and coarse tail) into the reader's units after aggregating on
the canonical value, and names the unit on the block; the grounding
scalars stay canonical. Workout distances arrive in kilometres or miles
with the unit named once. The prompt in every locale tells the model
that a block's figures are already in the reader's unit and takes the
evidence-block unit from the block instead of a fixed list.

Refs #1067
2026-10-01 13:23:17 +02:00
Marc-André Bombeck a7e6b89672 fix(insights): hand the briefing its figures in the reader's units
The daily briefing serialised the aggregated feature set as computed:
weight, grip strength and the weight target in kilograms, waist in
centimetres, glucose and the signals of the day in mg/dL (the glucose
signal carried no unit at all), workout distances in kilometres. A
reader on pounds or mmol/L got a briefing in units they do not use.

One step now converts the feature set after all canonical arithmetic,
on both the nightly and the on-demand path: absolute values through the
full transform, differences and slopes through the factor alone, every
converted block labelled, workout distances under unit-neutral keys.
The prompt, the stored fingerprint and the grounding check all read the
converted set, so a unit switch moves the fingerprint and the grounding
check compares the reply against the figures the model was shown. The
weight target sentence, the comparison block and the GLP-1 plateau
context quote weight in the reader's unit; the comparison block also
labelled sleep as hours while carrying minutes.

A unit switch now also re-warms a cached briefing alongside the status
notes and narratives.

Refs #1067
2026-10-01 13:23:17 +02:00
Marc-André Bombeck d1b2539b1f fix(coach): state reference and time-in-range bands in the reader's units
The reference grounding printed the fasting glucose bands in mg/dL and
the body-temperature band in °C, and the system prompt described time
in range as 70-180 mg/dL. For a reader on mmol/L or Fahrenheit the
model was handed one quantity in two units: the glucose block in
mmol/L, the band beside it in mg/dL.

The grounding block now takes both unit preferences and prints the
general, the diabetes goal and the temperature band in them, while the
placement is still classified on the canonical value. The glucose
block carries the time-in-range band in its own unit, and the prompt
points the model at it instead of naming a unit.

Refs #1067
2026-10-01 13:23:17 +02:00
Marc-André Bombeck 6dbf57f4f4 fix(ai): name the acute glucose and fever floors in both units
The acute red-flag clause stated the glucose floors only in mg/dL and the
sustained-fever floor only in °C. The clause is matched against what the
person writes, so a reading of 2.9 mmol/L or 103 °F did not meet any of
its numbers. Each floor now carries both units, mg/dL and °C first, in
the English and German contracts.

Refs #1067
2026-10-01 13:23:17 +02:00
Marc-André Bombeck 8b84e08145 Merge remote-tracking branch 'origin/main' into fix/v1397-account-backup 2026-10-01 13:21:55 +02:00
Marc-André Bombeck 9cab8e74da Merge pull request #1075 from MBombeck/fix/v1397-ecg-ingest
Accept the fractional heart rate and frequency HealthKit reports for ECGs
2026-10-01 13:21:31 +02:00
Marc-André Bombeck f9babade02 chore(openapi): regenerate for the account settings backup section 2026-10-01 13:12:28 +02:00
Marc-André Bombeck ff8277695a test(backup): round-trip every account setting through a real restore
Fill every User column on the source account, export through the streaming
writer, recreate the account with credentials of its own, restore through the
route, and compare: each setting column must come back with the value it left
with, and every identity, credential and bookkeeping column must still hold
the target's value. The section in the file is checked to carry nothing but
setting columns.
2026-10-01 13:12:25 +02:00
Marc-André Bombeck 7abaa25c14 feat(backup): export the account settings and restore them onto the account
Both backup purposes now carry an accountSettings section. The restore writes
it to the account being restored inside the same transaction, names every
refused value under the new accountSetting skip catalogue, and re-warms the
stored texts after the transaction when a unit preference changed, the way the
unit settings routes do. A file without the section leaves the account row as
it is, which is how every older backup restores. The instance settings
restore stays its own opt-in.
2026-10-01 13:04:41 +02:00
Marc-André Bombeck d731a1b8fe feat(backup): classify every User column and carry the account settings
Every column of the account row now has a backup verdict in
USER_COLUMN_BACKUP_CLASS: SETTING, CREDENTIAL, IDENTITY or OPERATIONAL. A
schema-derived guard fails on an unclassified column, and the setting columns
each get a codec in account-settings-backup.ts, so a column classified as a
setting without a way to travel does not compile.

The restore end checks each value the way the settings route that writes it
does: AI endpoints against this host's private-origin policy, languages, units
and time zones against the known vocabularies, threshold bands against their
bounds, the avatar against the upload's sniff and limits. A refused value is
left out and named; credentials, identity and the host's own cursors are never
admitted.
2026-10-01 13:04:36 +02:00
Marc-André Bombeck 729401e032 chore(openapi): describe the rounded ECG heart rate and frequency 2026-10-01 12:53:25 +02:00
Marc-André Bombeck 0dfce73570 fix(ecg): accept the fractional heart rate and frequency HealthKit reports
The ingest route required integers for the average heart rate and the
sampling frequency. HealthKit reports both as doubles and a watch's average
heart rate is often fractional, so most new recordings were refused with
422 while older ones, whose value happened to be whole, went through. Both
are now accepted as numbers and rounded once before they are stored; the
columns stay integers. A refused body now logs which fields were refused
and why, never their values.

Refs #1060
2026-10-01 12:50:08 +02:00
Marc-André Bombeck 28054e69c2 Merge pull request #1074 from MBombeck/fix/v1397-meta
Every guard must be able to fail; every backed-up column must round-trip
2026-10-01 11:57:12 +02:00
Marc-André Bombeck 6725110b25 chore(openapi): regenerate for the backup fields that now round-trip 2026-10-01 11:34:19 +02:00
Marc-André Bombeck 383323b542 Merge remote-tracking branch 'origin/main' into fix/v1397-meta 2026-10-01 11:29:08 +02:00
Marc-André Bombeck 4e4bc6f8be Merge pull request #1073 from MBombeck/fix/v1397-tz
Compute every user-facing day in the user's zone, and refuse new UTC day keys
2026-10-01 11:28:57 +02:00
Marc-André Bombeck 03eced171e Merge remote-tracking branch 'origin/main' into fix/v1397-meta 2026-10-01 11:25:06 +02:00
Marc-André Bombeck d1a7406ff7 test: pin the nutrient source marker and arrival time in the payload builder test 2026-10-01 11:24:25 +02:00
Marc-André Bombeck b7a3b0d331 test: round-trip every column of every two-ended model
The round-trip test proved that a row of each two-ended model comes back,
not that it comes back whole. A restore that writes the row with a column
defaulted returns the right count and loses the value; the medication
category went missing that way.

The new case lists each model's columns from the client's data model,
with optional/default/key attributes from schema.prisma (the two field
lists must agree). Columns the fixture left empty get a value that cannot
pass for a default, one column at a time so a refused value names its
column. Then it exports, deletes the account, restores, and compares each
column as a multiset of values: sealed columns by their plaintext, a
legacy plaintext column together with its sealed twin, declared foreign
keys by presence, primary keys, owner and @updatedAt excluded by rule.

A column added tomorrow is compared automatically: it comes back, or it
is named in COLUMN_EXCLUSIONS with a reason. Entries naming a column that
no longer exists fail. A pure case shows the comparison catches a column
it was never told about, and the run asserts at least 620 columns
compared (632 today). Removing the workout source marker, a schedule
label, the folded-cycle pointer or the nutrient createdAt from either end
each fails the run naming that column.
2026-10-01 11:17:44 +02:00
Marc-André Bombeck 3f5bcbd441 fix(backup): carry four columns the restore was dropping
A column-level round trip over every two-ended model found four values
that left with the export and came back empty or re-stamped:

- MenstrualCycle.absorbedIntoId: the disaster-recovery file carried the
  folded, soft-deleted start but not the start that absorbed it, so after
  a restore removing the absorbing start could no longer bring the folded
  one back. Carried in the disaster-recovery arm and written back only
  when the file carries the start it names.
- Workout.externalSourceVersion: the source's version marker, stored so
  the sync can replay it unchanged, was in neither end. Carried beside
  metadata in the disaster-recovery arm.
- NutrientIntakeDay.externalSourceVersion and createdAt: neither was
  selected, so a restored day lost its source marker and its first-arrival
  time. Carried in both arms.

Files written before this change parse as before; every new field is
optional on the way in.
2026-10-01 11:17:44 +02:00
Marc-André Bombeck ada490c7e9 Merge remote-tracking branch 'origin/main' into fix/v1397-tz 2026-10-01 10:59:51 +02:00
Marc-André Bombeck e2685cec67 Merge pull request #1072 from MBombeck/fix/v1397-derive
Serve resolved values to the client and report what a write left out
2026-10-01 10:59:31 +02:00
Marc-André Bombeck f3bf65fb4e test: fail any structural guard that cannot fail on an empty sweep
guard-floor-guard reads every *-guard(s).test file under src/ and every
test that walks a directory, parses it with the TypeScript compiler, and
fails unless it asserts a floor on what it found: requireFloor,
scanSourceMatches, toBeGreaterThan, an exact non-zero count, or an exact
non-empty set. A floor on the walk alone does not count; the Bearer-scope
guard had one and still matched nothing for weeks.

Files that are not scanners (unit tests of runtime functions named
"guard", fixed file lists with a positive match per file, temp-directory
listings) are named with a reason. An exemption that goes stale fails the
run. The reader's own shapes are pinned by probe sources, including the
ones it must not count: comments, strings, .not, zero floors, it.skip.

It answers per file, not per matcher, and says so.
2026-10-01 10:52:48 +02:00
Marc-André Bombeck b4577f5c31 test: give every scanning guard a floor on what it found
A guard that compares a sweep against an allowlist, or against "none of
these may exist", passes when the sweep comes back empty. walkSourceFiles
already refuses a short walk; this adds the same refusal for what a guard
does with the walk.

- requireFloor(label, found, floor) throws below the floor and refuses a
  floor of zero.
- scanSourceMatches(root, pattern, { fileFloor, matchFloor }) walks, matches
  and floors both the files read and the hits found.

Floors added, pinned at the current counts:

- coach_usage owner columns: the clauses it actually examined (6).
- measurement reference index: the foreign keys it extracted (2).
- job outcome fact inventory: job files (130, floor 120) and fact keys
  (399, floor 350).
- tone harness: assessment prompt modules (11).
- coach locale default: turn pipeline modules (15, floor 12).
- locale integrity: message bundles (7).
- settings card header coverage and settings anatomy: the walked cards.
- coach metric scope inventory: insight route sources.
- side-effect drift guard: both enums populated, since two empty keysets
  are equal.

The pill-mapper guard walked with globSync, which skips dot-prefixed
directories; it now walks through walkSourceFiles like the rest.
2026-10-01 10:52:48 +02:00
Marc-André Bombeck 27ac4c1d63 Merge origin/main into fix/v1397-tz 2026-10-01 10:39:26 +02:00
Marc-André Bombeck da8cc7a6ee Merge remote-tracking branch 'origin/main' into fix/v1397-derive 2026-10-01 10:34:17 +02:00
Marc-André Bombeck a3b5480d04 Merge pull request #1069 from MBombeck/fix/v1397-units
One unit system: every surface follows the reader's glucose and metric/imperial preference
2026-10-01 10:34:06 +02:00
Marc-André Bombeck 533b75fdcf Merge remote-tracking branch 'origin/main' into fix/v1397-derive 2026-10-01 10:30:10 +02:00
Marc-André Bombeck 9b9e1929b5 Merge pull request #1071 from MBombeck/fix/v1397-mobile
Make the signed-in app work on a phone, starting with lab results
2026-10-01 10:27:06 +02:00
Marc-André Bombeck 4a012be37e Merge branch 'main' into fix/v1397-units 2026-10-01 10:12:47 +02:00
Marc-André Bombeck 414b099972 test(guard): freeze client reads of server-resolved fields
A per-field registry of the answers the server resolves for the record on
screen (the blood-pressure target band, intakeActionable and courseStatus,
the AI capability, the module surfaces) and the ingredient shapes that
rebuild them in the browser: getBpTargets() on the viewer's age, a dose
offered from active and trackIntake, course state from endsOn against the
clock, the raw disableCoach column, server resolvers imported into client
code. A match in client code fails unless the file is allowlisted with the
reason it is not a rebuild; the switches that edit a stored value are the
allowlisted readers.

The walk carries a floor, every pattern is checked against a sample of the
shape it catches, a stale allowlist entry fails, and the total match count
must be non-zero. Putting back each of the three rebuilds this release
removed fails the guard.
2026-10-01 10:09:28 +02:00
Marc-André Bombeck 1200d1bb05 Merge pull request #1070 from MBombeck/fix/v1397-dense
Fold dense reads in requests and give every job queue a declared runtime
2026-10-01 10:07:08 +02:00
Marc-André Bombeck 5e21363e0f docs(comments): correct four comments that describe gates and mints that no longer exist
- /api/auth/me and the AuthUser type described disableCoach as the gate
  every Coach surface checks below a flags.coach short-circuit. Neither has
  been true since the AI capability resolution: it is the account's stored
  opt-out, and surfaces read ai.capabilities.coach or modules.coach.
- /api/mcp/tokens claimed /api/tokens mints medication:ingest; that mint was
  removed, and the medication pair now comes from the per-medication
  endpoint toggle.
- /api/meta/capabilities listed the token kinds as wildcard, medication
  ingest or MCP, missing measurements:write, workouts:write and
  documents:write. Comment only: the served scopeMintable answer for the
  FHIR face is unchanged and still right.
2026-10-01 10:06:39 +02:00
Marc-André Bombeck 5f548d331f fix(labs): say when a scanned PDF was read from its first pages only
A PDF longer than the pages a scan renders was read from its first ten
pages, and the cut was recorded only in the wide event. The person checking
the extracted rows had no way to know that values on later pages were never
read.

The rasterizer now returns the PDF's page count, the extract response
carries pageCoverage { read, total } when the cap applied, and the review
screen says how many of the pages were read.
2026-10-01 10:05:35 +02:00
Marc-André Bombeck 5caa15f4e1 fix(google-health): count sleep segments with a stage label the mapper does not know
A segment whose stage label was unknown (SLEEP_STAGE_TYPE_UNSPECIFIED, or a
label added upstream later) was skipped without a trace, so the night total
read short and nothing said why. The mapper now counts those segments and
keeps their labels, and the sleep sync puts both on its wide event.
2026-10-01 10:05:35 +02:00
Marc-André Bombeck 8821fdeb54 test(tz): run core day paths with the host at both edges of the clock
The suite and the production image both sit near UTC, so a UTC day and a
local day agree for most of every day and day-boundary defects kept
passing. The harness sets the host zone in code to Los Angeles and to
Kiritimati, gives the account the same zone, and checks a schedule slot,
a course's last day, a mood entry, the dashboard summary's mood instant
and a document date round trip at the instant where the local and the
UTC day differ. Unit tests cover the new date-only and key helpers.
2026-10-01 10:02:50 +02:00
Marc-André Bombeck e37263e8cc fix(vaccinations): render a dose date through the calendar-date formatter
The noon-UTC rendering trick fixes the day west of UTC and moves it east
of UTC+12. A dose date is a calendar date, so it goes through the
UTC-pinned formatter the date fields already use, which is right in every
zone.
2026-10-01 10:01:17 +02:00
Marc-André Bombeck 06e86ef584 fix(ui): keep the page-header title a sibling of its description
The grid change wrapped the heading in a cell div, which separated it
from the description paragraph the settings-score spec reads as its
following sibling. The heading is the grid item itself now.
2026-10-01 10:01:14 +02:00
Marc-André Bombeck a66976874e fix(mood): report the tag and factor keys a mood write did not store
An unknown or archived tag key, or a factor the catalog no longer carries,
was dropped on the way in while the entry still reported "inserted" (bulk)
or 201 (create, edit). A client had no way to tell that part of what it sent
never landed.

Each write now names those keys: the bulk result per entry, the create and
edit responses on the entry, as droppedTagKeys and droppedFactorKeys. Both
are present only when non-empty, so a response where everything landed is
unchanged. An archived tag an edit preserved is on the entry and is not
listed. The web shows a short notice after saving when a picked tag was left
off.
2026-10-01 10:01:06 +02:00
Marc-André Bombeck 7c5ff89def feat(lint): refuse UTC day keys outside the time zone module
`instant.toISOString().slice(0, 10)` and parsing a key back as UTC
midnight are the idioms behind every day-boundary fix this year: the
evening west of UTC and the small hours east of it land on the
neighbouring day. A new rule, healthlog/no-utc-day-key, refuses them in
src/ outside src/lib/tz and tests, and refuses a disable directive for
itself that is not next-line or gives no reason.

The time zone module now names every legitimate form: userDayKey for a
person's day, dateOnlyKey / dateOnlyAtNoonUtc / dayKeyAsUtcMidnight for
date-only values and day labels, daysBetweenDateKeys / weekdayOfDateKey /
isCalendarDateKey / statedDateKey for key arithmetic and parsing.

Of the 133 sites the rule found, 84 are gone. Most moved onto a named
helper with no change in behaviour; these changed behaviour:

- cycle calendar, insights, Coach snapshot and prediction refresh start
  their lookbacks at the first instant of the user's day
- a model-transcribed date like "June 10, 2026" no longer lands a day
  early in a process east of UTC (documents and lab scans)
- a custom report range covers exactly the picked days in the profile
  zone instead of starting the evening before west of UTC
- date-of-birth pickers cap at the user's today, not the UTC one
- an allergy onset date is stored at noon UTC like other date-only values
- the report's cycle summary, the Coach's usual BP range and the intake
  projector's rollup recompute use the user's day
- vaccination dates render as dates instead of the previous evening

49 remain, each with its reason on the line above: 39 UTC by design (15
file name stamps, rollup and object keys, the UTC-day score engines) and
10 marked baseline. A guard test requires a classified reason on every
directive and holds the baseline to a ceiling that only goes down.
2026-10-01 09:59:57 +02:00
Marc-André Bombeck a1fa84dcdf chore(units): drop the preference loader nothing calls yet 2026-10-01 09:53:45 +02:00
Marc-André Bombeck fdbbd3a84a fix(settings): gate the Coach tuning on the record's module state
Settings → Coach hid its preference and nudge cards on the raw disableCoach
column, which /me publishes for the signed-in person. Inside a managed or
shared record that answered for the wrong person: a guardian with the Coach
on saw the tuning for a record that has it off, and the other way round.

The cards now read the module map the server resolves for the record on
screen, the same map the navigation and the settings entry already follow.
2026-10-01 09:50:41 +02:00
Marc-André Bombeck 64c0b25411 test(e2e): open the labs sheet in German in the dialog overflow spec
The three-button footer fits a phone row in English, so the English
case never saw Cancel leave the sheet. A German case at every width
fails against the old footer (checked) and passes against the fix.
2026-10-01 09:49:19 +02:00
Marc-André Bombeck eae46ed535 fix(medications): preselect only a dose offered today, graded by the account's thresholds
The intake pickers chose their default from every active medication, so a
course that had ended but was not archived could be the preselected dose.
The default now reads the server's intakeActionable answer; the medications
page dialog still lists ended courses for back-filling a past dose, they are
just never the default.

Both pickers also graded "due" against the fixed 120 / 240-minute defaults
while the cards beside them used the account's own late and missed
thresholds. They read the same thresholds now.
2026-10-01 09:48:48 +02:00
Marc-André Bombeck ef420f9e2a fix(insights): draw the blood-pressure zones from the record's resolved band
The blood-pressure chart rebuilt its target zones in the browser from the
signed-in account's date of birth. A band the person had set themselves never
reached the chart, and inside a shared or managed record the zones followed
the viewer's age instead of the record's.

The targets payload already resolves for the record on screen. Its blood-
pressure card now honours the user's own band too (labelled Custom, like the
weight card), and the chart reads its zones from that card, so the chart and
the reference panel under it name one band.
2026-10-01 09:46:16 +02:00
Marc-André Bombeck 567fd8d51c test(e2e): sweep every signed-in route for sideways scroll at 390px
The lab list panned sideways on a phone while the overflow guard was
green, because /labs was not on its hand-kept list. The new sweep reads
the routes from src/app: static routes are visited as is, every dynamic
route needs a resolver to real paths, and routes that are not signed-in
surfaces are listed with their reason. A route added without either
fails the bookkeeping test by name.

It runs on an account of its own, filled once from globalSetup with one
or two of everything a route renders, in German, so the narrow-column
and long-string cases are present. Two lab tests assert at the elements
that broke: the marker name keeps a readable width, and the values
list's actions stay on screen. The dialog spec gains a 360px width,
where the labs sheet's three-button footer overflowed in English too.
2026-10-01 09:45:15 +02:00
Marc-André Bombeck 537ac3c7a1 fix(settings): stop settings and admin cards widening the page on a phone
Three cards put a full sentence into the SettingsCardHeader status slot
(mood reminder, low-stock warning, the app-log refresh button), which
does not wrap: the row grew to 1000px and /settings/notifications
panned sideways at every width. The sentence moves into the card body,
and the slot is capped at the row so a long status wraps instead.

Also on a phone: the provider-chain add control wraps, the report
picker's standard-template action drops under its sentence instead of
running past the card, and the dashboard layout rows put their switches
and arrows on a second line so the tile name is no longer cut to five
characters.
2026-10-01 09:44:43 +02:00
Marc-André Bombeck dc38540573 fix(ui): give the page-header description the full row on a phone
With three or four icon actions beside the title, the description was
left a ~130px column that wrapped five or six times. Below sm it now
spans the row under the title and actions; from sm up the actions span
both rows exactly as before.

A one-word German title wider than the column beside the actions ran
underneath them; the heading hyphenates by the page language and breaks
as a last resort. Notifications, whose two actions are text links,
moves them under the description on a phone (stackActionsOnPhone).
2026-10-01 09:44:43 +02:00
Marc-André Bombeck 24e6972f95 fix(labs): keep the biomarker chart axis at zero for a range starting at zero
A reference window of 0-130 padded the axis to -13, a tick that reads
like a value for a concentration that cannot be negative. The pad only
goes below zero when the data already does.
2026-10-01 09:44:30 +02:00
Marc-André Bombeck 4a13004917 fix(labs): fit the lab list, values list and add sheet to a phone
The compact list was a five-column table at every width. Below the fixed
columns (badge, 12rem range bar, 72px trend, chevron) the name column
collapsed to nothing, the badge sat over the value and the row panned
sideways off the card. Below lg the same cells now fold into two lines
per row; the desktop subgrid is unchanged.

The values table needed ~510px, so on a phone its edit and delete
buttons sat in a sideways-scrolling strip and the range bar labels were
clipped. Below lg each reading is a stacked row with its actions beside
it.

The add sheet's three footer buttons did not fit a phone row in German
and pushed Cancel off the left edge; the secondary save takes a row of
its own there, and the footer wraps instead of overflowing on desktop.
The scan review's 'links to existing marker' chip truncates instead of
running past its row.
2026-10-01 09:44:29 +02:00
Marc-André Bombeck 5820078008 fix(environment): default the date fields to the user's own day
The travel and backfill pickers defaulted to the UTC day, which was
tomorrow east of UTC in the small hours and yesterday west of it in the
evening, and the backfill start cut the home's effective instant the same
way. Both now read the day in the account's zone.
2026-10-01 09:39:09 +02:00
Marc-André Bombeck a67ba9ee66 fix(labs): match scanned duplicates on the reading's calendar day
The scan commit and the review screen looked for an existing reading in
the UTC day of the scanned date. A hand-entered morning draw east of UTC
sits on the previous UTC day, so scanning the same report wrote the
reading a second time. Both checks now compare calendar days: a date-only
reading's stated date, or the user's day of a hand-entered instant.
2026-10-01 09:37:59 +02:00
Marc-André Bombeck 9662a3d104 fix(insights): keep a medication course in the storyline through its last day
endsOn is a calendar date, and the storyline compared it with the instant
now, so a course dropped out on its final day. Compare it with the user's
own today as the column's date value instead.
2026-10-01 09:35:11 +02:00
Marc-André Bombeck 67d88de3d5 fix(glp1): file timeline side effects under the mood entry's own day
The timeline grouped side effects by the UTC day of moodLoggedAt, so an
evening entry west of UTC (or a morning one east of it) showed on the
neighbouring day. The entry's stored date is already the writer's local
day; group by that.
2026-10-01 09:34:13 +02:00
Marc-André Bombeck 838629276c fix(documents): store stated dates at noon UTC
A report's stated date, a document's filing date and the date a committed
lab reading or condition carries were written as UTC midnight, which is
the previous evening west of UTC: a reading dated the 1st showed on the
31st. Date-only values are now stored at noon UTC through one helper in
the time zone module, the convention the lab scan and the cycle engine
already use. Rows written at midnight still read back to the same date.
A document uploaded without a date files under the uploader's own day
rather than the UTC one.
2026-10-01 09:33:50 +02:00
Marc-André Bombeck 4ac05364fe fix(coach): count GLP-1 injection days on the user's calendar
The snapshot cut the last injection, the dose history and the projected
next injection on UTC days and compared getUTCDay() with the schedule's
local weekday. An evening injection west of UTC landed on the next day,
and east of UTC 'tomorrow' was today. Day keys now come from the user's
zone, which the Coach snapshot already resolves and now passes in.
2026-10-01 09:29:01 +02:00
Marc-André Bombeck 2dc73be233 fix(dashboard): put the mood card's instant on the user's local day
The mood series carries local day keys, and the summary wrote the newest
one out as UTC midnight. West of UTC that instant is the previous evening,
so a client formatting it in its own zone showed today's entry as
yesterday's. Emit the first instant of the day in the account's zone
instead; the field keeps its shape and type.
2026-10-01 09:27:56 +02:00
Marc-André Bombeck 1934b97663 test(guard): declare every queue's runtime and hold long ones to it
Every queue bound with createAndWork is now declared in
src/lib/jobs/queue-runtime.ts as short (cannot come near the default
fifteen minutes, with the reason), budgeted (stops itself at three
quarters of the default and resumes) or long (an explicit expiry, a
stop on the job's budget, and a lock or claim per identity; or a
declared one-shot with no retries).

The guard reads every binding, every boss.send and every schedule tuple
in the tree: each names a queue in the table, every entry is bound, a
long queue's sends and schedules all carry its expiry, its handler
stops on jobBudget / jobDeadline where declared and holds lockedPass or
the named marker, and a short or budgeted queue sets no expiry of its
own. Floors pin the counts (112 bindings, 64 sends, 74 schedules), and
planted long queues missing each protection in turn are caught. Run
against the tree before the previous commit it reports 59 findings;
dropping lockedPass and the cron expiry from pr-detection reports both.
2026-10-01 09:24:15 +02:00
Marc-André Bombeck ac3fdfccc3 fix(jobs): keep long passes inside their expiry and alone
pg-boss gives a job fifteen minutes unless the send says otherwise,
then fails it and retries it while the handler keeps running. Several
passes can legitimately need longer and had no protection at all: the
seven nightly status passes and the pre-generation (a provider call per
account), the period-narrative warm, the record-detection cron (every
account's history, every thirty minutes), the key rotation (every
encrypted column), the content-index backfill (up to 200
transcriptions) and the on-host backup.

Each of them now carries an explicit expiry on every send and schedule,
stops between units once three quarters of it is spent (jobBudget), and
runs under a session advisory lock keyed on queue and identity
(lockedPass), so the retry pg-boss starts after the expiry does nothing
beside a run that is still going. The lock is the one the full-history
imports already held, moved into job-lock.ts.

Where a pass stops early it says so (stopped_early) and the next run
continues: the status passes and the narrative warm leave the rest to
the next night, the pre-generation and the narratives walk the stalest
accounts first, the on-host backup now backs up the oldest copies
first, the key rotation reports a partial run in its audit row and
skips rotated rows when run again, and the dose-history import fails
the delivery so its retry resumes from the committed chunk. The
off-host backup, which already stopped on its budget, gets a four-hour
expiry and the lock.
2026-10-01 09:23:45 +02:00
Marc-André Bombeck 9a282ed698 fix(units): keep converted values on the rounding helpers
The narrative, the workout distance and the elevation chart converted
through the unrounded escape hatch, and the trend caption scaled its
noise floor off the raw factor. They now take the rounded helpers, so a
narrated pound or mmol/L figure reads at the grain every screen shows
it, and the caption's floors are declared canonically (the distance
floor in metres). The trends row joins the chart-feeding surfaces that
may hand a raw scale to a chart.

Refs #1067
2026-10-01 09:17:44 +02:00
Marc-André Bombeck 0039bd1d1f refactor(insights): use the shared rescale predicate in the status note
Refs #1067
2026-10-01 09:11:47 +02:00
Marc-André Bombeck b788b5b8b2 test(units): sweep every display tree for unit literals
The unit-preference guard covered the dashboard, the insights pages and
the target surfaces, and the class kept turning up beside them. It now
also walks src/components, src/app, src/lib/insights and the doctor
report and export modules for the glucose units anywhere in code and
for kg, km and °C in display strings, with comments stripped. Each file
that legitimately carries one is listed with its exact line budget and
the reason: the conversion and the pickers, input parsing, display-kind
tags, canonical wire and registry units, the SI policy for clinician
artefacts, and four prompt texts still to move. The sweep asserts a
match floor, so a broken walk cannot pass as a clean tree.

Refs #1067
2026-10-01 09:10:17 +02:00
Marc-André Bombeck 8a11e60bb3 fix(cycle): state the cycle-phase glucose row in the reader's unit
The cycle-phase table printed the bundle's mg/dL label beside raw mg/dL
values for every reader. Weight, temperature and now glucose rows take
their unit and conversion from the one reading resolver; every other
row keeps its bundle label.

Refs #1067
2026-10-01 09:10:16 +02:00
Marc-André Bombeck bc2d60cce8 fix(insights): plot the trends row and log fevers in the reader's units
Two more surfaces carried a fixed unit. The insights trends row labelled
weight in kg and body temperature in °C for every reader, and plotted
walking distance as raw metres under a km label; its trend caption
said the same. A single transformed series there now takes unit, scale
and offset from the preference, and the caption describes the converted
series against a converted noise floor.

The illness day sheet and timeline showed and took a fever in °C. The
fever is now seeded, typed and shown in the reader's temperature unit
and stored in °C as before.

Refs #1067
2026-10-01 09:08:11 +02:00
Marc-André Bombeck d6f79c8bef fix(workouts): show distance, pace and elevation in the reader's units
The workout list, the detail header, the stat tiles, the sport-average
line and the elevation chart printed kilometres, minutes per kilometre
and metres for every reader. They now read distance, pace and elevation
through the unit registry (km or mi, /km or /mi, m or ft). The splits
table keeps its kilometre rows, which are cut server-side, and says so.
A pace that rounded to sixty seconds now carries into the minute.

Refs #1067
2026-10-01 09:03:51 +02:00
Marc-André Bombeck 0f31fd199b test(guard): police dense measurement reads in request handlers and raw SQL
The dense-read guard walked the worker and insight directories only,
and the same class kept turning up beside them: the targets page, the
cycle insights, the per-kind series and the doctor report all lived in
app/api or a helper next to it.

The findMany check now also covers app/api, import, export, the targets
and the doctor report. It reads the type from the where object rather
than the first type key in the call, accepts a list of sparse literals,
and counts a key-bounded where (an id, externalId or measuredAt list,
or an exact instant) as bounded. Every remaining unbounded read is
listed with its reason.

A second check covers every raw statement in the tree that reads from
measurements: it must GROUP BY, use DISTINCT or LIMIT, or select
aggregates only, or be listed. Both checks carry floors and run their
matchers over a planted offender. Restoring the old targets builder
fails the findMany check on the year of glucose and the heart-rate
month; dropping the GROUP BY from the resting-pulse fold fails the SQL
check.
2026-10-01 09:02:23 +02:00
Marc-André Bombeck 5486014360 fix(score): write the glycaemia labels in the reader's glucose unit
The fasting-glucose pillar served its observed and reference labels as
"Fasting median 99 mg/dL" and "70-99 mg/dL fasting" whatever the
account's unit, and clients print those labels as they come. They are
now written in the record's glucose unit. The scored value, its unit
and the band edges stay canonical, so the score does not move and the
web, which converts from the value, cannot convert twice. The schema
now says which fields are canonical and which are display text.

Refs #1067
2026-10-01 09:00:53 +02:00
Marc-André Bombeck 5f1eb05445 fix(measurements): bound the per-night sleep list to a year ending at to
The sleep list capped its read to the last year only when no `from`
was sent. An explicit early `from` walked every per-stage row back to
that date, on a multi-source account several rows per night for years.

The read window is now at most a year ending at `to` (or now). `from`
narrows it but never widens it, older nights are reached by moving
`to` back, and `meta.windowFrom` names the instant a cut window
started, so a client can tell a cut from an empty history.
2026-10-01 08:58:42 +02:00
Marc-André Bombeck d0a9086538 fix(targets): edit glucose thresholds in the reader's glucose unit
The settings threshold editor took the identity path for the glucose
thresholds, so an account on mmol/L was shown a mg/dL default and asked
for mg/dL figures against 40-400 bounds, while the insights sheet for
the same threshold already spoke mmol/L. The shared target adapter now
owns the glucose unit as it owns pounds: fields, inward-rounded bounds,
the default hint and the canonical write all go through it, and the
insights panel and its sheet use the same branch instead of their own
conversion.

Refs #1067
2026-10-01 08:58:24 +02:00
Marc-André Bombeck 730e9e7015 fix(doctor-report): take the day path for dense heart-rate variability and blood oxygen
The report's dense exception covered pulse and glucose. Heart-rate
variability and blood oxygen were read raw for any window, and a watch
or ring writing them every minute puts six figures of readings into a
long report that draws them as one sparkline.

Their report sections are a statistics row and a series, the same as
pulse, so they take the same rule: beyond 90 days per local day, and
inside 90 days per local day once the window holds more than 10 000 of
their readings. One grouped count decides each type on its own. Count,
minimum, maximum and the latest reading stay exact; the mean is the
readings' mean. Glucose keeps its own rule because its clinical panel
needs the per-reading counts.

The bucket query now takes a list of types instead of two flags.
2026-10-01 08:56:19 +02:00
Marc-André Bombeck 1058859730 fix(narrative): narrate period changes in the reader's units
The period narrative pinned kilograms and mg/dL on its change list, and
its personal-range lines carried no unit at all. Every delta and band
edge is now stated in the reader's units (computed canonically, converted
at the end, percent left unit-free), and each band transition carries
its unit into the prompt. The sleep channel, a per-night total in
minutes, was labelled hours and is now converted to them.

Refs #1067
2026-10-01 08:55:19 +02:00
Marc-André Bombeck e7fdcc208e test(targets): pin the route over the folded glucose and heart-rate reads
The route test mocked Prisma and asserted a raw glucose findMany. The
glucose and resting-pulse inputs now come from their SQL readers, so the
test mocks those, feeds the pinned response through the in-memory fold,
and asserts that neither stream is read as rows.
2026-10-01 08:54:20 +02:00
Marc-André Bombeck 6c6d363bba fix(insights): write metric status notes in the reader's units
The per-metric status note quoted glucose in mg/dL, body composition in
kg, temperatures in °C and walking distance in metres, whatever the
reader had chosen; the deterministic floor without a provider did the
same. The generator now converts the series, the reference band and the
signal into the reader's units before they reach the prompt or the
floor, and prints the guideline band table in that unit while still
classifying on the canonical value.

A changed glucose unit or metric/imperial preference (own account or a
managed record) now re-warms the stored notes and narratives through
the hash-gated refill, so today's text does not keep the old unit.

Refs #1067
2026-10-01 08:52:44 +02:00
Marc-André Bombeck b2c484e25e fix(series): bucket heart-rate variability and blood oxygen like pulse
The dense rule in /api/measurements/series covered pulse and glucose
only. Heart-rate variability and blood oxygen read every raw row for
any window up to 3650 days, and a watch or ring that writes them every
minute makes that the same unbounded read pulse had.

Both kinds now fold per local day beyond 90 days and per local hour
inside 90 days once the window holds more than 10 000 readings. A
bucket keeps the point shape of its kind: only pulse carries
valueMin / valueMax. Statistics stay computed over every reading, and
a sparse series inside 90 days is unchanged. The OpenAPI description
names the four kinds.
2026-10-01 08:52:10 +02:00
Marc-André Bombeck 8949606de9 fix(cycle): read the insights crosstab as per-source day aggregates
GET /api/cycle/insights read a year of raw readings for its outcome
channels, glucose and heart-rate variability included. On a sensor
account that is over 100 000 objects per request.

The crosstab uses each local day's sum and count after picking one
source and device per day, so the route now reads readSourceDayAggregates
like the coach's cycle snapshot does, and each row carries its reading
count into metricDayMap.

The integration test runs the route over the fold and over every raw
reading handed in as a one-reading group, and compares the answers.
2026-10-01 08:50:31 +02:00
Marc-André Bombeck 70e6e07a89 refactor(units): resolve both unit preferences through one registry
Metric/imperial and the glucose unit were two separate lookups, so every
server-side text producer had to remember both and most remembered
neither. display-transform.ts now carries a glucose branch keyed by the
glucose preference (getReadingTransform), the metre-valued workout
quantities (distance, elevation, pace), and a resolver for the two
stored columns together. loadUnitPreferences reads them in one query and
useUnitDisplay hands the glucose unit out beside the metric/imperial
branch.

Refs #1067
2026-10-01 08:48:39 +02:00
Marc-André Bombeck 7f2349e56f fix(targets): fold the glucose year and the heart-rate month in SQL
The targets page read a year of raw glucose readings to keep the newest
one per meal context, and thirty days of raw heart rate to derive one
resting figure per day. A sensor reporting every five minutes puts
105 000 glucose readings in that year and a watch recording once a
minute puts 43 000 heart-rate readings in the month, and the page is
read on every visit from the web and the app.

Glucose now reads one row per context (DISTINCT ON) for the newest
value and one row per context and local day for the thirty-day mean
and the consistency strip; the strip takes day sums directly through
rollupConsistencyFromDays. Heart rate reaches the resting-pulse card
through readRestingPulseProxy, the SQL fold the insights page already
uses, merged per day with the native resting rows exactly as before.

The cards are unchanged: the integration test rebuilds them from the
raw readings through the in-memory folds and compares.
2026-10-01 08:47:18 +02:00
Marc-André Bombeck d00e106ce1 fix(clinician): print every shared statistic with its unit
The clinician view printed bare numbers for every measurement group and
the per-context glucose rows in raw mg/dL, so a recipient read glucose
without a unit and in the wrong one for an account on mmol/L. The PDF's
measurement table had the same gap for the raw glucose series.

Both artefacts now take the unit and the displayed number from one helper
(doctor-report/stat-display.ts): SI for mass, length and temperature as
before, hours for sleep, and the record owner's unit for glucose.

Refs #1067
2026-10-01 08:46:39 +02:00
Marc-André Bombeck 1b694ec222 Merge pull request #1068 from MBombeck/release/v1.39.6
Release v1.39.6
2026-10-01 01:15:33 +02:00
Marc-André Bombeck 8ea9322c8e docs(changelog): say which charts the 1.39.5 pulse buckets reach 2026-10-01 00:50:18 +02:00
Marc-André Bombeck 3e4f431373 chore(release): v1.39.6 — a critical framework fix, a workout token, a lab scan that keeps every reading, and an instant restore preview 2026-10-01 00:48:46 +02:00
Marc-André Bombeck 3d6b052a05 Merge pull request #1058 from BernhardBuckel/fix/ocr-review-date-validation
fix(labs): block a lab-scan save while a selected reading is incomplete
2026-10-01 00:43:50 +02:00
Marc-André Bombeck 02be4d3dff Merge branch 'main' into fix/ocr-review-date-validation 2026-10-01 00:20:48 +02:00
Marc-André Bombeck c777e9e9e4 Merge pull request #1065 from MBombeck/fix/v1396-small-fixes
Quick-add follows intakeActionable; hourly buckets for dense CGM inside 90 days
2026-09-30 23:57:44 +02:00
Marc-André Bombeck 20752fb4bb Merge pull request #1066 from MBombeck/fix/backfill-lane-expiry
Keep a full-history import from running beside its own retry; tombstone purge steps around a restore
2026-09-30 23:46:16 +02:00
Marc-André Bombeck 85d11bc364 Merge branch 'main' into fix/v1396-small-fixes 2026-09-30 23:27:25 +02:00
Marc-André Bombeck a5d19bfe98 Merge pull request #1064 from MBombeck/fix/backup-summary-manifest
Answer the restore preview from counts kept with the backup
2026-09-30 23:25:26 +02:00
Marc-André Bombeck 3f6144a5b9 Merge pull request #1062 from MBombeck/feat/workouts-write-scope
Mint a workouts:write token for headless workout ingest
2026-09-30 23:25:09 +02:00
Marc-André Bombeck 70ce666d00 Merge pull request #1063 from MBombeck/fix/dev-deps-advisories
Raise the dev-only grpc-js, brace-expansion and undici 7 floors
2026-09-30 23:15:59 +02:00
Marc-André Bombeck a0c290e140 fix(jobs): let the nightly tombstone purge step around a running restore
A restore clears every row of the account, tombstones included, inside one
long transaction under the account's exclusive restore lock. The nightly
purge deleted expired tombstones across accounts, one statement per batch,
without that lock: on an account under restore it waited on the restore's
row locks for as long as the restore ran, past its statement timeout, or
deadlocked with it once each side held rows the other needed.

Each batch is now deleted one account at a time, in a transaction that
first takes the restore lock in shared mode, the same order the
consolidation passes keep. An account under restore is refused at once,
kept out of the rest of the run, and purged the next night. Still one
delete per account per batch, never one per row. The job reports how many
accounts it deferred.

The integration test holds a stand-in restore on one account while the
purge runs: the purge returns without waiting, leaves that account alone
and purges the other. With the lock call removed it waits out the hold.

Refs #1031
2026-09-30 23:11:03 +02:00
Marc-André Bombeck 029d6d881c fix(jobs): keep a full-history import from running beside its own retry
The shared admission queue sent its jobs without an expiry, so every one
took pg-boss's fifteen minutes. Against pg-boss 12.34, a handler that runs
past its expiry is not stopped: the job is failed, its abort signal fires,
the worker and group slots are freed, and the retry of the same job starts
in the same worker beside the run it replaced. A per-minute heart-rate
history is thousands of pages, so on a slow link one import turned into up
to four copies of itself, on the one queue meant to run a single import at
a time.

- The admission job now carries a sixteen-hour expiry, sized for the
  longest legitimate import and under pg-boss's 24-hour ceiling.
- Each run holds a session advisory lock on its identity (kind, provider,
  account) on a connection of its own. A delivery that finds it taken does
  nothing and says so in the log; the running import stamps its marker or
  is offered again at the next boot. Ending the connection or the process
  releases the lock.
- The Google Health backfill runs under the job's budget and abort signal.
  The page walk asks before each request, stops there, and reports the run
  truncated, so it throws without the completion stamp and is retried.
- The drain moves out of the registrar into its own module so it can be
  driven against a real pg-boss.

The integration test pins the pg-boss behaviour and runs the lane's
handler with a two-second expiry: without the lock the import ran twice.

Refs #1023
2026-09-30 23:11:03 +02:00
Marc-André Bombeck 731e073284 fix(measurements): hour-bucket a CGM glucose series inside the 90-day window
A sensor reading every five minutes puts about 26 000 glucose readings in
a 90-day window, and the per-kind series sent every one of them raw. The
hourly bucketing that already applies to a dense heart-rate stream now
applies to glucose too, with the same 10 000-reading cap: the hour's mean
converted once to the user's unit, statistics over every raw reading.
A fingerstick meter stays far under the cap and keeps its raw points.

The doctor report keeps glucose raw inside 90 days. Its clinical panel is
computed from the raw readings of every source, while the day path works
from canonical-source day buckets, so the two do not give the same figures
when a meter and a sensor overlap.
2026-09-30 23:01:57 +02:00
Marc-André Bombeck ca10f2e5df fix(medications): dashboard quick-add offers only doses the server calls actionable
The dashboard and capture-picker intake form filtered the medication list
on `active && trackIntake`, so a course that had ended (still active,
nobody paused it) was offered for a dose while the cards, the table and
"take all" already followed the server's `intakeActionable`. The picker
now renders from that one answer as well.

When medications exist but none offers a dose today, the empty state no
longer claims there are no medications; it says nothing is due and
points to the medication history for a past dose.
2026-09-30 22:58:19 +02:00
Marc-André Bombeck a2fceb5585 fix(backups): answer the restore preview from counts kept with the copy
The restore dialog asked GET /api/admin/backups/{id}/summary for the
contents of a copy, and the route read the whole stored copy to answer:
every piece opened, every measurement parsed, the rest validated. On an
account of 1.8 million readings on slow hardware that took about two
minutes. The dialog stopped waiting after 15 s and said the contents
could not be read, and its automatic retry made the server read the
whole copy a second time.

The copy passes through the process once anyway while it is written, so
the preview is worked out there and kept on the row (DataBackup.preview,
migration 0364): the summarizeBackup counts, the schema version, and
the inner key ids with the sections they sit in and one sample value
each. Every creation path goes through storeBackupBlob (the weekly and
manual pass, and an upload), so every new copy carries one. The column
is plain JSON: counts and dates only, and the samples are ciphertext
that stands for what is inside the copy, which a key rotation must not
re-seal.

The route answers from it without opening the copy. Both verdicts are
taken again on every read, from what the preview keeps: whether this
release restores the schema version, and whether this server holds the
keys the copy needs. The pieces are still counted against the row, so
a copy that lost one is refused as the restore and the download refuse
it. A preview names the copy it describes and is ignored once the copy
changes; converting a single stored value into pieces carries it over.

A copy written before this has no preview. It is read whole once, as
before, and the result is kept on the row, so it is slow only the first
time; concurrent requests for the same copy share the one read.

Only a file that fails the schema answers 422 "Backup payload failed
schema validation". Read refusals keep their codes; anything else is
the server failing and answers 500.

The dialog no longer retries the preview, waits up to 55 s, and when it
stops waiting on an older copy it says the copy is still being read and
to open the dialog again in a few minutes.

Refs #1031
2026-09-30 22:51:02 +02:00
Marc-André Bombeck fab5cbccbf fix(deps): raise the dev-only grpc-js, brace-expansion and undici 7 floors
The dependency alerts flag development copies only: @grpc/grpc-js under the
test containers, brace-expansion on three major lines, and undici 7 next to
the app's own undici 8. None ships in the image.
2026-09-30 22:42:50 +02:00
Marc-André Bombeck c7be1a0c5f Merge branch 'main' into feat/workouts-write-scope 2026-09-30 22:35:44 +02:00
Marc-André Bombeck eb7c3fafe4 Merge branch 'main' into fix/ocr-review-date-validation 2026-09-30 22:35:42 +02:00
Marc-André Bombeck 95d3676821 Merge pull request #1061 from MBombeck/fix/deps-security-2026-09-30
Move next to 16.3.6 and raise three transitive floors
2026-09-30 22:35:26 +02:00
Marc-André Bombeck e7166cb3c6 feat(tokens): mint a workouts:write token for headless workout ingest
A bridge that pushes workouts from a watch vendor had no credential that
reached POST /api/workouts/batch: the route called requireAuth() with no
scope, so under the fail-closed default only a cookie session or a
wildcard token got through, and a measurements:write token was refused
403. The route's header still described the pre-fail-closed behaviour.

Add a separate workouts:write scope rather than widening
measurements:write, so a token already handed to a scale does not start
accepting workouts.

- POST /api/tokens/workouts mints it, mirroring the measurement and
  document mints: cookie session plus a fresh proof, a literal permission
  array, 10 mints a minute, at most 10 live tokens (409
  tokens.workouts.ceiling_reached), a one-year default lifetime, audited.
- POST /api/workouts/batch names the scope. Sessions and wildcard tokens
  behave as before. A scoped caller's workouts are stored as EXTERNAL,
  resolved from the credential, and a batch in which any entry names a
  source is refused 422 (workout.batch.source_not_permitted), the same
  rule the measurement batch applies. EXTERNAL is on no source ladder, so
  when the phone recorded the same session the phone's copy is shown.
- Settings > API offers a workout token card next to the measurement one,
  and the endpoint list shows the batch route.
- Guards: the mint site, the declared scope vocabulary, the recent-proof
  routes, and a new check that only the batch declares the scope.
- OpenAPI documents the mint, the batch's narrow-token behaviour and both
  error codes; docs/api/README.md lists the workout and document mints.

Refs #1054
2026-09-30 22:21:46 +02:00
Marc-André Bombeck 162ba62752 fix(deps): move next to 16.3.6 and raise the fast-uri, ip-address and dompurify floors
The production audit flags a critical advisory against next 16.2.0 to 16.3.5,
fixed in 16.3.6, and newer advisories against the transitive fast-uri (ajv),
ip-address (the MCP SDK's rate limiter) and dompurify (jspdf) copies. Next is
pinned to 16.3.6 rather than the newest patch so the install stays inside the
minimum release age without new exclusions.
2026-09-30 22:12:47 +02:00
Marc-André Bombeck 1627aa6c57 fix(labs): translate the review validation messages and narrow a test lookup 2026-09-30 22:02:02 +02:00
BernhardBuckel eaced8226b fix(labs): block a lab-scan save while a selected reading is incomplete
The review dialog silently dropped any selected reading that could not be
written (no date, no unit, no value) and saved the rest. When nothing was
left it showed "Select at least one reading to save", which described a
different situation and said nothing about what was missing.

A save is now all-or-nothing over the selected readings. When one is
incomplete, nothing is written; the dialog states how many readings need
attention, marks each missing field (aria-invalid, inline message, red
border, required marker on the label) and moves focus to the first one.
Marks appear after a save attempt and follow the edits. The "nothing
selected" message is kept for that case only.

Validation is a pure function next to the payload mapping, so the rule that
blocks a save and the rule that builds the payload cannot drift apart.

Adds EN and DE strings; the other locales are left to the maintainers.

Refs #1055
2026-09-29 20:31:22 +02:00
Marc-André Bombeck ae6a5ac693 Merge pull request #1053 from MBombeck/release/v1.39.5
Release v1.39.5
2026-09-28 01:17:57 +02:00
Marc-André Bombeck 3f3bb0579a chore(release): v1.39.5 — a dense heart-rate history within memory, and restores that hold less 2026-09-28 00:55:23 +02:00
Marc-André Bombeck 5bbcf28bdc Merge pull request #1052 from MBombeck/fix/1031-restore-memory
Bound restore memory and order it against the consolidation passes
2026-09-28 00:51:31 +02:00
Marc-André Bombeck add6d1fadc fix(restore): order the restore and the consolidation passes by one lock
A restore on a freshly booted instance failed its clearing step with a
deadlock (40P01) while the boot-time step consolidation was folding the
same account. A consolidation day updates or mints the day's total and
then soft-deletes the day's per-sample rows; the restore deletes every
reading of the account in one statement. When the restore reached a
day's samples before its total, each side held what the other needed
next.

The restore already took an advisory lock per account before its first
delete. Every day transaction of the passes built on runConsolidation
(step and mean consolidation, the per-sample cumulative drain, the dense
intraday retention) now takes the same lock in shared mode as its first
statement. A restore that starts mid-day waits for that day to commit;
a day that would start while a restore runs is refused at once, and the
pass leaves that account for its next run instead of folding rows the
restore is about to replace. The passes still share the lock with each
other.

A new integration test builds the lock order that deadlocked, with a
row trigger holding the consolidation on the day's total while the
restore starts; before this change the consolidation was cancelled with
a deadlock. A guard test requires every transaction in a pass on
runConsolidation to open with the shared lock.

Refs #1031
2026-09-28 00:34:11 +02:00
Marc-André Bombeck f2569b6fdf fix(restore): carry at most a hundred readings per insert statement
Prisma's debug logger keeps the arguments of its last hundred calls in
memory whether or not logging is on, and the client and the Postgres
adapter both log every statement with its parameters. A restore that
wrote 1 000 readings per statement therefore kept a copy of about the
last 100 000 readings alive for the whole measurement write: about
60 MB on 1.8 million Apple Health readings, next to a V8 heap limit of
524 MB in the default 1 GB container.

The bulk insert now splits whatever it is handed into statements of at
most 100 rows, which holds about 7 MB. The Apple Health export import
goes through the same helper and gets the same bound. The write costs a
little time: 94 s instead of 76 s for 1.8 million readings on a fast
host.

Refs #1031
2026-09-28 00:06:47 +02:00
Marc-André Bombeck 2eec103182 Merge pull request #1051 from MBombeck/fix/1023-dense-stream-memory
Keep a dense heart-rate stream out of memory
2026-09-27 21:47:18 +02:00
Marc-André Bombeck 6836830038 fix(doctor-report): report readings, not day buckets, for a dense type
A type served from day buckets (pulse or glucose past 90 days, and since
the previous change a dense pulse stream on any window) is drawn one point
per day, each the day's mean at the day's start. The summary line counted
those points as measurements, and the FHIR export stamped the last day's
mean as the latest observation: a value and a time nobody measured.

The day-bucket stats now carry when their newest reading was taken
(`latestAt`). `latestReading` returns that reading when it is there, and
the summary line counts each type's readings from its stats. Raw series
are unchanged: their stats count equals their points and their last point
is the newest reading.
2026-09-27 21:20:24 +02:00
Marc-André Bombeck 3458100ac4 test: give the report's pulse-window count a mock and a typed route call 2026-09-27 21:16:20 +02:00
Marc-André Bombeck 0e991c3640 fix(measurements): fold a dense pulse stream inside the 90-day raw window
Past 90 days every pulse reader already folded in SQL. Inside it, three
still read every raw heart-rate row, which on a watch that records a
reading a minute is 130 000 rows per read (#1023):

- The insights page's resting-pulse proxy, used when an account has no
  resting heart rate, walked the whole window to take one percentile per
  day and held the event loop for over a second per view. It now folds in
  Postgres (`readRestingPulseProxy`) with the same percentile, rounding,
  minimum-sample rule and day anchor.
- The per-kind series sent every reading: 14.7 MB for 90 days. A pulse
  window with more than 10 000 readings is now bucketed per local hour,
  mean plus low/high band, with stats still over the readings.
- The doctor report drew every reading into one sparkline. A pulse window
  over the same cap now takes the per-day path longer reports already use.

Sparse pulse (a cuff, hourly imports, a watch sampling every few minutes)
stays under the cap and keeps its raw shape.
2026-09-27 21:07:29 +02:00
Marc-André Bombeck 821c2eb884 test(google-health): pin a heart-rate walk past a thousand pages 2026-09-27 20:43:15 +02:00
Marc-André Bombeck e34741c077 fix(google-health): write a dense collection page by page during a backfill
A full-history backfill read every heart-rate point of an account into one
array, mapped it into a second, and wrote the lot in one call; the cycle's
deferred-rollup ledger then kept one entry per written reading. On a watch
that records a reading a minute that is over a million points, and the
backfill ran a 1 GB heap out of memory within seconds, restarting the
instance it shares with the app (#1023).

The metric walk now hands each page to its write before requesting the
next, and both the Google Health and Fitbit ledgers collapse to one key per
touched type-day as they record. The heart-rate walk's page ceiling rises
from 1000 to 10000: at one point a minute the old ceiling is under two
years, a longer history always ended truncated, and the backfill retried
the whole walk on every attempt and every boot without completing.
2026-09-27 20:42:54 +02:00
Marc-André Bombeck c2a1522634 Merge pull request #1049 from MBombeck/dependabot/npm_and_yarn/pg-boss-12.34.0
build(deps): bump pg-boss from 12.27.0 to 12.34.0
2026-09-27 20:14:27 +02:00
Marc-André Bombeck 1910a6f760 Merge pull request #1047 from MBombeck/dependabot/npm_and_yarn/types/node-26.6.2
build(deps-dev): bump @types/node from 26.5.1 to 26.6.2
2026-09-27 20:01:12 +02:00
Marc-André Bombeck b9af05cf8d Merge pull request #1046 from MBombeck/dependabot/npm_and_yarn/undici-8.11.2
build(deps): bump undici from 8.10.2 to 8.11.2
2026-09-27 19:52:25 +02:00
Marc-André Bombeck 7a21bb6787 Merge pull request #1045 from MBombeck/dependabot/npm_and_yarn/tanstack/react-query-5.103.2
build(deps): bump @tanstack/react-query from 5.102.8 to 5.103.2
2026-09-27 19:51:59 +02:00
Marc-André Bombeck 522b61fdec Merge pull request #1050 from MBombeck/dependabot/github_actions/codeql-action-9d88a12d2b
build(deps): bump the codeql-action group with 3 updates
2026-09-27 19:51:55 +02:00
Marc-André Bombeck 6f6c4ffff0 test(jobs): re-pin the pg-boss retention assumptions to 12.34.0 2026-09-27 19:51:46 +02:00
dependabot[bot] dfd0f2e6dd build(deps-dev): bump prettier from 3.9.6 to 3.9.9 (#1048)
Bumps [prettier](https://github.com/prettier/prettier) from 3.9.6 to 3.9.9.
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.9.6...3.9.9)

---
updated-dependencies:
- dependency-name: prettier
  dependency-version: 3.9.9
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-27 16:35:23 +00:00
dependabot[bot] bdad4f3dcd build(deps): bump the codeql-action group with 3 updates
Bumps the codeql-action group with 3 updates: [github/codeql-action/init](https://github.com/github/codeql-action), [github/codeql-action/analyze](https://github.com/github/codeql-action) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action).


Updates `github/codeql-action/init` from 4.38.0 to 4.38.2
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/b96794f015dfd88f77b49b1c93e0fa7110f94c63...2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2)

Updates `github/codeql-action/analyze` from 4.38.0 to 4.38.2
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/b96794f015dfd88f77b49b1c93e0fa7110f94c63...2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2)

Updates `github/codeql-action/upload-sarif` from 4.38.0 to 4.38.2
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/b96794f015dfd88f77b49b1c93e0fa7110f94c63...2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2)

---
updated-dependencies:
- dependency-name: github/codeql-action/init
  dependency-version: 4.38.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: codeql-action
- dependency-name: github/codeql-action/analyze
  dependency-version: 4.38.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: codeql-action
- dependency-name: github/codeql-action/upload-sarif
  dependency-version: 4.38.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: codeql-action
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-27 15:55:47 +00:00
dependabot[bot] 891db1753e build(deps): bump pg-boss from 12.27.0 to 12.34.0
Bumps [pg-boss](https://github.com/timgit/pg-boss) from 12.27.0 to 12.34.0.
- [Release notes](https://github.com/timgit/pg-boss/releases)
- [Commits](https://github.com/timgit/pg-boss/compare/12.27.0...12.34.0)

---
updated-dependencies:
- dependency-name: pg-boss
  dependency-version: 12.34.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-27 15:55:34 +00:00
dependabot[bot] ddf685e2c9 build(deps-dev): bump @types/node from 26.5.1 to 26.6.2
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 26.5.1 to 26.6.2.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 26.6.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-27 15:54:38 +00:00
dependabot[bot] 5a5356fc14 build(deps): bump undici from 8.10.2 to 8.11.2
Bumps [undici](https://github.com/nodejs/undici) from 8.10.2 to 8.11.2.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v8.10.2...v8.11.2)

---
updated-dependencies:
- dependency-name: undici
  dependency-version: 8.11.2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-27 15:54:10 +00:00
dependabot[bot] c5ed9e2296 build(deps): bump @tanstack/react-query from 5.102.8 to 5.103.2
Bumps [@tanstack/react-query](https://github.com/TanStack/query/tree/HEAD/packages/react-query) from 5.102.8 to 5.103.2.
- [Release notes](https://github.com/TanStack/query/releases)
- [Changelog](https://github.com/TanStack/query/blob/main/packages/react-query/CHANGELOG.md)
- [Commits](https://github.com/TanStack/query/commits/@tanstack/react-query@5.103.2/packages/react-query)

---
updated-dependencies:
- dependency-name: "@tanstack/react-query"
  dependency-version: 5.103.2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-27 15:53:43 +00:00
Marc-André Bombeck dbcbf752b1 Merge pull request #1044 from MBombeck/release/v1.39.4
Release v1.39.4
2026-09-27 16:18:04 +02:00
Marc-André Bombeck 7d82a32fa9 fix(coach): keep the result table's scroll area reachable from the keyboard 2026-09-27 15:59:42 +02:00
Marc-André Bombeck 98f2875f8e test(coach): strip step markup until stable 2026-09-27 15:45:14 +02:00
Marc-André Bombeck 5ab157a908 chore(release): v1.39.4 — a Coach you can see working, encrypted routes and contacts, and restores that finish on large accounts 2026-09-27 15:12:37 +02:00
Marc-André Bombeck 833fb0b465 fix(workouts): report no route when its track cannot be read 2026-09-27 15:11:43 +02:00
Marc-André Bombeck f98f8eaa24 Merge branch 'fix/chart-all-range-meaning' into release/v1.39.4 2026-09-27 14:22:57 +02:00
Marc-André Bombeck 206da07e8c Merge branch 'fix/meds-ended-and-mental-health' into release/v1.39.4 2026-09-27 14:18:09 +02:00
Marc-André Bombeck 6f37cbdb23 fix(backup): carry each medication's category through backup and restore
The clinical category a person picks for a medication lives in a side table
created at runtime, outside the schema. The backup builder and the restore
only walk schema models, so no backup ever carried it: after a restore every
medication read as "Other".

Both backup formats now carry the category inside its medication, and the
restore writes it back in the same transaction as the medication. A file
from before this change restores as before; a category this server does not
know reads as Other instead of refusing the file.

The backup plan gains a list for tables created with raw SQL, and a check
that every such table in the source either maps to a schema model or has a
verdict there, so the next one cannot drop out of backups unnoticed.
2026-09-27 14:17:42 +02:00
Marc-André Bombeck 7b5ea8b353 fix(charts): name a folded point of steps as a daily average
A week or month point of a cumulative metric is the average daily total,
which keeps the axis comparable with the 7, 30 and 90 day tabs. The
caption said "Weekly avg", which reads as an average week's total. Steps,
energy, distance, flights and daylight now say "Daily avg per week" or
"per month" on the caption and in the tooltip, in all seven languages;
level metrics keep the plain average.
2026-09-27 14:08:50 +02:00
Marc-André Bombeck b45a668cf4 fix(charts): serve the All range's coarse buckets as their average day
The All range is read from the WEEK or MONTH rollup tier once a history is
long enough, from DAY rows for a short one, and from the live table on a
coverage miss. The chart folds every path into the average day of each
week or month, but a tier row carried a cumulative metric's whole total
and a level's reading-weighted mean. A month of steps therefore read about
thirty times higher for a long history than for a short one, under a
caption that said average.

A tier row now carries the average day of its bucket on every tier: a
cumulative metric's total over the days that hold a reading, a level's
mean of its daily means. The rollup fold counts the bucket's days and adds
up their means for it. Only the web chart's series reads (the chart
endpoint and the dashboard batch) use these rows.
2026-09-27 14:08:49 +02:00
Marc-André Bombeck e94e9b94a8 fix(medications): keep a medication's category when it is edited on the web
The add and edit wizard had no row for the thyroid, digestive, skin and
sleep-aid categories, so such a medication opened on "Other" and saving any
change, even a new dose time, rewrote its category to OTHER. The wizard
now offers a row for every category the app knows, translated in all seven
languages.

An edit also sends the category and treatment class only when the category
row was changed. A stored value the wizard cannot show, such as one a newer
server or another client wrote, now survives an unrelated edit.
2026-09-27 14:01:00 +02:00
Marc-André Bombeck c7e53176c1 Merge branch 'fix/v1394-review-correctness' into release/v1.39.4 2026-09-27 14:00:04 +02:00
Marc-André Bombeck a224875ed9 feat(medications): add mental health as a medication category
Antidepressants, anxiolytics, mood stabilisers and ADHD medication had no
category of their own and ended up under "Other". MENTAL_HEALTH joins the
clinical category list: the add and edit wizard offers it as its own row
with a brain icon, the card badge names it, and it is translated in all
seven languages.

The category is a text value, so no migration is needed. Clients that
read the category as a string show the new value; an app that does not
know it yet falls back to its own label for it.
2026-09-27 13:51:39 +02:00
Marc-André Bombeck 65c5cbda5b build: re-measure the aggregate client budget for v1.39.4
The release branch alone measured 3699 KB gz against the 3700 cap; the
review fixes added 1.3 KB gz across the whole build, nearly all of it new
copy in the seven lazy locale catalogs. The four eager routes measured
the same on both builds and stay inside their ceilings. The aggregate cap
moves to 3724, the same headroom as the earlier re-measurements.
2026-09-27 13:49:59 +02:00
Marc-André Bombeck 8295dfe9b6 fix(medications): stop offering a dose once the course has ended
A medication whose end date had passed still showed taken and skip in the
table and on its card, because the action row only looked at whether the
medication was active. The schedule engine already stops minting doses
after the end date, so reminders, the doses card and the today list were
quiet, but the medication itself kept inviting a dose that is no longer
part of the course.

The server now resolves one rule and publishes it on the list and detail
reads: `courseStatus` (UPCOMING, CURRENT or ENDED, in calendar days on the
user's clock, both ends inclusive) and `intakeActionable` (active, intake
tracked, course includes today). The table and both card variants render
their actions from it, the take-all flow skips such a medication, the card
and table name an ended course with an "Ended" badge, and no overdue
escalation is raised for it. A course that ends today keeps its actions
for the whole local day.

The detail header's "Ended" status now follows the same field. It compared
the end date's UTC midnight with the clock and so called the whole last
course day ended. Logging a past dose from the history is unchanged.
2026-09-27 13:49:21 +02:00
Marc-André Bombeck 0b72c44dbb Merge branch 'fix/sync-reset-after-restore' into release/v1.39.4 2026-09-27 13:46:55 +02:00
Marc-André Bombeck eda87fd4a7 fix(sync): expire delta cursors issued before a restore or a data wipe
A restore writes rows back with their original updatedAt, behind every
paired client's watermarks, and removes rows without leaving tombstones.
A client that kept its cursor would miss both on its next incremental
pull. The same holds after the person deletes all their data.

`users.sync_reset_at` (migration 0363) records when the record was last
replaced: the restore stamps it as its last write and again right after
the commit, the per-account and the admin wipe stamp it inside their
transactions. Cursors now carry the time they were issued, and
/api/sync/changes answers its existing `cursorExpired` to a cursor issued
before the reset, or one without an issue time on an account that has
one. The comparison is on the issue time, because after a restore a
freshly drained cursor still carries old watermarks.
2026-09-27 13:46:38 +02:00
Marc-André Bombeck 26352001b9 chore(coach): drop an unused type import from the method line 2026-09-27 13:43:39 +02:00
Marc-André Bombeck 4c7e5bc318 fix(coach): keep the reply's bubble when its persisted copy arrives
The persisted copy of a streamed reply used to mount as a new bubble, so
what the reader had done on the streamed one (the chart or table view, the
open steps list, the evidence panel) reset when the conversation refetch
landed. A turn now keeps one key from its first streamed frame to its
persisted copy, both render in the same wrapper, and the copy keeps the
live tables instead of refetching them, so React keeps the one bubble.
The wrapper stops being a live region once the turn is settled. The
150 ms twin-hiding window this replaces is gone.
2026-09-27 13:40:55 +02:00
Marc-André Bombeck 21a2e2fcef fix(coach): keep the chart on "as a table" so the chart is offered back
"As a table" used to drop the table's chart, so the reply offered no way
back to it. The copied table now keeps its chart and carries view: table,
which the panel opens on the table (the chart one tap away on the toggle)
and the chips read to offer "as a chart". show_result with view table
does the same. The field is optional on the result metadata; a client
that ignores it shows the chart first as before.
2026-09-27 13:36:48 +02:00
Marc-André Bombeck 5e9c4fe8d8 fix(jobs): allow the free-text backfill's address and audit counts as run facts 2026-09-27 13:32:59 +02:00
Marc-André Bombeck 14bc609712 test(coach): follow the comparison read and the question pointer in the dialog scenarios 2026-09-27 13:32:59 +02:00
Marc-André Bombeck b1629e2ad3 refactor(coach): keep the exclusion gate in its own module beside the snapshot builder 2026-09-27 13:32:58 +02:00
Marc-André Bombeck daf386fe7f fix(backup): use the renamed after-transaction allowance for the chart rebuild 2026-09-27 13:32:58 +02:00
Marc-André Bombeck 5173049130 Merge branch 'release/v1.39.4' into fix/v1394-review-correctness 2026-09-27 13:27:59 +02:00
Marc-André Bombeck ee5c44d9d7 fix(coach): name a night in the prose by the key the sleep table uses
The Coach's recent nights carried the wake instant in UTC as their date,
while the sleep table under the answer keys a night by the local day it
ends on. East of UTC the two named different days for the same night.
The snapshot now gives the night's own key.
2026-09-27 13:27:51 +02:00
Marc-André Bombeck 7e91596f02 perf(coach): send the table rules only when there is a table
The recheck and follow-up rules now ride the tool-mode prompt only once
the conversation holds a table, or from the round after the turn produced
its first one. The clarifying-question rules are shorter and English for
every locale, like the other instructions to the model; the German copy
of them and of the recheck rule is gone. A turn without tables sends
about 1 300 characters less on every round.

The golden transcripts change only in the system prompt's hash and
length (4 509 to 3 187 characters; 4 728 to 3 280 for the German turn).
2026-09-27 13:26:16 +02:00
Marc-André Bombeck 42e658f775 test(coach): pin the stored dialog id shapes 2026-09-27 13:22:29 +02:00
Marc-André Bombeck 6a458ac5b0 fix(coach): hold restored dialog ids to the shapes the server mints
Table refs, step ids, chip ids, a chip's anchor ref, clarification choice
ids and a reused table's source are now validated against their exact
server-minted patterns when a stored reply is read back. Some of them are
written into the model's context on a later turn (the earlier-tables list,
the "keep looking" fetched list), so a stored row edited by hand can no
longer carry text into a prompt through them.
2026-09-27 13:22:09 +02:00
Marc-André Bombeck d6ac4acad2 refactor(coach): count the assistant messages before the window inside the conversation read 2026-09-27 13:22:09 +02:00
Marc-André Bombeck 4e47670f25 refactor(coach): import the prior-table gate from the executor, not the tools barrel 2026-09-27 13:22:09 +02:00
Marc-André Bombeck 419ff04765 Merge branch 'fix/restore-large-account-clearing' into release/v1.39.4 2026-09-27 13:21:41 +02:00
Marc-André Bombeck fc13b9de5c fix(restore): skip expired tombstones and give the chart rebuild its own limit
A restore now leaves out measurement tombstones deleted longer ago than
the tombstone retention. The nightly purge removes exactly those rows,
the delta feed answers cursorExpired for every cursor that could still
be served one, and the consolidation repairs look only inside the same
horizon. Younger tombstones keep their readers (a lagging paired client,
the undo of a recent delete, the repairs, the duplicate guard on
re-uploaded samples) and are written as before. The backup file is
unchanged. On a seeded account of 1.89 million readings whose 1.68
million tombstones were past retention, the restore on a slowed database
took 5.4 min instead of 15.

The rollup fold after the commit rebuilt five years of buckets under the
60 s request statement limit and could be dropped on a slow disk, leaving
the charts empty until the next boot. `recomputeUserRollups` takes a
`statementTimeoutMs` that scopes each aggregate and persist transaction
with SET LOCAL, and the restore passes its after-commit allowance.

Fixture tombstones in two round-trip tests were dated in July 2026 and
had aged past the retention; they are now relative to the run.
2026-09-27 13:21:18 +02:00
Marc-André Bombeck c133acb332 test(import): stage the zip-bomb extraction in the test's own directory
The test diffed the shared system tmpdir before and after the extraction,
and other test files extracting in parallel stage their files there too,
so it failed on their files rather than its own. TMPDIR now points at a
directory of the test's own for the call.
2026-09-27 13:21:18 +02:00
Marc-André Bombeck bd3aa3ddb1 fix(coach): hold an excluded metric's earlier tables back from the model
show_result now passes the same scope gate a fresh read does before it
decrypts a stored table: a metric the person has since excluded from the
Coach, or one outside the conversation's scope, answers
unavailable_in_scope and nothing is sent. The list of earlier tables in
the context drops those metrics too, so the model is not told they exist.

The exclusion (the person's own list plus switched-off modules, and no
adherence when medications are excluded) is the snapshot builder's, now
one exported helper both paths use.
2026-09-27 13:18:26 +02:00
Marc-André Bombeck 6da52805bd Merge branch 'coach/wp8-evals' into release/v1.39.4 2026-09-27 13:18:26 +02:00
Marc-André Bombeck 2d9443b0b7 fix(coach): keep the person's question out of the system role, read the latest messages once
"Keep looking" no longer copies the unfinished question into the
server-written context lines. The question stays in the transcript as the
person's own turn; the line only points at it. Lifted into the system
role, whatever the question said would have carried the system's
authority.

A turn now reads its conversation's newest messages once and shares the
rows between the chip, clarification, "keep looking" and repeat-question
checks, instead of three identical reads.

Earlier tables keep their m<k> names once a conversation outgrows the
window a turn loads: the index counts the assistant messages before the
window too, so a name the model read on an earlier turn still points at
the same table.
2026-09-27 13:16:08 +02:00
Marc-André Bombeck eeda21c7a1 refactor(coach): keep the table storage budget in the pure refs module
The backup validation now reads the per-message table ceiling from
results/refs, which imports nothing but types. Reading it from
results/project pulled the tool executor and the message store into the
snapshot builder's import graph, and the free-text sanitiser guard then
walked files that never build a prompt.
2026-09-27 13:15:48 +02:00
Marc-André Bombeck 874d02294e fix(backup): let the restore job's budget admit large accounts
A restore is refused before it deletes anything when its transaction limit
would run past three quarters of the job's expiry. At two hours that refused
a same-size replacement of about four million readings. The expiry is now six
hours, which admits ten million over ten million; a dead worker still frees
the account within minutes through the heartbeat, so the longer expiry does
not hold an account longer.

The refusal now names both counts, the readings in the backup and the ones the
account holds now (removed readings included until the nightly clean-up),
since clearing the latter costs time too.
2026-09-27 13:13:50 +02:00
Marc-André Bombeck e7a786f64a test(coach): stream a clarifying reply without chips, as the server does
The server offers no chips under a clarifying question. The second
streamed turn now carries the card alone, and axe runs once with the
chips under the first answer and once with the card.
2026-09-27 13:11:53 +02:00
Marc-André Bombeck 8342d2337b test(coach): register the live scenario run with the egress and env guards
run-case.ts now calls a provider for the live scenario run, and judge.ts
reads COACH_EVAL_SCENARIO_REPEATS. Both belong to the offline evaluation
harness, like the judge and its model knobs.
2026-09-27 13:11:52 +02:00
Marc-André Bombeck 89110abeb6 fix(backup): bound a Coach turn's stored tables on restore
A turn never stores more than 128 KB of table JSON, but a restore accepted
any size in resultsJson or resultsEncrypted and sealed it into the database.
Both are now bounded: the readable form by its UTF-8 size, the sealed form at
twice that, above the ciphertext's measured expansion. A file this release
writes always fits; a larger value is refused like any other malformed field.
2026-09-27 13:08:40 +02:00
Marc-André Bombeck 4558271b3e fix(coach): let a correct comparison with an earlier period stand
The grounding ledger derives differences only between figures of one
payload, so a correct "up 4 mmHg on last week" drawn from two separate
table reads was withheld as unverified. A table of the period before or of
a year ago now reads the current window too, and its summary carries the
current figures and the change (delta and percent change) beside the
earlier ones. A wrong delta is still flagged.
2026-09-27 13:08:36 +02:00
Marc-André Bombeck c2ab9cda11 test(coach): put the dialog scenarios to a real model nightly
The live evaluation now captures the tool calls a generation makes, with
their arguments, and hands them to the judge. runScenarioLive puts a
scenario to the model in the chat turn's own context (system prompt,
tool-mode and dialog addenda, DATA INVENTORY, EARLIER TABLES, transcript)
over the real tool catalogue, answers each call with a stand-in result,
and reads the reply through the turn's clarification and chip parsers.
runScenarioJudge grades each scenario a few times with the same
evaluateScenario the deterministic suite uses and reports a pass rate per
scenario; the server-only scenarios and checks are left out.

Like the existing judge it runs only with COACH_EVAL_API_KEY, from the
nightly workflow's non-blocking step, and never throws.
2026-09-27 13:07:25 +02:00
Marc-André Bombeck 9913734961 fix(coach): move focus to the composer after a chip or a clarification choice
A tapped follow-up chip goes away and a clarification choice disables as
the turn starts, which dropped focus to the page. Both now hand focus to
the composer, which stays focusable while a reply streams (read-only with
aria-disabled rather than disabled). The clarification question is
announced through a live region that is mounted before the question
arrives; the card itself no longer carries one.
2026-09-27 13:07:18 +02:00
Marc-André Bombeck 1dd74bfa20 test(coach): follow the related-metric chip copy 2026-09-27 13:07:18 +02:00
Marc-André Bombeck 722945702a fix(privacy): clear the last readable copies of practitioner contact details
The encryption backfill now also removes the two copies of a practitioner's
contact details that outlived the sealing. An appointment reminder's copy of
the address is cleared, since the reminder resolves it from the practitioner
when it fires. An address-book edit's audit row written before the sealing
kept the old phone number and address in its previous values; those values
leave the row and the changed fields stay named. Rows of a deleted account,
which no per-account job reaches, are scrubbed by the discovery pass itself.

A route whose readable geometry is a JSON null rather than SQL NULL had
nothing to seal but matched discovery every night. The pass now sets it to
SQL NULL so it drops out.
2026-09-27 13:07:17 +02:00
Marc-André Bombeck 3482581ce1 fix(encounters): name the practice address on an appointment nudge again
Sealing the practitioner's address left the appointment arm reading the old
readable column, which is now empty, so a booked visit's push lost the address
on booking, rescheduling and restoring a deleted visit.

The reminder no longer keeps its own copy of the address. The reminder tick
resolves it from the owning visit's practitioner when it builds the push and
decrypts it there, so an edit of the address also reaches a nudge that is
already booked. MeasurementReminder.location stays NULL on appointment rows:
booking writes none, a re-anchor clears one an earlier release wrote, and a
backup neither carries nor restores one. A checkup's own free-text location is
unchanged.
2026-09-27 13:07:10 +02:00
Marc-André Bombeck 9892088620 fix(coach): account for every stored table and keep table controls on screen
A withheld table now leaves a line saying why (module off, or the stored
tables could not be read) and a failed read shows an error row with a
retry, so the Data used count matches what is listed. A table copied from
an earlier answer names that answer's date under its title. The preview
shows the latest twelve periods of a time series, and the truncation note
says the latest rows are kept, which is what the server keeps. The title,
copy and view controls sit above the scrolling table with the title kept
as a hidden caption, and a reply with tables takes the full column width.

The step headers and the related-metric chip read as label: value in all
seven locales, so a metric name no longer sits capitalised mid-sentence.
2026-09-27 13:07:07 +02:00
Marc-André Bombeck 25ad1810c2 fix(coach): offer the period before only when the record reaches back
The "compare with the period before" chip now needs a first reading
before the window's start, the same history check the other history chips
use, and is never offered on an all-time table, which has no period
before it: the table tool reads all time as the current period whatever
it is asked.
2026-09-27 13:06:55 +02:00
Marc-André Bombeck 203068d5ba fix(coach): keep a billed reply when its tables fail, and fit tables once
Tables are now projected outside the provider's failure path: a
projection defect costs the turn its tables and is annotated, instead of
refunding tokens already billed and dropping the reply.

The at-rest ceiling for a message's tables is applied once, when the
dialog is assembled, before anything streams. A table trimmed only at
write time used to show live and read back as withheld after a reload.
2026-09-27 13:06:02 +02:00
Marc-André Bombeck 49df950043 test(coach): pin all-time step months across history lengths and read paths 2026-09-27 13:04:30 +02:00
Marc-André Bombeck ec281c02e2 test(coach): grade the dialog scenarios through the real pipeline
Ten scenarios, each in German and English, describe what a turn must do
with a question: which tool it calls and with which arguments, whether it
may read anything new, whether it asks back, declines a dose, offers
chips only for what the record holds, answers a chip without a provider,
offers to keep looking after a forced answer, and keeps an earlier
table's title out of the model's context. evaluateScenario grades a run
against them.

The deterministic suite drives POST /api/insights/chat with a scripted
provider; the tool loop, executor, table tool, chips, clarification
filter, method line, reply guards and stream run for real. Every check
also runs against a misbehaving model or a broken record and must fail
there.

route-followups.test.ts pins the front door for chips and answered
questions: validation, the rate limit and capability gate on a reuse
turn, the stored chip winning over anything the request adds, stale
chips and answers degrading to a plain message, and the continue line.
2026-09-27 13:04:12 +02:00
Marc-André Bombeck de2200bd5c fix(coach): make table weeks and months mean one thing per metric
A total's weeks and months are now the sum of its days, labelled as a
total, and a level's stay a mean. All time is read as UTC calendar months
from the rollup tier's MONTH fold, or the same fold of the live table when
the tier has no rows, so a month no longer reads as a mean of daily totals
for a short history and a monthly total for a long one. Months are keyed
by their UTC start instead of being re-read in the user's zone, which
named every month one early west of UTC.

The chart's long ranges had the same shift: tier rows are now stamped at
noon UTC of the bucket's first day, which falls inside the bucket's own
week and month in every zone.

Step length and walking speed keep two decimals, loud-sound events count
as a total in whole events, and HRV counts a night measured by both
estimators once and charts the estimator the person mostly has. The model
summary names what a period's value is and gives a total's range total.
2026-09-27 13:03:31 +02:00
Marc-André Bombeck 7c32dca7ab fix(coach): count distinct sources in the finished steps header 2026-09-27 13:03:28 +02:00
Marc-André Bombeck bc6c782745 fix(coach): quote formula starts behind whitespace, in fullwidth and pipe when copying a table 2026-09-27 13:03:27 +02:00
Marc-André Bombeck 40ea0d8ed3 test(coach): cover the dialog in the browser
Three streamed turns against a stubbed chat stream: steps under the answer, a result table with its chart/table toggle and copy menu, a follow-up chip and a clarification choice that each send which one was tapped, and axe over the answer, chips and card in both themes.
2026-09-27 13:02:49 +02:00
Marc-André Bombeck 56e51ebed2 fix(coach): catch a German dose change that names the dose
The outbound screen matched "Erhöhe auf 2,4 mg" but not "Erhöhe deine
Dosis auf 2,4 mg": the German change verbs had no slot for an object
between the verb and the target, unlike the English "increase your dose
to". The raise and lower patterns now accept one.
2026-09-27 13:00:07 +02:00
Marc-André Bombeck 38a7e386a9 fix(coach): keep the chart on a table shown again
Asking for an earlier table "as a chart" went through show_result, which
builds the requested view, but collecting the turn's tables then reset
every chart to null and only derived a new one for fresh tables. The table
came back without its chart. A table shown again now keeps the view it was
given.
2026-09-27 13:00:07 +02:00
Marc-André Bombeck c1aa235e27 fix(workouts): read a route that does not open as no track
A damaged or foreign-key route ciphertext threw out of readRouteGeometry, so
one bad track answered the workout detail with a 500 and failed the activity
insight job. It now reads as no track with a warning on the request event, and
still never falls back to the readable column.
2026-09-27 12:56:01 +02:00
Marc-André Bombeck 74f4c6e767 fix(coach): step a result chart's value axis evenly
The line and bar charts under a Coach reply let recharts place the y-axis
ticks over an auto domain, and after thinning the ones that would collide
a blood pressure line could read 75, 90, 105, 135. The chart now computes
a nice domain and hands explicit ticks one step apart (1, 2, 2.5 or 5
times a power of ten); bars keep their zero baseline.
2026-09-27 12:51:43 +02:00
Marc-André Bombeck e7f3385374 Merge branch 'coach/wp3-charts' into release/v1.39.4 2026-09-27 12:47:28 +02:00
Marc-André Bombeck b5d33502dc feat(coach): show result tables as charts with a chart/table toggle
A table the answer referenced opens under the prose as its chart; the
others sit under Data used in the evidence disclosure and open as
tables. The plot is one image whose name points at the table view, two
series carry legend buttons, and the chart loads through the shared
chart runtime. A metric chart token for a metric a shown table already
covers is dropped.
2026-09-27 12:47:06 +02:00
Marc-André Bombeck d63d2e6d83 Merge branch 'coach/wp7-continue' into release/v1.39.4
# Conflicts:
#	src/lib/ai/coach/turn/pipeline.ts
#	src/lib/ai/coach/turn/provenance.ts
2026-09-27 12:43:23 +02:00
Marc-André Bombeck 968b8b1efd Merge branch 'coach/wp4-followups' into release/v1.39.4 2026-09-27 12:41:44 +02:00
Marc-André Bombeck b5023ae935 feat(coach): keep looking after the round cap
When the tool loop forces an answer at its round cap, the reply leads
its chips with "Keep looking". Tapping it runs a normal turn, under the
budget gate as ever, with two server-written context lines: the question
that was left unfinished (at most 1000 characters) and what the forced
turn already read, each table by the name show_result takes, so the
continued turn shows those again instead of fetching them twice.

An answer is continued at most once. The continued reply records the
message it continues in metricSource.continuationOf and offers no
further "Keep looking", even when it is forced again; a chip on a reply
that is itself a continuation is refused.
2026-09-27 12:41:20 +02:00
Marc-André Bombeck 66718a1c7d feat(coach): follow-up chips under the latest answer
Up to three chips, derived on the server from what the turn read: the
other view of a table with a chart, the period before, a year earlier,
a wider window, and a metric a discovered pattern links to. A chip is
offered only when its read was done this turn and the record holds the
metric; the year-ago and wider-window chips also need the record's
first reading to reach back that far. The model may name chips in a
FOLLOWUPS block, but only to reorder ones the rules already allow; every
label is rendered from the catalog.

A tapped chip resolves against the chips stored on the conversation's
latest reply. "As a chart" and "as a table" are answered from the
stored table without a model call or a budget reservation: the rows are
copied unchanged and the message is tagged providerType "reuse". Other
chips run a normal turn with a server-written context line. A chip that
is no longer current falls back to a plain message.

A setting turns the chips off (absent means on).
2026-09-27 12:36:01 +02:00
Marc-André Bombeck c4bf5a916d feat(coach): choose a chart for each result table on the server
A table over time is drawn as a line for a level metric and as bars
for a total, with at most two series in one unit. Category counts get
bars, horizontal above six categories, the top eight and one other.
Fewer than two or more than 400 rows, or no numeric column, stay table
only. show_result's view now counts: table drops the chart, chart turns
an earlier day table into counts per range with a histogram (fixed
widths for the common metrics, Freedman-Diaconis otherwise, none below
ten values).
2026-09-27 12:34:06 +02:00
Marc-André Bombeck 02801bdfda Merge branch 'fix/restore-large-account-clearing' into release/v1.39.4 2026-09-27 12:14:04 +02:00
Marc-André Bombeck db10ba714e test(coach): pin the answered-clarification line on the local path
The line that resolves an answered clarifying question was already
appended to the system prompt on both paths; nothing proved it for the
no-tools (local model) path. Three route-level cases now do: the local
prompt and the tool-mode prompt both carry the server-resolved line, and
a turn without an answer carries neither. Removing the line from the
local prompt fails the first case.

The golden harness gains a coachMessage.findMany mock for this; it
defaults to no rows, so no existing transcript changes and the golden
snapshots are untouched.

The result-table caption test used the regex dotAll flag, which the
TypeScript target rejects (TS1501); it matches across lines with
[\s\S] instead.
2026-09-27 12:11:55 +02:00
Marc-André Bombeck b40de3a4d9 fix(coach): count a table shown again once, and say it is from before
The method line merged a repeated read by keeping the larger count. With
show_result that could let an earlier answer's count stand over the read
this turn just made. A fresh read of the same source, window and period
now always wins, whichever order the steps ran in, and the two are never
added. An entry that rests only on an earlier table says so ("from an
earlier answer"), including a reused table no step accounts for.

The new catalog string is in all seven locales.
2026-09-27 12:11:55 +02:00
Marc-André Bombeck ad541cd5bb fix(coach): show a step for metric tables and for a table shown again
get_metric_table now gets a step like every other read: the domain is
its validated metric, and once the table is in, the window, period and
granularity are the ones the table was built with (after the executor's
defaults). The count is the readings the table folds, taken from the
summary the server computed, so a read past the sixth table still counts.
A step whose call produced a table now names it (resultRef), for the
projected tables of the older tools as well.

show_result gets its own step. It reads nothing new: while it runs it
names no domain, and once the stored table is found it takes the source
of the read that built it and the name the copy carries in this turn. A
table that could not be shown is a failed step with the reason, never an
empty read.

The property test now drives show_result too and checks resultRef; the
coverage test gives each tool the smallest arguments it accepts instead
of passing empty arguments to a tool that requires a metric.
2026-09-27 12:11:54 +02:00
Marc-André Bombeck e0b4f3c427 fix(restore): size the restore budget by the rows written, and keep test housekeeping off the short limit 2026-09-27 11:57:37 +02:00
Marc-André Bombeck 914fcbcbf1 Merge branch 'coach/wp2-tables' into release/v1.39.4
# Conflicts:
#	src/app/api/insights/chat/__tests__/__snapshots__/golden-transcripts.test.ts.snap
2026-09-27 11:55:05 +02:00
Marc-André Bombeck 47efdd6606 feat(coach): result table with copy for a spreadsheet or as text
The table shows its caption, scoped headers, right-aligned tabular
numbers and a dash for a missing reading, twelve rows before Show all.
Copy writes TSV and an HTML table together, falling back to TSV, with
formula starts neutralised and separators flattened inside cells.
2026-09-27 11:54:31 +02:00
Marc-André Bombeck a967ccac44 feat(coach): metric tables and show_result for the chat tools
get_metric_table reads one metric as days, weeks or months through the
chart reader, cut in the user's zone and collapsed to one source per day,
with null for a period without a reading. The model reads a bounded
summary; the full table rides the turn, encrypted at rest. show_result
shows a table an earlier reply of the same conversation fetched, resolved
only against that conversation's own messages. Workouts, labs, sleep and
adherence results project into tables, earlier tables are named in the
context by metadata alone, and result:rN marks are stripped from the reply.
2026-09-27 11:54:30 +02:00
Marc-André Bombeck b84ea0604f Merge branch 'coach/wp1-steps' into release/v1.39.4
# Conflicts:
#	src/app/api/insights/chat/__tests__/route-capability-gate.test.ts
#	src/app/api/insights/chat/__tests__/route-list-query.test.ts
2026-09-27 11:53:39 +02:00
Marc-André Bombeck cbf603c3c9 Merge branch 'fix/sidebar-collapse-bottom' into release/v1.39.4 2026-09-27 11:51:13 +02:00
Marc-André Bombeck 00a5a8862f Merge branch 'coach/wp5-clarify' into release/v1.39.4
# Conflicts:
#	src/app/api/insights/chat/__tests__/__snapshots__/golden-transcripts.test.ts.snap
2026-09-27 11:47:52 +02:00
Marc-André Bombeck d2aba1b86b feat(nav): move the sidebar collapse control to the bottom of the sidebar
The small chevron above the first nav entry becomes a full footer row that
heads the utility group: directly above Admin for an administrator, directly
above Settings for everyone else. PanelLeftClose / PanelLeftOpen mark the two
states; the label reads Collapse while expanded and stays for screen readers
only in the icon rail, where the tooltip names the action. aria-label switches
between collapse and expand; the stored choice keeps its storage key.

The width transition now honours reduced motion. Adds the expand and
sidebar-action labels in all seven locales.
2026-09-27 11:47:48 +02:00
Marc-André Bombeck dc085cff4d Merge branch 'coach/wp6-method' into release/v1.39.4 2026-09-27 11:47:38 +02:00
Marc-André Bombeck 01aba93878 feat(coach): say how an answer was worked out
The evidence disclosure under a Coach answer now carries one muted
line: which sources and windows the turn read, how many readings, and
how they were aggregated ("Blood pressure, last 90 days: 142 readings,
weekly averages · Sleep, last 30 days: no readings in this window").
The server builds it from the recorded steps and tables in the request
locale; it holds catalog strings and counts only, never a reading, and
a source that turned up nothing says so.

The tool-mode prompt gains a recheck rule: when the person questions a
figure, name the source and window, read it again (or reuse the stored
table), and correct the answer if the two differ.
2026-09-27 11:47:11 +02:00
Marc-André Bombeck 1914764ddc feat(coach): show what the Coach looked at above the answer
While a turn runs, the header names the read in progress with a soft
shimmer; when it ends the list folds into "Looked at N sources". Each
row reads domain, window, and the count or the reason nothing was
found. Completed steps are announced through a polite status region at
most once every 1.5 s, and a reloaded conversation stays quiet. The
spinner and shimmer stop under reduced motion.
2026-09-27 11:44:55 +02:00
Marc-André Bombeck ea2eaf2074 feat(coach): stream a step for every read the turn makes
Each tool call now emits a running step as it starts and its final
status as it settles: found with a server-counted number of readings,
empty with the reason, or failed. The no-tools path shows one step for
the record summary. Steps carry catalog labels rendered in the request
language, closed-enum domains and windows, and integers only; a lab
analyte, a value or a model-written argument never reaches one. At most
twelve per turn. They persist on the provenance, so a reload shows the
same list.

The conversation window reaches the step so a call without a window
names the one it actually read. The no-tools transcripts gain the
summary step; a new transcript pins found, empty and failed steps ahead
of the first token.
2026-09-27 11:44:54 +02:00
Marc-André Bombeck d44b875ec6 test(restore): stub the reading count the restore budget now reads 2026-09-27 11:37:51 +02:00
Marc-André Bombeck 6b07d48bf9 feat(coach): ask back when the metric or window is ambiguous
A reply may end with a ---CLARIFY--- block (kind metric, window or
context, 512-byte cap). The server keeps only metric choices the record
holds, drops the question when fewer than two remain, takes window
choices from the presets, screens the question text like any reply, and
never offers a second question right after one. Choice labels come from
the catalog, never from the model.

An answer arrives as clarification { messageId, choiceId? }; it resolves
against the stored question on the conversation's latest message and
adds one server-written line to the next turn's context. The card sits
above the composer, announces politely and takes no focus.

A reply that is only the block, with no question before it, is now an
empty reply instead of falling back to the unstripped text.
2026-09-27 11:33:32 +02:00
Marc-André Bombeck 93b6c086b4 fix(restore): let a large restore outlast the request statement timeout
A restore of an account with 1.9 million readings, most of them deleted
by the nightly consolidation and still awaiting the purge, was cancelled
in its clearing step: `DELETE FROM measurements` ran past the 60 s
statement timeout every pooled connection carries, and the whole restore
rolled back with a message that named no cause (#1031).

Most of that statement was not the delete. Two columns point into
`measurements` with ON DELETE SET NULL and had no index, so Postgres
scanned `personal_records` and `ecg_recordings` once per deleted reading:
38 of 40 s on a seeded account with 300 personal records. Migration 0362
indexes both, which also speeds up the tombstone purge and account
deletion.

The restore transaction now sets its own statement and idle-in-transaction
limits to the transaction budget with SET LOCAL, and the budget counts
the rows the account holds as well as the rows the file carries. A
rolled-back restore names what the database refused it over (timeout,
lock, constraint, storage, connection, other) on the job row, the
console, the audit row and the wide event.
2026-09-27 11:24:41 +02:00
Marc-André Bombeck 78fc22d0f8 Merge branch 'coach/wpF-contracts' into release/v1.39.4 2026-09-27 11:10:37 +02:00
Marc-André Bombeck 1e9b0aa7ff test(api): list the stored-tables route among the per-table module-gated reads 2026-09-27 11:02:14 +02:00
Marc-André Bombeck 0598b58f0e feat(coach): client slots for steps, tables, method, chips and clarification
The streaming hook handles the step, result, followUps and clarification
frames and sends followUp and clarification on the tool route only. The
bubble gains slots for the step list, the tables and the method line; the
thread offers chips under the latest assistant turn only; the conversation
shows the clarification card above the composer and marks a typed answer
as answering it. The tables of a persisted message load lazily when it
scrolls into view, seeded from the stream for the turn that produced them.
The new components render nothing yet.
2026-09-27 10:57:53 +02:00
Marc-André Bombeck fe0a03761e feat(coach): message catalog for the dialog in all seven languages
Adds every string the dialog needs up front: step labels, table titles,
columns and controls, the method line, the follow-up chips and their
setting, the clarification card, and the caption of an answer reused from
a stored table. A key catalog shared by server and client names each one;
a test holds the catalog and the bundles equal in both directions.
2026-09-27 10:50:49 +02:00
Marc-André Bombeck ad72ae3e4c feat(coach): serve a message's stored tables and publish the stream contract
GET /api/insights/chat/{id}/messages/{messageId}/results returns the
tables one assistant message read, narrowed to the conversation's owner
like the conversation read, with a table withheld as module_disabled when
its domain's module is off and as unavailable when it cannot be read. A
data read: no AI capability.

The published document now describes every stream frame as the
CoachStreamEvent union, including the suggestedAction frame it never
named, the new step, result, followUps and clarification frames, their
components, the provenance fields, the followUp and clarification request
fields, and the reuse provider type.
2026-09-27 10:45:18 +02:00
Marc-André Bombeck 8fcd204172 feat(coach): seams for steps, tables, charts, method, chips and clarification
Each later piece of the dialog gets its own module, answering nothing for
now: the step builder, the table projection and chart choice, the result
ref marks, the follow-up derivation, sentinel, resolution and continue
chip, the reuse turn, the clarification parse and answer, the method line,
and the four prompt addenda. The turn pipeline calls them where they
belong, so the frames go out in the documented order (step, token,
provenance, result, cards, clarification, followUps, done) and a blocked
turn drops its tables, chips and clarification. With every piece empty
the stream and the prompt stay byte for byte as before.
2026-09-27 10:43:15 +02:00
Marc-André Bombeck 2feb622b6a Merge branch 'fix/encrypt-routes-and-practitioner-contact' into release/v1.39.4 2026-09-27 10:38:08 +02:00
Marc-André Bombeck 742ef2c9b0 feat(coach): report tool calls as they start and settle
The retrieval loop takes onCallStart and onCallSettled callbacks, fired
for every call with a turn-wide index; a throwing callback is swallowed.
The trace carries each call's schema-validated arguments (never the raw
string, never persisted), the result says whether the answer was forced
at the round cap, and a seedCalls parameter is accepted but not read yet.
2026-09-27 10:37:40 +02:00
Marc-André Bombeck f2e32afb24 fix(privacy): store environment coordinates at 1 decimal instead of 2
The home location of the environment module was rounded to 2 decimals,
about 1 km, which places a home in a neighbourhood rather than the town the
schema comment promised. The weather archive it feeds is gridded at 9 to
25 km, so the extra precision bought nothing.

Every stored coordinate of the module now goes through the same 1-decimal
rounding (about 11 km north-south, 7 km east-west at 50° N): the home, the
travel periods, the geocoder's results, the per-day weather rows, and a
restore of a file written with finer values. Migration 0361 rounds the
existing users, travel periods and per-day rows; running it twice changes
nothing more. The answers keep their shape, plain numbers. The API
descriptions and the schema comment say 1 decimal now.
2026-09-27 10:37:37 +02:00
Marc-André Bombeck a8b3e5d7f4 feat(coach): store a turn's result tables encrypted beside the message
A new nullable column, coach_messages.results_encrypted, holds the tables
of values a turn read as AES-GCM ciphertext; only their metadata rides the
plaintext provenance. readMessageResults serves them to the owner, each
table whole or withheld with a reason. The provenance restore learns the
steps, method, table metadata, chips, clarification and the forced-answer
marker, entry by entry against the wire schema.

The column is registered for key rotation, carried through both backup
formats (ciphertext in a disaster-recovery file, readable JSON in a
portable one) and goes with its row on conversation delete and wipe.
2026-09-27 10:36:27 +02:00
Marc-André Bombeck cde7af3cf8 feat(coach): wire contract for steps, result tables, method, follow-ups and clarification
Adds the TypeScript types for the four additive stream frames and their
provenance fields, a Zod mirror for the published document held equal to
the types by a type test, and a guard that no newer frame reuses a key the
shipped native client decodes. The chat request accepts followUp and
clarification, inert for now.
2026-09-27 10:33:13 +02:00
Marc-André Bombeck 620c538f9d Merge branch 'coach/wp0-pipeline' into release/v1.39.4 2026-09-27 10:25:41 +02:00
Marc-André Bombeck b8e78a78b3 chore(openapi): regenerate for the practitioner backup ciphertext fields
The practitioner entry of the backup payload gains the optional
locationEncrypted and phoneEncrypted fields. The rotation script names each
new column once, at its call, so a dropped call is noticed rather than
covered by a comment.
2026-09-27 10:21:48 +02:00
Marc-André Bombeck fe53804c4c refactor(coach): split the chat turn into a pipeline under lib/ai/coach/turn
The route keeps the front door: auth, the coach capability, the body
read and schema, the rate limit, the locale and the inbound refusal
screen. Everything after it moves into one module per step:
conversation, context, chain, budget, model, reply-guards, cards,
provenance, persist, sse, errors and pipeline. The capability re-check
at the egress site stays owned by the route and is handed to the
pipeline, so the capability inventory still reads both calls there.

The stream producer now writes through a TurnEmitter created inside
createSseStream and passed to the model step, which is where live
progress frames will come from. Nothing writes to it early yet.

No behaviour change: the golden transcripts pass byte-identical, the
existing route tests pass unmodified, and every annotate, audit and
error-code name appears as often as before.

Guards follow the code. The fence call-site check reads turn/context.ts,
the German-default locale ban covers every file in turn/, and the
fenced module-graph test now asserts that turn/sse.ts and turn/errors.ts
reach neither the tool registry nor the snapshot builder. That test
named lib/ai/coach/tools.ts, which stopped existing when the registry
became a directory, so its negative check could not fail; it points at
tools/index.ts now, and a new sanity check fails if the tool route can
no longer reach the path it names.
2026-09-27 10:14:07 +02:00
Marc-André Bombeck 5eb7956bad fix(privacy): encrypt workout GPS tracks and practitioner contact details at rest
The GPS track of an outdoor workout was stored readable, and its first and
last points are usually the person's front door. The phone number and address
in the address book of doctors and practices were readable too, while the
note beside them was already encrypted.

Migration 0361 adds workout_routes.geometry_encrypted (the geometry loses
its NOT NULL) and practitioners.phone_encrypted / location_encrypted, plus
partial indexes on the backfill's discovery predicates. A track is sealed as
one binary AES-256-GCM value bound to its purpose; the contact fields use the
same Bytes codec as the note. The practitioner's name, practice and specialty
stay readable, because the picker searches and sorts on them.

Every writer stores ciphertext only: workout batch ingest, practitioner
create and edit, and both restore formats. Readers prefer the ciphertext and
fall back to the old column for rows not yet migrated: the workout detail
(map, splits, GPX), the activity insight's climb figure, the practitioner
DTO behind the address book, visits and vaccinations. The wire shape does not
change. An edit's audit row now names a changed phone number or address
without recording either value.

free-text-encryption-backfill covers the three columns in the same pass,
finding a route through its workout. All three are registered for key
rotation (registry, CLI script, and the in-app rotation). A disaster-recovery
backup carries the contact fields as ciphertext only; a portable export
carries them readable. Workout routes are still not part of a backup, as
before. The old columns are marked for removal in a later release.
2026-09-27 09:59:34 +02:00
Marc-André Bombeck 17abd37dd7 test(coach): pin the chat turn as golden SSE transcripts
Drive POST /api/insights/chat through the real SSE stream and the real
reply guards for every branch a turn can take: tool mode with present,
drifted and missing figures, the no-tools path, inbound and replayed
refusals, the budget refusal, each provider failure class, a cancelled
turn, the outbound block, every sentinel in its valid and malformed
forms, learn-link scrubbing, the three no-provider paths, a workout
scope, the post-call defect path, and the refusals that answer before
the stream opens.

Each transcript records the frames the client receives (heartbeat
comments dropped) and the ordered side effects: persisted messages,
budget reserve and reconcile, audit rows, annotate names with their
meta keys, and the provider inputs as prompt fingerprints.
2026-09-27 09:50:51 +02:00
Marc-André Bombeck 69ddcc28e7 Merge pull request #1043 from MBombeck/fix/e2e-delegated-writes
test(e2e): run the delegated-writes journey and fail CI when a spec skips entirely
2026-09-27 05:10:00 +02:00
Marc-André Bombeck ed05772a8e test(e2e): run the delegated-writes journey and fail on silent skips
The delegated-writes spec checked for the invitation form's level control
right after page load, before the form had painted, found nothing and
skipped every test on every run, CI included.

- Give the journey its own account pair, seeded and reset in global setup,
  so it no longer invites the same pair as the account-sharing journey
  (a second live grant between two accounts is refused with 409).
- Wait for the form through its data-slot and fail when the WRITE level
  control is missing instead of skipping.
- Revoke the journey's grant in afterAll.
- Keep it out of the mobile project in the config rather than through a
  runtime skip.

Add two checks so a skip cannot hide a spec again:

- e2e-conditional-skip-guard.test.ts requires every conditional
  test.skip/test.fixme in e2e/ to carry a reason and refuses a bare
  test.skip().
- scripts/check-e2e-skipped-specs.mjs reads the Playwright JSON reports of
  both shards in the e2e gate job and fails when a spec file skipped all of
  its tests across every project, apart from an allowlist with reasons.
2026-09-27 04:48:08 +02:00
Marc-André Bombeck 1f725326b0 Merge pull request #1042 from MBombeck/release/v1.39.3
Release v1.39.3
2026-09-27 03:40:29 +02:00
Marc-André Bombeck f57b6bf979 fix(admin): one card that fails to render no longer takes the page down
An admin page stacks independent cards, and a card that threw while
rendering replaced the whole page, so a field missing from the off-host
card's payload hid the snapshot table beside it. Every card in an admin
section now sits in its own boundary and fails as an error card with a
retry that remounts it; the rest of the page keeps working.
2026-09-27 03:19:39 +02:00
Marc-André Bombeck 881a8d9061 test(e2e): meet every recent-proof gate from a stale session
The invitation journeys, the backup journey (archive, snapshot download
and restores) and the delegated doctor report acted on jars signed in once
in global setup, so they passed or met the re-proof gate depending on how
far into the run they started. Each now acts from a session of its own,
made stale before every gated press, and answers the dialog with the
password; the delegated report asserts the 401 before re-proving over the
wire. The helper gains expireRecentProof, reproveWithPassword and
actWithReproof.
2026-09-27 03:19:39 +02:00
Marc-André Bombeck bf7bb0925d test(a11y): give the mocked backups list its off-host deletion and lifecycle fields
The off-host card reads pendingDeletions and lifecycle, which the route
always sends. The mock predated them, so the card threw and the page never
painted its rows. The mock now carries a refused deletion and a bucket
without an expiry rule, so the scan reaches both new lines.
2026-09-27 03:00:37 +02:00
Marc-André Bombeck 95ea178929 test(e2e): start the report fixture's drug before the empty window
A report for a past window lists a medication only if its course had begun
by the window's end. The fixture's drug was entered on the day of the run,
so it was rightly absent from a report for last year and the control that
expected it failed. The course now starts before that window. Generating the
report also meets the re-proof dialog from a stale session every time,
rather than only when the run has been going for five minutes.
2026-09-27 03:00:37 +02:00
Marc-André Bombeck a6daa84c17 test(e2e): meet the recent-proof gate from a stale session, as a person does
Connecting an assistant and making a share link ask for a sign-in or
re-proof within five minutes. The shared jar is signed in once in global
setup, so the specs passed early in a run and failed later. They now start
from a session of their own signed in ten minutes ago: the consent page
withholds Allow and links to the confirm page, where the password re-proof
returns to the consent request; the share form opens the re-proof dialog
and creates the link after the password is given.
2026-09-27 03:00:36 +02:00
Marc-André Bombeck dd9efb5066 test(security): escape the whole endpoint when building the proof pattern 2026-09-27 02:20:18 +02:00
Marc-André Bombeck 45bae0013c chore(release): v1.39.3 — documents from Paperless and Papra, confirmations that hold, the right day everywhere, and backups that delete what they should 2026-09-27 02:12:27 +02:00
Marc-André Bombeck ab31c9d89c fix(oura): ask for cycle phases over the user's own days, like the other collections 2026-09-27 01:01:29 +02:00
Marc-André Bombeck 3cbfe7f7f9 Merge branch 'fix/v1393-review-security' into release/v1.39.3 2026-09-27 00:59:23 +02:00
Marc-André Bombeck 9642c749c9 fix(auth): a new email address on an account with a second factor needs that factor
The address is what single sign-on links an existing account by, and
changing it took the password or a session younger than five minutes on
every account. A remembered browser skips the second factor at sign-in and
still makes a fresh session, so the password alone could move the address
of an account the second factor was meant to protect.

On an account with a second factor only a second factor or passkey
completed in the last five minutes counts now; the password is not
checked. The refusal names it (second_factor_required in rejectedFields,
or 401 profile.update.emailSecondFactorRequired when the address was all
that changed), and the profile form opens the re-proof dialog with the
factors the account holds, then saves again, no longer offering the
password field. Accounts without a second factor keep the password or a
recent sign-in. A token cannot change the address of such an account;
the app does not change it.
2026-09-27 00:59:06 +02:00
Marc-André Bombeck bd270d635a test(sharing): the invitation route's integration cases follow the recent-proof gate 2026-09-27 00:52:11 +02:00
Marc-André Bombeck 72a34b3b47 Merge branch 'fix/v1393-review-data' into release/v1.39.3 2026-09-27 00:18:47 +02:00
Marc-André Bombeck 1bf84149f8 test(integration): clear the host-wide off-host tables between tests
The purge requests and the off-host key-use ledger are not keyed to a
user, so truncating users never reached them. A file that reads them
whole, the purge job or the encryption status view, saw rows earlier
files had left and failed in a full serial run.
2026-09-27 00:17:01 +02:00
Marc-André Bombeck 357b742637 test(sharing): follow the invite form's reset through the re-proof flow 2026-09-27 00:14:32 +02:00
Marc-André Bombeck 7d05f68f23 fix(http): say when proxy headers go unread, and trust X-Real-IP only at one hop
With TRUST_PROXY_HOPS=0 behind a proxy that sends only X-Real-IP, every
client address resolves to nothing and all anonymous sign-ins share one
rate-limit bucket, with nothing in the log to say why. The first request
that carries a forwarding header the setting does not let HealthLog read
now logs one warning naming the header and the setting to change.

X-Real-IP stood in for a missing X-Forwarded-For at any hop count. It is a
single address, so it is now read only with TRUST_PROXY_HOPS=1; with two
or more hops the chain the count describes is X-Forwarded-For.

The upload, import and native batch routes that bypass the proxy now carry
Cross-Origin-Resource-Policy and Cross-Origin-Embedder-Policy like every
other response, and so do the proxy's early exits.

The env examples described an unset TRUST_PROXY_HOPS as right for a
directly exposed host; unset means one hop, and that host wants 0.
2026-09-26 22:45:51 +02:00
Marc-André Bombeck 995bd2385a fix(auth): wrong passwords from elsewhere can no longer lock the owner out
The per-account password limit refused every attempt once ten failures
had landed in fifteen minutes, counted before the password was checked.
Ten guesses from two addresses therefore locked a password-only account,
the app's password sign-in included, and repeating them kept it locked
for as long as anyone cared to.

A place the account has signed in from before is now neither counted nor
held back: a remembered browser, a phone presenting the device id a login
of this account was issued to, or an address a session or device login of
this account came from in the last thirty days. Anywhere else gets five
free failures a day and then a wait that doubles with each failure, from
thirty seconds to at most fifteen minutes, instead of a wall. The per-IP
limit is unchanged, and an unknown identifier is limited the same way on
its hash.

Under an SSO-only policy, a password sign-in to an account other than the
one a pending link names is now refused before the password is checked,
so that exception no longer tells right passwords from wrong ones.
2026-09-26 22:42:40 +02:00
Marc-André Bombeck 1900792756 fix(mcp): connecting an assistant asks for a recent sign-in or re-proof
Allowing an AI assistant hands it a standing credential to the record
that outlives the session, the same class of act as minting a token, but
the consent took a live session alone. A stolen session could connect
its own assistant and keep reading after the owner signed everything out.

The consent page now shows the Allow form only when the session signed in
or re-proved within five minutes (with the second factor on an account
that has one). Otherwise it links to a new confirm page that runs the
same re-proof dialog as the rest of the app and returns to the exact
consent request. The allow decision checks again and mints nothing
without it; deny needs no proof. The confirm page only ever returns to
the consent endpoint.
2026-09-26 22:38:40 +02:00
Marc-André Bombeck f4b9d8a0e1 fix(backup): list the purge job's awaiting-run count among its outcome facts 2026-09-26 22:35:49 +02:00
Marc-André Bombeck a294d7f684 fix(sharing): invitations need a fresh proof and end with sign out everywhere
Offering access to the record took a live session alone, and an
invitation outlives the session that sent it: whoever held a stolen
session could invite their own account and keep a way into the record
after the owner signed everything out. POST /api/account/grants now takes
the recent-proof gate at every level (a sign-in or re-proof within five
minutes on the browser, with the second factor on an account that has one;
a step-up elevation on a token, which no shipped client uses here), and
the invite form opens the re-proof dialog and sends again.

Sign out everywhere now withdraws every invitation the account offered
that nobody has accepted. Accepted grants are left standing on purpose:
each is a person the owner chose, often a carer who still needs the
record, and a sign-out button must not quietly cut them off. The response
lists them as grantsKept and the sessions card shows each with a one-click
End access.
2026-09-26 22:34:21 +02:00
Marc-André Bombeck 382c44ee88 fix(import): keep a queued Apple Health upload when sweeping staged files
The staging sweep removed any staged upload older than seven hours. An
import can wait in the queue behind another account's import for longer
than that, and when its turn came the file was gone and the import failed.
The sweep now keeps every upload a queued or running import still names,
and the extracted XML while an import is past the queue. When the queue
cannot be read, it removes nothing that tick.
2026-09-26 22:21:46 +02:00
Marc-André Bombeck a4d27c618e fix(export): every whole-record export asks for a fresh proof
GET /api/export with type=all (the default), POST /api/export/health-record
and GET /api/fhir/Patient/$everything hand over the whole record but took a
live session alone, so a stolen browser session could still walk off with
everything the full-backup gate was meant to protect. A browser session now
needs a sign-in or re-proof within five minutes, with the second factor on
an account that has one, and the doctor-report panel opens the re-proof
dialog and retries. When a manager builds the report for a record they
manage, their own session is the one asked.

On a token the shipped app keeps working: health-record and $everything
take the token as before, including a fhir:read token, and the recent-proof
guard names both. GET /api/export?type=all, which no shipped client calls
with a token, wants a step-up elevation there. Single-type exports are
unchanged.

The API reference now also describes the enrollment rule for accounts
with a second factor and the passkey refusal it adds.
2026-09-26 22:21:43 +02:00
Marc-André Bombeck 9311337997 fix(reminders): read a first-due date sent as a date as that day in the user's zone
A reminder's first-due date could only be sent as a date-time, and the
web form sent the browser's local midnight, so a browser set to a zone
other than the profile's could move the day. The API now also takes a
bare calendar date and stores it as that day's midnight in the user's
zone, and the web form sends the date itself. A date-time still means the
instant it names.
2026-09-26 22:19:49 +02:00
Marc-André Bombeck b6b51fcb5e fix(medications): let a snooze set before a dose's window hold that dose
Since a snooze holds only the slots whose window had opened when it was
set, a snooze set ahead of a dose, such as "remind me later" in the app
before the dose is due, held nothing and the reminder came anyway. A
snooze set while no window of the medication is open now holds the next
slot to open. One set while a window is open still holds only that slot,
so a morning skip that snoozes to the end of the day leaves the evening
dose reminded.
2026-09-26 22:17:14 +02:00
Marc-André Bombeck 0692017f34 fix(auth): adding a credential beside a second factor needs that factor
On an account with a second factor, TOTP setup, security-key registration
and passkey registration no longer accept the password, a password re-proof
or a session younger than five minutes. A remembered browser skips the
second factor at sign-in and still creates a fresh session, so the password
alone could add a key that then satisfies every gate the factor protected.
Only a TOTP code, a security key, a passkey or a completed second factor
within five minutes opens enrollment there; the Bearer arm of TOTP setup and
security-key registration asks the same of its elevation. Accounts without
a second factor keep the previous rules.

The refusal names the proofs the account can give, and the enrollment
dialogs offer exactly those. A proof that verifies now gives its attempt
back to the shared re-proof budget, including the current password on a
password change.
2026-09-26 22:16:44 +02:00
Marc-André Bombeck 4d3a98ed43 fix(medications): count every weekday a monthly rule names in the supply runway
FREQ=MONTHLY;BYDAY=MO means every Monday of the month, but the runway
counted it as one dose a month, so a Monday medication's supply read about
four times longer than it lasts and its low-supply notice came late. A
weekday without an ordinal now counts as every such day in the month
(yearly rules per BYMONTH month), a weekday with one (1MO, -1FR) as one
day, and BYSETPOS as the number of positions it picks.
2026-09-26 22:15:16 +02:00
Marc-André Bombeck 612eedcbbb fix(medications): warn when an as-needed medication runs low
Since the supply runway stopped counting an as-needed schedule as a daily
dose, a medication taken only as needed had no runway and never raised a
low-supply notice. It now warns once when two doses or fewer are left,
with its own line naming what is left, and re-arms after a refill like any
other medication.
2026-09-26 22:14:03 +02:00
Marc-André Bombeck 04eb8dd7f8 fix(doctor-report): compare course dates as days in the report zone
A medication's start and end dates are calendar dates, but the report
compared them against the window's instants. West of UTC the window
begins hours after UTC midnight, so a course that ended on the first day
was left out, and one that started the day after the window was listed.
Both now compare against the window's first and last day in the report
zone.
2026-09-26 22:11:27 +02:00
Marc-André Bombeck 6769f90f4c fix(rollups): step one tier finer when the coarse tier comes back empty
The granularity router read only the coarsest tier the window cleared, and
a coarse bucket that starts before the window is left out. Data that sat
only in that leading partial bucket, such as three months at the start of
a 731-day window, read as no data at all. The router now steps one tier
finer until a tier has buckets, down to DAY.
2026-09-26 22:10:45 +02:00
Marc-André Bombeck bb12d942c0 fix(backup): keep a wipe's purge request until the next off-host run
A data wipe during the nightly upload could leave the pre-wipe copy in
the bucket: the purge the wipe started removed its request at once, and
the upload still in flight checked that request after finishing and found
nothing. A wipe's request now stays until a nightly run has walked the
account since the wipe. Until then each purge removes only the copies
dated up to the wipe's day, so the copy of what the account holds after
the wipe stays, and the admin card no longer counts the waiting request
as copies still in the bucket.
2026-09-26 22:08:51 +02:00
Marc-André Bombeck e9cf3c1b15 fix: carry the cross-branch rules through offhost keys, the Telegram test mock and the OIDC reason list 2026-09-26 22:07:11 +02:00
Marc-André Bombeck 19edda66c0 fix(import): re-fold every day a CSV import touched, even when it fails
A re-import that moved a reading to another instant re-folded only the day
it moved to, so the day it left kept the reading in its rollups. And a
write chunk that failed part-way ended the request before the re-fold ran;
a retry then read the landed rows as duplicates and touched nothing, so
those days kept their pre-import rollups for good. The re-fold now covers
the old instant of a moved row and runs whether or not the writes finish.
2026-09-26 22:06:39 +02:00
Marc-André Bombeck 96b98cb719 fix(insights): compare completed days in the step-total range delta
The current half of a cumulative metric's range delta counted today's
still-growing total, so the comparison read lower every morning. Both
halves now end on the last completed day: yesterday on the user's
calendar, and never a UTC day bucket that has not ended yet.
2026-09-26 22:05:37 +02:00
Marc-André Bombeck 66b1aef40c Merge branch 'fix/encrypt-free-text-and-local-ai' into release/v1.39.3
# Conflicts:
#	src/app/api/import/csv/route.ts
2026-09-26 21:50:05 +02:00
Marc-André Bombeck 4409529c89 Merge branch 'fix/backup-rotation-and-deletion' into release/v1.39.3
# Conflicts:
#	docs/api/openapi.yaml
#	src/lib/jobs/apple-health-import-worker.ts
2026-09-26 21:48:20 +02:00
Marc-André Bombeck c86f23c2c0 fix(security): keep ALLOW_LOCAL_AI_PRIVATE_HOSTS=true for the operator's own AI, deprecated
Making `=true` grant nothing would stop a single-user self-host's local
model on a patch update. It is deprecated for one release cycle instead,
in a narrowed and safe form: it still grants a private host, but only to
the operator's own configurations (the instance-wide admin provider and
AI settings saved on an admin account), and only through the pinned
operator-approved dispatcher, so redirects stay forbidden and metadata,
link-local and unspecified addresses stay refused. A non-admin account's
own base URL needs an exact origin in AI_PRIVATE_ORIGINS.

Provider resolution passes the owning account's role to the client
(`operatorTrusted`); the save route and the connection test apply the
same rule to the account being configured. The boot summary now says the
setting is deprecated and names the replacement, and the admin AI
settings page shows the exact AI_PRIVATE_ORIGINS line for the private
origins saved on the instance (every account's Local and gateway URL and
the admin base URL, scheme, host and port only), so the operator can copy
it and drop the old setting.
2026-09-26 20:59:10 +02:00
Marc-André Bombeck 76398c80c2 test(backup): drop an import the as-stored rewrite left unused 2026-09-26 20:59:09 +02:00
Marc-André Bombeck 94aa7c6bd4 fix(backup): read nothing shorter than a ciphertext as needing a key
The shortest value either codec writes is 40 base64 characters. A
shorter string under an ...Encrypted member is not ciphertext, and
reading it as a legacy value would have made a restore demand the v1
key for a field that holds none.
2026-09-26 20:41:52 +02:00
Marc-André Bombeck 03ccb21227 Merge branch 'fix/step-up-and-session-revocation' into release/v1.39.3
# Conflicts:
#	messages/de.json
#	messages/en.json
#	messages/es.json
#	messages/fr.json
#	messages/it.json
#	messages/ko.json
#	messages/pl.json
2026-09-26 20:40:59 +02:00
Marc-André Bombeck 7da778760e fix(backup): leave the admin wipe's off-host copies in place, and correct the backup and rotation runbooks
The admin wipe of every account is the operator clearing their own host,
and the bucket's copies are the documented way back from a wipe pressed
by mistake, so it writes no off-host deletion request. Deleting an
account, deleting a managed profile and "Delete all data" still do.

The backup runbook no longer says the worker never deletes an object: it
lists the grant the worker needs (DeleteObject included), when objects
are deleted, the version-4 envelope, the lifecycle check and how to
rotate the off-host key. The rotation runbook no longer says backups are
covered: rotation reaches a backup's envelope, not the content a restore
writes back, and a retired key stays needed until no backup lists it.
The privacy notice beside account deletion says the same about off-host
copies.

A failed import records its failure in a plain try block, and the
extraction test that inflates past the 64 MiB floor gets the time it
needs on a loaded runner.
2026-09-26 20:33:30 +02:00
Marc-André Bombeck 5fd858e0af refactor(ai): define the operator-held providers once
The list of provider tags that send data out through a credential the
operator holds (admin-openai, admin-codex) existed four times: in the
consent gate, in the capability resolver, in the shared-provider health
read and in the admin provider-health ordering. A tag added to one and not
the others would be consented for in one place and not the other. The list
and the local-provider test now live in src/lib/ai/provider-egress.ts and
every reader imports them.

The guard meant to keep one copy matched a variable name, so the copy in
the resolver, under another name, never tripped it. It now matches the
list itself in either order and names the one file allowed to hold it.
2026-09-26 20:27:53 +02:00
Marc-André Bombeck 63e69e98ea fix(auth): refuse a device-bound refresh token presented without its device
A refresh token issued to a device is refused when presented under another
device id, but leaving the X-Device-Id header out skipped the comparison,
so a stolen token rotated simply by naming no device. A token whose row
carries a device id now rotates only for a caller naming that same id.
Tokens issued without one still rotate as before. The iOS app sends its
device id on every request, sign-in and refresh included.
2026-09-26 20:23:55 +02:00
Marc-André Bombeck bf63f6bdba fix(auth): claim a WebAuthn challenge in the statement that checks it
The passkey sign-in, security-key sign-in and security-key registration
verifiers read the challenge, verified the response, and deleted the
challenge afterwards. Two requests carrying the same assertion could both
read it before either deleted it, and both be accepted.

A challenge is now claimed with one guarded DELETE ... RETURNING that also
checks its ceremony, its account and its expiry, before anything is
verified; a concurrent second request finds nothing. A passkey sign-in also
refuses a challenge that was begun for a different account than the passkey
belongs to.
2026-09-26 20:22:12 +02:00
Marc-André Bombeck ece5b1d624 test(auth): give the login route tests the per-account bucket they now charge 2026-09-26 20:22:11 +02:00
Marc-André Bombeck 849748c4cd fix(backup): bind new off-host objects to their key and account, and cap what an uploaded backup may inflate to
Off-host objects are now written as envelope version 4: the header names
the off-host key by fingerprint, and the object's key in the bucket
(<date>/user-<id>.json.enc) is authenticated as GCM associated data, so
a copy moved to another account or another night no longer opens.
Objects of versions 1 to 3 still read. BACKUP_ENCRYPTION_PREVIOUS_KEYS
(comma-separated, on the compose whitelist and in the env manifest)
keeps retired off-host keys readable, which is the rotation path the
off-host key did not have.

The admin backup upload counted the bytes that arrived and none after
the gunzip, so a small gzip could expand without limit into the JSON
scanner and take the app down. The inflated bytes are now held to 100
times the compressed bytes read (at least 256 MB, at most 4 GB) and a
file past that is refused with 413 before anything is stored.
2026-09-26 20:18:55 +02:00
Marc-André Bombeck 1b4594e69f fix(import): bound what an export may inflate to, allow one import per account, and never leave the upload behind
The extractor held the inflated export.xml to a flat 8 GiB whatever the
member occupied, and the header ratio check reads sizes the archive
writes itself: a member declaring an honest ratio could inflate at
1000:1, so an 8 MB upload could fill the temp directory. The streamed
byte count is now held to 200 times the member's compressed size on
disk (never less than 64 MiB, never more than 8 GiB), and a stored
member may not grow at all.

An account may have one Apple Health import queued or running. A
second upload with different bytes is refused with 409
import.apple_health.busy and the running job's id; the check and the
new row are one transaction under an advisory lock.

The staged upload is the person's export in plain text. It is now
removed on every exit that leaves no worker to read it: a refused or
broken multipart body, no worker running, a queue that takes no job
(the row is failed as well), the admin route's missing or unknown
target account, and an account deleted before the worker reached it.
The worker removes the files before recording a failure, so a row that
went with a deleted account no longer strands them. The 15-minute
import reconcile pass also sweeps staged files older than the longest
an import may run.
2026-09-26 20:11:45 +02:00
Marc-André Bombeck ba70e19cf9 fix(logging): scrub every credential prefix the app mints
The log and error redactor missed the registration invite token (hlv_) and
the native sign-in handoff code (hlh_). The filter that keeps secrets out
of the idempotency replay cache and out of relayed upstream error bodies
missed the handoff code and the three MCP OAuth artifacts (hlac_, hlrt_,
hlc_). Both now cover every prefix the app issues: hlk_, hlr_, hls_, hle_,
hlv_, hlh_, hlac_, hlrt_ and hlc_.
2026-09-26 20:10:57 +02:00
Marc-André Bombeck d7b5fcd6c2 fix(auth): cap failed password sign-ins per account, not only per address
Password sign-in was limited per client address only, so guesses spread
over many addresses reached one account without end. Each account now has
its own ceiling of ten failed attempts in fifteen minutes, whichever
addresses they come from. The attempt is counted before the password is
hashed and given back when the password is right, so the owner signing in
does not use it up. An identifier that matches no account is counted under
its hash with the same ceiling, so the refusal does not reveal whether the
account exists. Passkey and single sign-on remain open while the ceiling
is reached.
2026-09-26 20:10:12 +02:00
Marc-André Bombeck bc69dec8e6 fix(http): trust X-Real-IP only behind a declared proxy
The client-IP resolver read X-Real-IP on every path: with
TRUST_PROXY_HOPS=0, which means no proxy in front and no forwarding header
to believe, and on the path where the X-Forwarded-For chain was shorter
than the declared hops, which means the proxies were bypassed. A caller
sending a new X-Real-IP with each request got a new per-IP rate-limit
bucket each time.

X-Real-IP now gets the trust X-Forwarded-For gets: it is read only when at
least one proxy hop is declared and the request carries no X-Forwarded-For.
A short chain resolves to no address. The reverse-proxy guide no longer
suggests TRUST_PROXY_HOPS=0 for a proxy that sets X-Real-IP; such a proxy
takes 1.
2026-09-26 20:10:12 +02:00
Marc-André Bombeck 92c5b0a60d fix(auth): end connected assistants, tokens and share links on sign-out everywhere
"Sign out everywhere" ended web sessions and device logins but left every
credential that works without signing in: a connected AI assistant kept its
OAuth connection and minted the next access token from it, a connector or
ingest token kept working, and a clinician share link kept opening the
record. A password change revoked the tokens but not the assistant's
connection or the share links. Anything a stolen session had minted
outlived the remedy.

- Sign out everywhere now ends every other sign-in, every AI-assistant
  connection, every programmatic token except the caller's own, and every
  clinician share link. Share links are revoked by default; the web offers
  a checkbox to keep them (keepShareLinks=1), and a client that sends
  nothing, such as the shipped app, gets the safe default.
- A password change and an admin password reset also end AI-assistant
  connections, share links and step-up elevations.
- Turning on the first second factor (TOTP or a security key) ends every
  other sign-in, as a password change does. Adding a further factor does
  not.

destroyOtherSessions takes an explicit reach ("sign-ins" or "everything")
so each caller says how far it goes.
2026-09-26 20:06:36 +02:00
Marc-André Bombeck 5a054d636e docs(openapi): list every OIDC error reason the native leg can receive
The login route's description named only the four reasons the login step
itself sends. The callback, which the identity provider drives and so has
no OpenAPI entry, ends the native leg at healthlog://oidc-callback with
eight more, and nothing written listed them. An app build matched against
hyphenated shorthand (identity-conflict) while the server has always sent
oidc_identity_conflict, so every SSO error fell through to the generic
message. The values do not change; the description now names the full
set, and a structural test binds it to the literals the two routes pass
to their redirect helpers in both directions.

Regenerates docs/api/openapi.yaml, including the CSV import description
from the previous commit.
2026-09-26 19:59:11 +02:00
Marc-André Bombeck 24050d84c7 fix(import): make re-importing the same CSV idempotent and fast
Re-uploading a large export with an externalId column ran one
updateMany per row inside a single interactive transaction; on a
9 000-row file that outlived Prisma's 5 s timeout and the request ended
in a 500.

A re-imported externalId row whose stored value, unit, instant, glucose
context and note already match the line is now a duplicate: not written,
reported as skipped / duplicate. Changed rows still update, a tombstoned
one is still resurrected. The existence probes run per measurement type
in chunks of 1 000 keys, and the writes commit in chunks of 200 (creates
via createManyAndReturn, updates as one batch transaction per chunk)
instead of one transaction around the whole file. A failure part-way
leaves earlier chunks written, and re-uploading the same file completes
the rest.

The OpenAPI description now says what a re-upload does, including the
natural-key dedup for rows without an externalId, which it used to call
a duplicate.
2026-09-26 19:58:50 +02:00
Marc-André Bombeck 46eb8c8b94 fix(backup): carry a not-yet-migrated title or note as stored
Sealing a readable Coach title or custom-metric note while building a
disaster-recovery file gave each export a fresh IV, so the streaming
writer and the materialising builder no longer produced the same file.
A row the free-text backfill has not reached yet now rides as stored,
readable, inside the encrypted backup; the restore seals it, and a
migrated row carries its ciphertext verbatim as before.
2026-09-26 19:58:49 +02:00
Marc-André Bombeck 1c7785c23b fix(backup): take off-host copies out with the account, and say which keys backups still need
Deleting an account, deleting a managed profile, "Delete all data" and the
admin wipe now write an off-host deletion request in the same transaction
as the deletion. A new job (offhost-backup-purge, kicked straight away and
run nightly as a backstop) lists the bucket once, deletes every
<date>/user-<id>.json.enc object of each pending account and removes the
request only when nothing of the account is left. A refused delete keeps
the request with the bucket's answer and is retried; the off-host card
shows how many deletions are outstanding and why. A copy the nightly run
was writing while the account was deleted is taken back after the upload.

The off-host card also reads the bucket's lifecycle rule and says plainly
when there is none (every nightly copy kept forever) or when the
credential may not read it.

Every stored backup now records the key ids its content was written
under, and every off-host upload records the same per key. The admin
encryption view lists, per key, the stored copies that need it with the
oldest date, and when the last off-host copy needing it expires. The
"safe to drop" badge now requires that no backup still needs a retired
key, instead of only that every row was rotated.

Migration 0358 adds data_backups.inner_key_ids, the key-use table and the
deletion requests.
2026-09-26 19:54:40 +02:00
Marc-André Bombeck 0fc83cb0a1 fix(auth): ask for a fresh proof before the record or a credential to it leaves
Exporting the whole record, making a clinician share link, minting a token,
and the admin backup download, upload and restore, data wipe and password
reset ran on a live session alone. The plaintext full backup did, while the
encrypted one beside it asked for a second factor. Whoever held a stolen
session could take the record, or leave behind a credential that outlives
the session.

These now go through one gate, requireRecentProof (assertRecentCookieProof
for the routes that resolve their caller themselves). A browser session
passes after a sign-in or re-proof within five minutes: a second factor on
an account that has one, otherwise the password or a passkey. The refusal is
401 auth.reproof.required with meta.methods, and the web opens the re-proof
dialog, posts the proof to the new POST /api/auth/reproof and retries. A
password proof stamps the new Session.reproofAt (migration 0359), never
mfaVerifiedAt, so it cannot stand in for a second factor anywhere.

On Bearer, the full backup asks for an X-Step-Up elevation; the encrypted
export asks for a second-factor elevation on an account that has one. Share
links and connector tokens keep taking the token alone, because the shipped
app calls them without an elevation and reads a 401 there as a dead
session; the guard test names them.

Key rotation keeps its stricter second-factor gate.
2026-09-26 19:54:38 +02:00
Marc-André Bombeck 1a674cf4b0 fix(security): grant private AI endpoints by exact origin, dialled pinned
ALLOW_LOCAL_AI_PRIVATE_HOSTS=true let any user of the instance point the
Local provider or the OpenAI-compatible gateway at any private address
the server could reach, the metadata range included, and a granted host
was dialled with no connect-time pin at all.

AI_PRIVATE_ORIGINS grants a private AI endpoint with the exact-origin
grammar NOTIFICATION_PRIVATE_ORIGINS and NIGHTSCOUT_PRIVATE_ORIGINS use.
A granted call goes through the pinned operator-approved dispatcher:
redirects forbidden, and metadata, link-local and unspecified answers
dropped at dial time even for a granted name. Everything else stays on
the public pin. The Local client (buffered and streaming) and the
gateway and admin-key tags of the OpenAI client all take their policy
from one function.

The host-list form of ALLOW_LOCAL_AI_PRIVATE_HOSTS keeps working with the
same pinning; a never-grantable literal or a host:port entry is refused
with a one-time warning. Its "true" form grants nothing any more and is
reported in the boot readiness summary with the replacement.

A failed lab-report scan no longer puts the endpoint's response body into
the wide event; status and model stay. The response to the caller never
carried it.
2026-09-26 19:46:11 +02:00
Marc-André Bombeck f7b3ce6ee0 fix(privacy): encrypt Coach conversation titles and custom-metric notes at rest
The title of a Coach conversation is the first 80 characters of the
opening message, and the note on a custom-metric reading is free text;
both were stored readable while every other note was encrypted.

Migration 0357 adds coach_conversations.title_encrypted and
custom_metric_entries.note_encrypted (the title loses its NOT NULL) plus
partial indexes on the backfill's discovery predicate. Every writer now
stores ciphertext only: conversation create, proactive nudge, reminder
surfacing, rename, entry create and edit, and both restore formats.
Readers prefer the ciphertext and fall back to the old column for rows
not yet migrated; a ciphertext that does not open throws instead of
falling back. The history title search decrypts in memory, since SQL can
no longer match the title.

free-text-encryption-backfill is a boot-time, idempotent pg-boss job
(staggered past the startup storm, daily discovery tick) that seals each
remaining readable value and nulls it in one transaction per row. A pass
that sees a row twice stops with an error instead of looping.

Both columns are registered for key rotation (registry, CLI script, and
the in-app rotation that walks the registry). A disaster-recovery backup
carries ciphertext only, sealing a not-yet-migrated row on the way out;
a portable export carries readable text. The old columns are marked for
removal in a later release.
2026-09-26 19:46:01 +02:00
Marc-André Bombeck 405c996b6a fix(backup): refuse a restore that needs a dropped key or reaches into another account
A backup carries every encrypted column as the stored ciphertext, and a
restore writes it back verbatim. Key rotation re-seals the stored copy's
envelope but cannot reach inside it, so a copy taken before a rotation
still needs the retired key. Without it the restore went through and
left rows no reader can open.

The restore, the restore preview, the admin upload and the monthly
restore drill now collect the key ids of every inner ciphertext value,
hold them against ENCRYPTION_KEYS and decrypt one value per key. A
missing key, or an id configured with different key material, is
refused before anything is deleted, with the key id named. The restore
status and the preview say which key to put back.

The restore also checks, inside its transaction, that it added no
reference from the account's rows to rows another account owns. The
check is derived from the schema's foreign keys rather than written per
section, so the tag and category upserts keyed on a global key are
covered along with every link table. The illness parent update is
scoped to the owner as well.

The off-host listing now follows every page: the first page held only
the oldest dates, so the drill could read an old object and report the
chain as stale.
2026-09-26 19:22:03 +02:00
Marc-André Bombeck 42d47e0877 Merge branch 'fix/auth-takeover-hardening' into release/v1.39.3
# Conflicts:
#	docs/api/openapi.yaml
#	messages/de.json
#	messages/en.json
#	messages/es.json
#	messages/fr.json
#	messages/it.json
#	messages/ko.json
#	messages/pl.json
2026-09-26 19:14:05 +02:00
Marc-André BombeckandClaude Opus 5.5 813981af63 CI: Coolify-Deploy per POST (Coolify 4.3 lehnt GET ab)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 19:13:46 +02:00
Marc-André Bombeck cc60b82d84 refactor(integrations): read the OAuth redirect URIs through the env helpers
The seven integration clients now read their redirect URI and the app URL
through envValue/envOr instead of a local ?.trim() ||. The empty-env guard
drops its pending entry and floors its walk, and proves its matcher still
fires on a real client with the old read put back.
2026-09-26 17:08:47 +02:00
Marc-André Bombeck 903f0a9a22 refactor(medications): drop the legacy today walker and its own zone solver
expandTodayIntakes had no caller left once the today projection moved onto
the recurrence engine and localHmAsUtc; it carried the last private
wall-clock solver in the medication code. The recurrence engine now takes
its offset and UTC-day helpers from the tz module instead of local copies.
2026-09-26 17:07:02 +02:00
Marc-André Bombeck d65ee42d94 test(fhir): key the adherence fixture by medication id 2026-09-26 17:03:38 +02:00
Marc-André Bombeck 314e9c1aa3 refactor(tz): take the medication and reminder trees off the zone literal
The medication and measurement-reminder code now imports DEFAULT_TIMEZONE
from the tz module like every other fallback, so the lint rule no longer
exempts those paths.
2026-09-26 17:03:19 +02:00
Marc-André Bombeck e2814336e5 Merge branch 'fix/aggregation-day-boundaries' into release/v1.39.3
# Conflicts:
#	src/app/api/medications/[id]/route.ts
2026-09-26 17:00:54 +02:00
Marc-André Bombeck 026e8fc1ed Merge branch 'fix/compose-env-and-claims' into release/v1.39.3 2026-09-26 17:00:46 +02:00
Marc-André Bombeck bd8cf5d83f Merge branch 'fix/medication-schedule-timezones' into release/v1.39.3 2026-09-26 17:00:46 +02:00
Marc-André Bombeck a8cf4c1dad Merge branch 'feat/document-picker' into release/v1.39.3 2026-09-26 17:00:45 +02:00
Marc-André Bombeck 22339aa38c Merge branch 'feat/mcp-search-records' into release/v1.39.3 2026-09-26 17:00:45 +02:00
Marc-André Bombeck 58275aee1a Merge branch 'feat/fhir-condition-body-site' into release/v1.39.3 2026-09-26 17:00:45 +02:00
Marc-André Bombeck 7860df2fba perf(rollups): fold weekly, monthly and yearly buckets from canonical days in SQL
Building the coarse buckets from the DAY tier read every day of the window
into the process: a five-year yearly read moved thousands of rows per type,
and the Coach's history bands read several such windows per request. The
per-day source pick and the fold now run in Postgres (DISTINCT ON the day,
ordered by the ladder rank and then the source name, the same order the
in-process pick uses), so a coarse read returns one row per bucket. The
long-range chart picks its tier from the span of the window's days and reads
that tier once. The Coach snapshot hands its already-loaded source order to
the history bands instead of each band reading it again.
2026-09-26 16:56:02 +02:00
Marc-André Bombeck a7f66b8519 docs(sso): explain how an existing account is linked to a provider identity 2026-09-26 16:55:03 +02:00
Marc-André Bombeck a67dfc668c fix(backups): count a multipart backup upload while it is read
The upload route is now outside the proxy matcher, so nothing bounded the
multipart parser, which holds the whole form. The bytes are counted first
and the form is parsed from what was kept, stopping at the 10 MB cap.
2026-09-26 16:54:04 +02:00
Marc-André Bombeck b10072b85e style(auth): format the re-proof and profile-update helpers 2026-09-26 16:35:42 +02:00
Marc-André Bombeck 2139b49c47 fix(http): stop reading request bodies of up to 512 MB before authentication
Next reads the body of every non-GET request the proxy matches into
memory before the route runs. The ceiling was 512 MB so the Apple Health
importer could receive whole archives, which let any anonymous POST to any
API path make the server hold that much.

The ceiling is now 1 MB (proxyClientMaxBodySize). The fifteen routes whose
real bodies are larger are left out of the proxy matcher and read their
own body after authenticating; apiHandler gives them the proxy's refusals
(worker-only, demo mode), security headers and a CSP. safeJson now counts
bytes while it reads and stops at its cap instead of reading everything
first, the CSV and dose-history imports do the same, and a multipart
backup upload is counted while it is read. A test compiles the matcher the way
Next does and checks it skips exactly the listed routes and every route
with a larger body is listed.

Local lab OCR runs its WebAssembly engine in a worker served from
/tesseract/. Those responses, and the /labs and /documents pages that start
the OCR, now carry 'wasm-unsafe-eval' in script-src; no other route does.
2026-09-26 16:31:03 +02:00
Marc-André Bombeck ff4aa32f6d fix(doctor-report): keep a report with a past end date inside its dates
A report whose end date lies in the past listed medications that started
after it, the dose history up to today and the latest injection even when it
came later. It now lists a medication only if its course had begun by the
end date (or it had a dose scheduled inside the window) and had not ended
before the start, and dose history and the last injection stop at the end
date.
2026-09-26 16:25:45 +02:00
Marc-André Bombeck 9d2fd1db14 fix(tz): one default zone, and the user's own calendar where Berlin was hard-coded
The status assessments folded their recent days, weeks, months and years on
Berlin days whatever the user's zone, the mood and cycle crosstabs keyed
their metric days in Berlin, the resting-pulse proxy defaulted to Berlin
days, the briefing's opener rotated at Berlin midnight, and every
assessment prompt labelled today's date as Berlin's. They now use the
user's zone. Rollup months and years are labelled by their UTC start,
which is how they are cut; read in a zone west of UTC the label named the
month before.

"Europe/Berlin" was written out in some eighty places. DEFAULT_TIMEZONE in
lib/tz/format is now the one definition: the second copy in mood/date-key,
DISPLAY_TIMEZONE, the Berlin-only day key helpers and the per-route copies
are gone. An in-repo lint rule rejects the literal outside lib/tz and
tests; four areas another change owns are listed as pending.
2026-09-26 16:23:14 +02:00
Marc-André Bombeck 6819ce70c6 fix(ops): read an empty TRUST_PROXY_HOPS as unset
The shipped compose file passes TRUST_PROXY_HOPS as an empty string when
the operator never set it, and the parser rejected the empty string as an
invalid value, throwing wherever the client address was read. Empty now
means the default of one trusted hop.
2026-09-26 16:17:16 +02:00
Marc-André Bombeck 8da7583ec6 fix(auth): link single sign-on to an existing account only after its own sign-in
The SSO callback bound a verified provider email to the local account with
the same address on the spot. The local address is not verified: anyone
could register with it, or type it into their profile, and the SSO user
then landed in an account the other person still held the password to.

The callback now links nothing. It records the link it would make in a
sealed, ten-minute, HttpOnly cookie and sends the browser to the sign-in
page, and the link is made only when that browser then signs in to that
same account with its password (and second factor) or passkey. Under an
SSO-only policy the password form opens for exactly that account. The
native sign-in answers oidc_link_required; the link is confirmed once on
the web.

Moving an account to a new email address now also needs a fresh proof: a
sign-in or second factor in the last five minutes, or the current password
sent alongside the change. Without it the address is left as it was and
reported in rejectedFields; the rest of the save still lands.
2026-09-26 16:10:32 +02:00
Marc-André Bombeck c366d4946c fix(integrations): treat an empty redirect URI variable as unset
The compose file passes every whitelisted variable through, so an unset
redirect URI reaches the process as an empty string. Withings then sent
redirect_uri= to the provider, and Fitbit and Google Health refused to start
the connection as not configured although NEXT_PUBLIC_APP_URL was set. Every
integration now treats an empty or blank value as unset and derives the
callback from the app URL.
2026-09-26 16:08:57 +02:00
Marc-André Bombeck c88754a0b5 fix(measurements): re-warm status assessments from every measurement write
The MCP writes, the Telegram reply, the CSV and backup importers and the
Apple export import refreshed the rollups by hand and never re-warmed the
cached status assessments, so a reading logged there kept the day's old
assessment until the nightly pass. They now run the shared post-write tail,
and the export import re-warms every type it wrote. The WHOOP body sync
removed its legacy weight row without refolding that day; it does now.

A structural test lists every file that writes measurements and how it keeps
both readers current, so a new write site fails until it says.
2026-09-26 16:07:51 +02:00
Marc-André Bombeck 4e7beb797c fix(analytics): all-time extremes and range deltas count one source per day
The all-time weight, blood-pressure and pulse figures the insight features
carry averaged every raw row, so a device that samples densely outweighed the
readings the source ladder prefers on the same days. They now keep one source
per day, like the dashboard's all-time figures.

The period-over-period range delta averaged readings. For step-like totals
the current window still holds the last day and a half as many small
samples, so the average collapsed; it now compares average daily totals. For
sleep it averaged stage segments and in-bed envelopes; it now compares
average nights of time asleep. The API descriptions say which.
2026-09-26 16:07:45 +02:00
Marc-André Bombeck b2bb81cac3 fix(apple-health): keep one source per device across an OS update in the export import
The export importer keeps the largest source subtotal per day for step-like
totals, and it told sources apart by name, version and device. On the day a
phone or watch updates, its records carry two versions, so the one device
became two sources and the day kept only the larger half. The identity is
now the source and its device without any version.
2026-09-26 15:59:07 +02:00
Marc-André Bombeck 34f847f12f fix(integrations): anchor synced daily totals at local noon in the user's zone
Withings, Fitbit, Google Health, Polar and Oura wrote each daily total and
daily summary at noon UTC of its date. From UTC+12 on (New Zealand all year,
Fiji, Tonga, Samoa) noon UTC is already the next local day, so every synced
step count, SpO2 or resting-pulse day showed up a day late. The rows now sit
at local noon of their date in the user's zone, and the fetch windows run
through the user's own today.

Fitbit weigh-ins carry a local wall clock without an offset and were read
as UTC; they are read in the user's zone now.

ExternalIds stay on the calendar date, so the next sync finds each row and
moves it in place instead of adding a second one, and the day a row leaves
is refolded. Rows inside each integration's re-read window heal on the next
sync; Fitbit and Google Health re-read the whole history on reconnect.
2026-09-26 15:58:02 +02:00
Marc-André Bombeck 7b5bc130d8 fix(auth): require a fresh proof before a second factor is added
A browser session on its own could start TOTP enrollment or register a
security key. Combined with a pending secret counting as a factor, that let
a stolen session give itself a second factor, register a passkey with it,
and keep access after the owner changed the password.

TOTP setup and security-key registration now pass on the cookie path only
when the session signed in or completed a second factor in the last five
minutes, or when the body carries a proof in the step-up shape (password,
a confirmed authenticator code, or a passkey or security-key assertion).
The settings cards ask for that proof when the server answers
auth.reproof.required and retry the same call with it. The Bearer path is
unchanged: its elevation already is the proof.

Every route that checks a password or a factor as a re-proof now uses one
verifier and one per-account budget of five attempts per fifteen minutes,
shared with the step-up mint, and records each refused proof as
auth.mfa.failed. Passkey enrollment and password change had neither the
limit (passkey enrollment) nor the audit row (both). A structural test
freezes the set of credential-verifying routes and requires a throttle and
an audit call in each.
2026-09-26 15:55:57 +02:00
Marc-André Bombeck bbf6a0aeb9 build: name the OCR language packages literally in the staging script 2026-09-26 15:45:28 +02:00
Marc-André Bombeck 6a422542f1 fix(digest): decide a milestone's day on the user's calendar
Today's key, each new record's day and the streak series were UTC days, so
through a New York evening a best set that afternoon counted as yesterday's
and dropped out of the digest. All three are now the user's own days; the
streak series is folded live on local days for this read.
2026-09-26 15:44:25 +02:00
Marc-André Bombeck a1d94a33ed fix(charts): end the mood and intake heatmaps on the user's today
Both heatmaps stepped back from now in 24-hour strides and cut each key in
UTC, so in the evening west of UTC, or the morning east of it, the newest
cell was a different day from the one the server keyed the readings on. The
days now come from today's key in the user's display zone, stepped on keys.
2026-09-26 15:44:24 +02:00
Marc-André Bombeck 24ef378e93 chore(lint): skip the staged OCR engine files 2026-09-26 15:43:06 +02:00
Marc-André Bombeck 73e0653b2c fix(tz): one start-of-day for every zone, including skipped midnights
Local day bounds had three implementations. The day-key one read the zone
offset at UTC midnight, which on a transition day in zones far from UTC
(Pacific/Auckland, Australia/Sydney) is the offset after the change, so the
day started an hour off. The instant one converged on local 00:00, which in
zones that skip midnight (America/Santiago, America/Havana) does not exist,
and returned 23:00 of the previous day.

startOfLocalDayKey and localDayWindow in lib/tz/local-day are now the only
implementation: the first instant that reads the day, tried under every
offset in force around it. A skipped wall clock resolves to the moment the
clocks jump, the day-keyed copies in the measurement drains, the compliance
rollups and the dashboard batch window are gone, and the noon and mid-hour
anchors use the same converge.
2026-09-26 15:41:16 +02:00
Marc-André Bombeck 62cef974bf fix(medications): scope a snooze to its slot and key report adherence by id
A snooze lives on the medication row, and the reminder tick applied it to
every slot of that medication. A Telegram "skip" of the morning dose
snoozes to the end of the day, so the evening dose of the same medication
was neither reminded nor marked missed by the reminder path. A snooze now
holds only slots whose reminder window had opened when it was set, dated by
the row's updatedAt that the snooze write stamps (the same reading the skip
and pin suppression already uses). A later edit to the row can only widen
the hold back to the old behaviour.

The doctor report kept adherence in a map keyed by medication name, so two
medications with the same name (an ended course and a new one, two
strengths) collapsed into one row and the second overwrote the first. The
map is keyed by medication id now and carries the name as the label; the
report's medication list carries the id. The PDF, the FHIR adherence
observations, the MCP visit summary, the clinician view and the GLP-1
section read it that way.
2026-09-26 15:38:20 +02:00
Marc-André Bombeck 95f8d7144a docs(api): regenerate the contract for the update-check switch 2026-09-26 15:37:33 +02:00
Marc-André Bombeck e1e664be46 fix(health-score): leave today's partial step total out of the activity pillar
The activity pillar averaged the 28 days ending today, so any score computed
during the day counted a step total that was still growing and pulled the
average down. The window is now the 28 completed local days ending
yesterday, cut on day keys.
2026-09-26 15:37:25 +02:00
Marc-André Bombeck 148d6c035f fix(dashboard): count the logging streak on local day keys
The streak walked back from UTC midnight of today's key and read each
instant in the user's zone. West of UTC that instant is still yesterday, so
the walk started a day early and the streak came out one day short. It now
steps through the day keys themselves.
2026-09-26 15:37:25 +02:00
Marc-André Bombeck 35f7741006 fix(analytics): all-time and year-ago averages from one source per day
Rows older than the five-year rollup window were added to the all-time
figures without choosing a source per day, so a vital recorded by two
devices counted both on every one of those days. They now keep the
ladder-canonical source per day, like the rollup half and the live path.

The year-ago 30-day average read the monthly tier and kept whichever month
began inside the window, which could be a month off or leave the value
empty. It is now the count-weighted mean over exactly the 30 days that start
395 days ago.
2026-09-26 15:37:17 +02:00
Marc-André Bombeck 2c88acc5f7 fix(labs): serve the in-browser OCR engine from this origin
Local lab OCR reads a report photo on the device with tesseract.js, whose
defaults load the worker, the WebAssembly core and the language data
from cdn.jsdelivr.net. The production CSP allows workers and fetches only
from this origin, so the engine could not load; where it did load (dev),
the browser of anyone scanning a report contacted a third-party CDN.

The worker, the three LSTM core builds and the deu and eng best_int
language data (about 17 MB) are now copied from pinned packages into
public/tesseract/ at prebuild and predev, and createWorker is pointed at
them with the worker started from its URL rather than a blob. A test
holds the options against the staged file list.
2026-09-26 15:37:13 +02:00
Marc-André Bombeck d51ba9f134 fix(rollups): choose the canonical source per day inside weekly, monthly and yearly buckets
The rollup writer keeps one row per bucket and source. Collapsing the stored
WEEK / MONTH / YEAR rows picked one source for the whole bucket, so a month
of manual blood-pressure readings plus one synced reading reported the synced
day alone, and a step month that switched devices lost every day the losing
device carried. The live weekly and monthly chart fold made the same pick.

Every coarse bucket is now folded from the canonical DAY buckets: the source
ladder picks one source per day, then the week, month or year counts every
one of its days. Spread, slope and r² are composed from the summed day
accumulators. The live fold picks per local day before folding into weeks
and months. Ties between sources without a ladder rank break alphabetically
on the SQL paths too, matching the rollup reader.
2026-09-26 15:37:10 +02:00
Marc-André Bombeck 94ac863bdf docs: describe encryption scope, PDF rendering and backups as they are
The README said everything is kept encrypted at rest, that allergies and
family history are encrypted records, that the doctor report is
generated client-side, that there is no telemetry of any kind, and that
S3 backups are switched on in the admin panel. Free text, documents,
questionnaire answers, AI-written text and credentials are encrypted;
measurement values, lab values, medication names, mood scores and the
allergy substance or family condition are not. The PDF is rendered on
the server. Off-host backups are configured through the BACKUP_*
variables, and the admin panel only shows their status. The server's own
outbound requests are named along with their switches.

.env.example now says it is a starter and points at
.env.production.example as the complete reference, which is the file CI
checks against the env manifest. The Withings client id and secret it
listed are not read from the environment at all; they are entered in
Settings.
2026-09-26 15:34:12 +02:00
Marc-André Bombeck afcb37e76c feat(config): let the operator turn off the breach and update checks
Two requests left the server without anything being connected: the
HaveIBeenPwned range query on every password set (registration, change,
admin reset) and the daily GitHub releases request behind the About page
and the admin version tile. Neither could be turned off, which made
"nothing leaves" untrue for an instance that wanted it to be.

PASSWORD_BREACH_CHECK_DISABLED and UPDATE_CHECK_DISABLED (1, true, yes or
on) stop each request. Both stay on by default. The breach check keeps
its fail-open contract: switched off, a password is simply not looked up.
The update route answers status "unknown" with reason "disabled" and
the admin tile says the check is off. The password routes reach the
check only through the switch, and a test holds that import line.

Both are on the compose whitelist, in the env manifest under a new
"Outbound requests" group with IP_GEO_LOOKUP_DISABLED, and documented in
both env examples and the getting-started guide.
2026-09-26 15:33:34 +02:00
Marc-André Bombeck 91571d4674 fix(medications): count the whole cadence in the supply runway
The runway estimate read FREQ=MONTHLY as one dose every 30 days whatever
its INTERVAL, so a quarterly injection with two doses left showed about 60
days of supply instead of 180. FREQ=DAILY;INTERVAL=2 counted as daily, a
yearly rule ignored INTERVAL and BYMONTH, and a monthly rule ignored extra
BYMONTHDAY values. A CYCLIC schedule was counted as if it never paused,
and a PRN schedule as if it were due every day. The rate now honours
INTERVAL for every frequency, counts the listed days and months, scales a
cyclic schedule by on / (on + off) and leaves PRN out. The low-stock job
selects the schedule type and cycle lengths so it reads the same rate.

Whole-dose counts no longer lose one to binary floating point: 2.4 mL at
0.8 mL per dose is 2.9999999999999996 in IEEE 754 and used to read as two
doses. The stock summary, both runway estimators, the list and detail
routes, the GLP-1 route, the Coach snapshot and the inventory readout now
floor through one helper that treats anything within 1e-9 of the next whole
number as that number.
2026-09-26 15:32:29 +02:00
Marc-André Bombeck 228c5c9da6 fix(copy): say what the AI provider receives and what is encrypted
The "Send raw data" switch promised anonymised single readings from the
last 30 days. It sends bucket averages from the rollup table: per day for
the last 90 days, per week for the year before, per month back to five
years, each with its date and reading count. The label, both
descriptions and the warning now say that, and the "off" text no longer
claims the summaries carry no individual value (they include the latest
one).

The data-posture line and the Coach's own description of the app said
all health data is encrypted at rest and nothing leaves the instance
beyond the AI provider. Free text, documents, questionnaire answers,
AI-written text and tokens are encrypted; measurement values, lab
values, medication names and mood scores are not. Both now say so, and
the Coach is told not to claim otherwise. Two narrower absolutes are
scoped to what they cover: the local-model onboarding title and the
off-host backup card.

All seven locales.
2026-09-26 15:30:30 +02:00
Marc-André Bombeck 888b738546 fix(reminders): send a multi-hour protocol at every hour it names
A reminder with FREQ=DAILY;BYHOUR=7,19 (the morning-and-evening blood
pressure course) was only ever sent in the morning. The tick opened its
send window at notifyHour alone, so the 19:00 slot stayed due until 07:00
the next day, and the claim was keyed per local day, so a second send that
day would have been refused anyway.

The window is now the hour of the current slot: the local hour of
nextDueAt when it is one of the rule's BYHOUR values, else notifyHour. The
early skip for a reminder already sent for its slot uses the same hour, so
it stays consistent with the hold-open rule and lastNotifiedAt. A
multi-hour reminder claims per slot hour; a single-hour reminder keeps the
per-day key.
2026-09-26 15:27:25 +02:00
Marc-André Bombeck 13db7935f6 fix(image): ship the operator scripts the runbooks run in the container
The password-reset runbook tells an operator to run
`docker compose exec app node scripts/reset-password.mjs`, and the
intake-repair runbook runs `healthlog-tsx scripts/repair-intake-anomalies.ts`
inside the container. The runner stage copied nothing from scripts/, so
both failed with "Cannot find module", the reset at the moment an admin
is locked out.

The runner stage now copies both scripts and the Argon2 parameter module
the reset imports, and proves at build time that each reaches its own
first check with every import resolved. A structural test holds every
in-container command in docs/ and the Dockerfile copies in step.

Key rotation is documented the way it works on the published image: the
Rotate now button under Admin > Encryption is the primary path. The
rotation script imports the application graph and runs from a source
checkout of the same release; the runbook, the admin hint in all seven
languages and the decrypt error now say so.
2026-09-26 15:26:03 +02:00
Marc-André Bombeck 8a03654e8f fix(medications): read schedule days as calendar days, not in the user's zone
A medication's startsOn/endsOn are calendar dates stored as UTC midnight,
and the rrule library emits its day anchors the same way. The engine read
those midnights on the user's wall clock, which west of UTC is the evening
before. A FREQ=WEEKLY;BYDAY=MO plan therefore fired on Sundays in New York,
a daily course starting on the 14th produced a dose on the 13th, and an
evening dose on the last course day was cut off. One-shot doses, the first
dose of a rolling cadence and the legacy weekday walk (startsOn floor,
endsOn cap, every-N-weeks phase) carried the same shift.

The engine now keeps a calendar day as a calendar day end to end: startsOn
and rrule anchors are read from their UTC fields, instants (createdAt,
intake times) are converted to the local day they fall on, and only then is
the HH:mm materialised in the user's zone. Rolling cadences count calendar
days from the local day of the last intake, so a late-evening dose across a
DST change no longer slides a day. A nonexistent local time now always
moves forward, including in zones whose clocks skip midnight. RRULE anchors
with BYHOUR are collapsed per day so a twice-daily protocol cannot emit
duplicate slots.

CYCLIC on/off weeks are counted as seven-day blocks from the start day in
the local calendar. They used to snap to Sunday-rooted UTC weeks, so a
three-weeks-on course starting on a Wednesday lost its first days and the
off week began on the wrong day east and west of UTC.

Measurement reminders pass their anchor and course end as instants; the
adapter now converts them to the user's calendar day before handing them to
the engine.
2026-09-26 15:25:08 +02:00
Marc-André Bombeck e1718e3c30 fix(auth): count a second-factor attempt before verifying it
The login challenge read its attempt count, verified the factor, and only
then incremented. Requests sent in parallel all read the same count below
the cap, so one ticket allowed more guesses than the cap. Each attempt is
now reserved by a single guarded UPDATE before the factor is evaluated,
and a failure only settles the reserved attempt.
2026-09-26 15:21:42 +02:00
Marc-André Bombeck 3c3e5ceab7 fix(config): treat an empty environment variable as unset
docker-compose.yml forwards its whitelist as "${NAME:-}", so a variable
the operator never set reaches the process as the empty string. Reads
written as a nullish fallback kept that string: the weather client built
an empty base URL and every geocode failed with ERR_INVALID_URL, and the
IP geo lookup requested a relative path.

Reads with a fallback now go through src/lib/env.ts (envValue, envOr,
envFlag), which treats empty and whitespace as unset. IP_GEO_LOOKUP_DISABLED
accepts 1, true, yes and on instead of only "1". A structural test refuses
a ?? fallback written directly against process.env anywhere in src/, and
the compose whitelist guard counts the helper's call shape as a read.
2026-09-26 15:20:42 +02:00
Marc-André Bombeck 8cb958bf27 fix(auth): accept a TOTP code only from a confirmed secret
A pending secret from an enrollment that was never confirmed counted as a
second factor wherever a code was verified: step-up minting, the passkey
enrollment re-proof, MFA disable and login completion. Anyone holding a
session can create a pending secret, so a code from one proves nothing
about the account owner. verifyMfaFactor now refuses both TOTP and
recovery codes until totpConfirmedAt is set.
2026-09-26 15:19:26 +02:00
Marc-André Bombeck 656542b040 fix(documents): date Papra search rows by their document date only
Papra's date: filter matches the document date, so a row now shows that
date or none, and an undated document falls out of a date range in the
list as it does on the server. Import still files an undated document
under the day it was added.
2026-09-26 15:15:32 +02:00
Marc-André Bombeck bb5d0ab933 docs(documents): Papra organization ids and tags permission, deletion by content, the Paperless SQLite case limit 2026-09-26 14:47:40 +02:00
Marc-André Bombeck d69e12bac2 fix(scripts): skip documents the source already says are too large once HealthLog has named its limit, and show small sizes in KB 2026-09-26 14:47:12 +02:00
Marc-André Bombeck 057281998f fix(documents): read Papra as it answers
Papra organization ids are checked against org_ plus 24 characters
before anything is sent. A 403 user.not_in_organization and a 400
server.invalid_request.params read as no such organization instead of a
refused key; the error body is read for its code and never passed on.
The connection test also reads the tags, so a key without tags:read
fails at save (permissionMissing) instead of on the first filter. Name
searches quote each word, so a leading dash is not a negation, and the
date range goes to Papra as date:>= / date:<= with the per-row check
kept as a net.
2026-09-26 14:46:01 +02:00
Marc-André Bombeck c5a63934bd fix(documents): an import of bytes deleted in HealthLog stays deleted under any source key
Keyed uploads and picker imports also check deleted, not yet purged
documents by content and answer deleted, remembering the new key on the
tombstone so the purge carries it into the ledger. A hand upload without
a key still stores a new copy. No content hash of a deleted document is
kept past the purge.
2026-09-26 14:42:13 +02:00
Marc-André Bombeck 933553a7bd docs(documents): source instance in the workflow recipe and the key rules; token and removal rules for the picker 2026-09-26 14:33:23 +02:00
Marc-André Bombeck 6534c3f9e8 fix(documents): picker and settings card follow-ups
The settings card stays visible, read-only, while a connection is
stored but the operator list is gone or Documents is off, so the token
can still be removed; a new address asks for the token again. The
picker clears a selection when the search or a filter changes, says
when the 25-document limit is reached, steps back the rows a finished
run did not touch and offers Pick more, shows an empty state, and
announces each row's result to screen readers. Both system switches
are radio groups with one tab stop and arrow-key movement. Strings in
all seven languages.
2026-09-26 14:32:46 +02:00
Marc-André Bombeck 6a751bc51d docs(api): publish sourceInstance on the upload and lookup routes, and the picker's review changes 2026-09-26 14:28:46 +02:00
Marc-André Bombeck 1eac05b454 fix(documents): key imports by source instance, keep a token on its origin, and harden the import path
- Source keys carry the normalised origin of the Paperless-ngx or Papra
  they came from (source_instance on the document, the alias and the
  purge ledger; unique NULLS NOT DISTINCT). A key stored without one
  (v1.39.2 imports) matches any instance of its system, and a lookup
  without one matches any stored instance. The upload route, the lookup
  route and the import script accept or send it; backups carry it.
- Saving a connection reuses the stored token only for the same origin;
  a new origin needs the token again (422 tokenRequired).
- Document ids are checked against what each system issues (Paperless
  digits, Papra [A-Za-z0-9_-], never . or ..) before any URL is built;
  the Papra organization id likewise.
- Paperless API 9 filters dates on created__gte / created__lte, in the
  picker and the script. A search page the local re-check empties reads
  on, up to five source pages. Tags are read past the first 250.
- The import's key pre-check uses the lookup allowance, a failed fetch
  no longer charges the upload allowance, and one import per key runs at
  a time under an advisory lock, so a double click downloads once.
- Reading and deleting one's own connection works with the documents
  module off and the operator list unset.
2026-09-26 14:20:17 +02:00
Marc-André Bombeck 0a58edc87a fix(fhir): code the mean glucose only when it is a continuous-stream mean
97507-8 is the mean of interstitial glucose in mass/volume. A spot-reading
mean is neither, so it now goes out text-only in the account's unit. A
continuous-stream mean keeps the code and is sent in mg/dL, the unit it is
computed in, whatever unit the account displays.
2026-09-26 13:55:41 +02:00
Marc-André Bombeck 6029c7c30d fix(documents): keep a picker row at full contrast once it shows its import result; two date fields per row on phones 2026-09-26 13:45:15 +02:00
Marc-André Bombeck 0ac5377cc2 fix(fhir): correct the LOINC and SNOMED CT terms the export sends
A run of the HL7 validator against every code the export can emit found
terms that do not exist, are inactive, mean something else, or carry a
display the code system does not publish.

- Body water and bone mass use 101683-1 and 101685-6; the old codes are a
  nasogastric fluid output and a calculated body-fat mass.
- Step length, walking speed, walking asymmetry and VO2 max ride their
  HealthKit identifiers: LOINC has no fitting term, and two of the old
  codes do not exist.
- Mood, estimated A1C, average cycle length and average period length are
  text-only. The old codes did not exist or were questionnaire items.
- LDL, vitamin D and eGFR use the method-less and total terms (2089-1,
  62292-8, 69405-9) a recorded value can honestly claim.
- Resting heart rate and pulse-oximetry SpO2 also carry the heart-rate and
  oxygen-saturation codes the R4 vital-signs profiles require.
- Blood pressure, adherence, glucose-panel and injection-site codings carry
  the published displays; ATC codings carry none, since the user's
  medication name is not the ATC name. The name stays on the text.
- Mood is a survey finding, not a vital sign, so it no longer rides the
  vital-signs panel.
2026-09-26 13:44:10 +02:00
Marc-André Bombeck 44abc6f1a0 fix(fhir): code allergy and injury conditions with active SNOMED CT concepts
Allergy used 106190000, inactive since 2013; it is now 473011001 Allergic
condition. Injury keeps 417163006 with the display SNOMED CT publishes,
Traumatic or non-traumatic injury; the old display was rejected.
2026-09-26 13:44:09 +02:00
Marc-André Bombeck 1e54f291a7 docs(mcp): notes, held-back documents and module switches across every read 2026-09-26 13:39:11 +02:00
Marc-André Bombeck 9e38ee3a99 fix(documents): report picker and card results through the shared outcome line, and register the disconnect as a destructive control 2026-09-26 13:32:52 +02:00
Marc-André Bombeck 35327b84c1 fix(fhir): leave out the vital-signs DiagnosticReport when there are no vital signs
A window without a vital sign emitted the panel with result: [], which R4
rejects. The DiagnosticReport now goes out only when it has a result, and
the vital-signs section drops an empty entry list rather than sending one.
2026-09-26 13:31:38 +02:00
Marc-André Bombeck 87526e3df6 fix(fhir): code the body-site side with active SNOMED CT qualifiers
The HL7 validator reports 419161000 and 419465000, the left and right
concepts of the R4 bodysite-laterality value set, as inactive. Use the
active qualifier values 7771000 Left and 24028007 Right, with 51440002
Right and left. The side word in bodySite.text stays English, the language
of every other generated text in the Bundle; the builder takes no locale.
2026-09-26 13:29:45 +02:00
Marc-André Bombeck 9b8c5ab44c test(mcp): notes and held-back document text stay off the wire against real Postgres 2026-09-26 13:29:36 +02:00
Marc-André Bombeck 836f72605f fix(mcp): keep notes and held-back document text off the wire, gate every read
Follow-ups to the clinical-record search, test first:

- Condition and vaccination notes are no longer searched or returned.
  Both reads use an explicit column list without the note, as the Coach
  illness snapshot and the doctor report already do. A structural guard
  fails when any MCP read of either model names noteEncrypted or has no
  explicit select.
- A document uploaded with AI reading deferred is not searched by its
  text and returns no excerpt (metadata.reason "ai_read_deferred"); its
  title, kind and links stay findable.
- Documents older than the newest 500 are found by title and file name
  through a bounded SQL lookup on those plaintext columns.
- Query words shorter than four letters match whole words or word starts
  only, so "arm" no longer finds "Darm".
- A deleted practitioner is no longer named or matched, in search, fetch,
  get_visits and the appointments in get_preventive_care. The empty-query
  listing shows visits that happened, not booked ones.
- get_labs, get_medication_schedule, get_medication_compliance and the
  lab and medication resources (read, list, completion) answer
  { present: false, reason: "module_disabled" } when their module is off,
  without reading. get_visits withholds condition labels when illness is
  off and says so in conditionsReason.
- The consent screen and the tool descriptions name what a connection
  can read, the indexed text of stored documents included.
2026-09-26 13:26:55 +02:00
Marc-André Bombeck d109d67889 feat(documents): pick documents from Paperless-ngx or Papra in the vault and wherever documents are linked
A settings card under Integrations connects either system and tests it
before saving. An import button beside Upload in Documents, on a
condition's documents card, and beside Add in the visit and vaccination
document pickers opens a sheet that searches by name with tag and date
filters, shows what HealthLog already holds, and imports the ticked
documents one at a time with a result per row. The buttons appear only
for a person in their own record with a connection; strings in all
seven languages.
2026-09-26 13:26:18 +02:00
Marc-André Bombeck 92f2cc729f fix(documents): name the document-AI capability in each route that can queue it, and catalogue the picker's error codes
The ingest path takes the capability from its caller, so the upload and
the import route each read getAiCapability("documentAi") in their own
source, where the AI route inventory classifies them.
2026-09-26 13:18:48 +02:00
Marc-André Bombeck caf3eb323d docs(api): publish the document picker routes as cookie-only, and freeze them as owner-only 2026-09-26 13:13:51 +02:00
Marc-André Bombeck c840d1012a test(documents): exercise the picker's routes against the database with the source faked at the fetch layer 2026-09-26 13:07:44 +02:00
Marc-André Bombeck cab67b4c06 test(documents): pin the picker's origin allowlist and both source adapters 2026-09-26 13:03:45 +02:00
Marc-André Bombeck fdc60f69c2 feat(documents): search and import from Paperless-ngx and Papra on request
A person stores one connection per system (base address, Papra
organization id, API token encrypted at rest) and can search it by
document name with tag and date filters, then import picked documents
one per request through the same ingest path as an upload: source-key
answer before any download, content dedup, deleted stays deleted, quota,
provenance, and the person's own AI reading setting. An import can link
the document to the visit, condition or vaccination it was picked for.

The operator lists the instances in DOCUMENT_SOURCE_ORIGINS; unset, the
feature is off. Only listed origins are contacted, through safeFetch with
the origin pinned, redirects refused, timeouts and byte caps. The routes
are cookie-only and owner-only. The token is registered for rotation,
removed by Delete all data, and not carried in backups.
2026-09-26 13:02:36 +02:00
Marc-André Bombeck 639a30e133 docs(mcp): describe what search and fetch cover for clinical records 2026-09-26 13:02:05 +02:00
Marc-André Bombeck 1dbab4a912 test(mcp): search and fetch over clinical records against real Postgres 2026-09-26 12:59:31 +02:00
Marc-André Bombeck 5d80b194ac feat(mcp): search and fetch cover visits, conditions, documents and vaccinations
In its default mode ChatGPT can call only search and fetch, and until now
those two covered metric domains, medications and lab analytes. A question
about a knee operation or a discharge letter had nothing to land on.

search now also returns visit:<id> (procedures included), condition:<id>,
document:<id> and vaccination:<id>. Matching runs after the decrypt over
the account's own rows, bounded per kind, folded the way the body-sites
view folds sites, with German/English body-part and vault synonyms.
Documents match on title, file name, kind and whole words of the blind
content index; the body is never read for a search. Results rank by
matched query words, then score, kind, date and id, so the offset cursor
stays stable. Record results are capped at 50.

fetch returns each record's key fields and its one-hop links through the
link service, every link carrying an id fetch accepts. Free text is fenced;
short labels are scrubbed. A document returns metadata and at most a
1500-character excerpt of its indexed text, never the file or its stored
summary.

A switched-off module's records are neither read nor returned: illness,
inboundDocuments and vaccinations for the new kinds, and now medications,
labs and the owning module of a discovery signal for the older ones.
2026-09-26 12:55:28 +02:00
Marc-André Bombeck 89b18e001e refactor(documents): move the upload's store path into one ingest function
The upload route keeps authentication, its rate buckets, multipart parsing
and the response shape; the source-key answer, size and type checks,
pre-link narrowing, content-hash dedup with alias memory, the quota-gated
insert, the audit row and the background jobs move to
src/lib/documents/ingest.ts unchanged, so a second way in can store
through the same rules.
2026-09-26 12:53:32 +02:00
Marc-André Bombeck 8934a2900e feat(fhir): export the body site and side of a condition
Condition.bodySite carries the free-text site as text. The side rides a
contained BodyStructure reached through the core bodySite extension, coded
with the SNOMED CT concepts of the R4 bodysite-laterality value set, and is
repeated in the text so a receiver that ignores extensions still reads it.
2026-09-26 12:45:15 +02:00
Marc-André Bombeck 4af6b87a2a Merge pull request #1039 from MBombeck/release/v1.39.2
Release v1.39.2
2026-09-26 11:57:44 +02:00
Marc-André Bombeck cec7fd2b9c test(e2e): tamper with a piece of the stored backup, now that copies are kept in pieces 2026-09-26 11:40:50 +02:00
Marc-André Bombeck bd75c851f1 chore(release): v1.39.2 — document import, body sites, check-ups that stay due, and backups that fit in 1 GB 2026-09-26 11:25:03 +02:00
Marc-André Bombeck 226baa8636 Merge branch 'fix/checkup-stays-due' into release/v1.39.2 2026-09-26 10:48:00 +02:00
Marc-André Bombeck f3df0023b2 fix(migrations): tighten and widen the 0355 repair where the evidence allows
A snooze that had already run out before the send is history, not a
choice about the reminded slot, so it no longer keeps a row from being
repaired. The "no due date" arm matched nothing, because a reminder
cannot be created without a cadence; it now covers a rule whose last
occurrence was the one sent, which is open unless it was done or
skipped since, while a course whose window closed before the send stays
closed through the end-date guard. The start-page step reads a stored
item list only when it is a list, so a malformed layout can no longer
fail the migration.
2026-09-26 10:41:02 +02:00
Marc-André Bombeck 7aefde67e2 fix(reminders): an edit that does not change the cycle keeps the open slot
Renaming an overdue booster check-up on the web still moved it to next
year. The edit sheet sends the first due date as the browser's local
midnight on every save, a booster row stores the dose instant plus N
days, and the route read the different instant as a new first due date.

The route now compares the first due date by calendar day in the
profile timezone and drops a resent same-day value from the write. The
edit sheet sends only the fields that changed. Re-enabling a reminder
that stays due after it is sent keeps the slot it was on instead of
scheduling from now; a short-cycle reminder is still scheduled from
now. Moving the notify hour later on the day a reminder was already
sent carries the last-sent cursor along, so the slot does not go out a
second time at the new hour.
2026-09-26 10:38:47 +02:00
Marc-André Bombeck 31e4c95487 fix(reminders): one cycle rule for the tick and the start page
The start page read every reminder due before the end of the day, so a
daily weigh-in at 20:00 or a twice-daily blood-pressure course showed
"check-up due" from the morning on and took a pinned place on the rail.

`holdsOpenAfterReminder` is now the one definition of a reminder that
stays due after it is sent: an interval longer than seven days, a rule
whose next gap is longer than seven days, a rule with no occurrence
left, or no cadence; never an appointment. The tick uses it to decide
whether a delivered reminder rolls on, and the start page uses it to
show such a reminder for its whole due day and keep it under the cap.
A short-cycle reminder shows only once its time has come and is not
pinned.

The tick also skips a reminder already sent for its current slot
outside its notify hour before the auto-resolve read. The eventful
satisfy worker still resolves it the moment a reading or lab result
lands, and the poll still runs for it once a day, in the notify hour;
the weekly hold stays after that poll so the safety net is daily.
2026-09-26 10:36:15 +02:00
Marc-André Bombeck fb960fb72e fix(reminders): decide what stays due by the cycle, not the measurement type
The first cut kept only free-text check-ups due after their reminder
and let every reminder with a measurement type roll on. A fortnightly
PHQ-9 or GAD-7 reminder is a measurement reminder, and each one still
jumped two weeks forward the morning it was sent without the
questionnaire being filled.

The rule is now the cycle length. A reminder whose next slot is more
than seven days away, or that has no cadence, stays due after its
reminder until it is satisfied (a matching reading, a lab result or
"done"), skipped or snoozed, and is sent again at most once a week. A
reminder on a weekly or shorter cycle rolls on as before. Appointments
stay one-shot. A reading that lands on an open measurement reminder
still sets lastSatisfiedAt and schedules the next cycle from itself.

The 0355 repair drops its "no measurement type" condition for the same
cycle rule, so the fortnightly questionnaires in the reported shape
are put back on the day they were reminded.
2026-09-26 10:33:13 +02:00
Marc-André Bombeck b2bfeb57c8 Merge branch 'fix/checkup-stays-due' into release/v1.39.2 2026-09-26 10:21:57 +02:00
Marc-André Bombeck 4d4a527c0d test(reminders): pin the snooze guard of the 0355 repair on its own
The snoozed fixture sat inside a week of the send, so the one-week clause already excluded it and dropping the snooze guard from the migration left the suite green. Snooze it further out, a minute after the send, so only the snooze cursor tells it apart from a roll-on.
2026-09-26 10:21:22 +02:00
Marc-André Bombeck 8b78e5486d docs(daily): note that a new rail kind needs its stored lists extended
The start-page item choice stores the enabled kinds, so a list saved before a kind existed reads as that kind switched off. Say so next to the kind list, where the next kind will be added.
2026-09-26 10:05:55 +02:00
Marc-André Bombeck cd79cfaae9 fix(reminders): keep a check-up's due date when only its details are edited
Every edit of a reminder recomputed its due date from now, so fixing
the label or the location of an open, overdue check-up moved it to its
next slot, the same "gone until next year" the reminder tick caused.
The due date is now recomputed only when the edit changes when the
reminder recurs: the interval, the rule, the first due date (compared
by value, since the edit forms resend every field), or switching a
disabled reminder back on. A notify-hour edit keeps the due day and
moves the hour on it, together with a snooze pinned to that slot.
2026-09-26 10:05:54 +02:00
Marc-André Bombeck 93881c1f93 fix(daily): keep due check-ups and today's visits on the start page
The start page's short list left out things a reminder had just told
the person about. A check-up counted only once its due hour had
passed, a booked visit was read one at a time and dropped out at its
start time, which is when its reminder fires, and both sat below doses,
sync problems and the Coach check-in under a three-item cap, so a busy
morning pushed them off.

The check-up item now covers every check-up due today or overdue and
names up to three of them. Visits are read for the whole local day,
also once started, and for the next 48 hours: everything booked today
shares one item, the next day with a visit gets a second, and the
today / tomorrow / day-after wording follows the calendar rather than
an hour count. A due check-up and today's visits always keep a place
under the cap; the displayed order is unchanged. A Coach cadence label
is translated here as it is on the checkups page.

The digest's wire shape is unchanged: visits reach it only as
`upcoming_visit` items, which may now appear twice.
2026-09-26 10:01:32 +02:00
Marc-André Bombeck 54b46f4679 fix(reminders): keep an open check-up due after its reminder
The reminder tick rolled every delivered reminder on to its next slot.
For a check-up (a reminder with no measurement type, made by the person
or suggested by the Coach) that filed an open task under next month or
next year the moment it was reminded, although nobody had done it. The
start page and the check-up card then showed a yearly check-up due
today as scheduled for next year, and a check-up with no cadence
dropped off every surface.

A check-up now keeps its due date after the reminder until it is
marked done, skipped or snoozed, and is reminded again at most once a
week while it stays open. A new `last_notified_at` column records the
last delivered reminder; a repeat is held while that send was for the
current slot and fewer than seven calendar days have passed, so a
snooze, a skip or a completion opens a fresh slot that fires on its own
day. The per-day claim stays the guard against two sends in one day.
Measurement reminders keep rolling on (the next reading satisfies them
and their next slot comes round soon), as do check-ups on a weekly or
shorter cadence, whose next slot is the next reminder anyway.
Appointment reminders stay one-shot.

Migration 0355 adds the column and puts back check-ups the old tick
rolled on: a live, enabled check-up whose most recent reminder claim is
followed within ten minutes by its last write, carrying a due date more
than a week past that send (or none, for a one-shot), not done, skipped
or snoozed since. Its due date returns to the instant of that send.
Anything else is left as it is. The same migration adds `upcoming_visit`
to start-page item choices stored before visits were one of them, which
otherwise read as visits switched off.
2026-09-26 10:01:27 +02:00
Marc-André Bombeck f5bab3258a fix(checkups): say "overdue since yesterday" instead of "overdue by 1 days"
The due phrase on the check-up card and the checkups page counted a
check-up one day past its date as "Overdue by 1 days", and the same
counted form read wrongly in German. One day over now has its own
phrase in all seven languages. Both overdue phrases keep the warning
colour through a shared `isOverdueDue` helper, so a surface no longer
compares against a single key.
2026-09-26 10:01:04 +02:00
Marc-André Bombeck 69d501fbb8 docs(integrations): keep the import tokens out of the crontab line 2026-09-26 09:39:30 +02:00
Marc-André Bombeck 5fb5145d7a docs(integrations): the importer uploads when its lookups are spent 2026-09-26 09:25:57 +02:00
Marc-André Bombeck 1667e9fdf5 Merge branch 'feat/document-import-token' into release/v1.39.2 2026-09-26 09:25:56 +02:00
Marc-André Bombeck 91acd9853f fix(scripts): send the source key in the form only, so a spent lookup never blocks the upload 2026-09-26 08:59:37 +02:00
Marc-André Bombeck 6292f7b6f4 docs(integrations): match the import guide to the metered re-sends
Every upload that sends a file counts towards the token's hourly limit,
workflow re-sends included, and a spent lookup allowance makes the
script wait rather than skip the wait. Note the 20 extra source ids a
document may collect, and name the settings section in the environment
example as the app shows it.
2026-09-26 08:56:28 +02:00
Marc-André Bombeck e5214265f6 Merge branch 'feat/document-import-token' into release/v1.39.2
# Conflicts:
#	docs/api/openapi.yaml
#	docs/integrations/document-import.md
2026-09-26 08:55:30 +02:00
Marc-André Bombeck 39b56ee4e2 Merge branch 'fix/backup-chunked-storage' into release/v1.39.2 2026-09-26 01:49:22 +02:00
Marc-André Bombeck 4bce039ee6 docs(backup): describe conversion on rotation, restores in progress and downgrades
The runbook now says that key rotation converts copies still stored as one
value into pieces a slice at a time, that a backup skips an account whose
copy is being restored, that two backups of one account run one after the
other, what a reader answers when its copy is replaced mid-read, and that
migration 0352 cannot be undone by going back to v1.39.1.
2026-09-26 01:49:03 +02:00
Marc-André Bombeck 8ad4610370 fix(backup): make rotation, concurrent writes and old rows safe for pieces
Key rotation re-sealed a single-value backup in place, which holds the
stored string, its bytes, the plaintext and the new ciphertext at once; a
copy can be over a hundred megabytes and the in-app rotation walked 25 of
them per page, enough to run a 1 GB container out of memory. Rotation now
converts each such copy into pieces under the active key instead, one row
at a time. The ~hlgcm1. stream of v1.38.6 to v1.39.1 is read a megabyte
at a time with its tag checked at the end, inside one transaction, so a
copy that fails the check is left untouched; the copy keeps its date. The
scan reads only the first characters of each value. Measured on a copy of
a 2.6 million-reading account (126 MB stored): converted in 25 s with the
heap flat at 57 MB under a 200 MB limit, where re-sealing in place ran out
of heap.

The weekly and manual backup leave an account alone while a restore of
its current copy is queued or running, and count it as skipped, not
failed. A reader whose copy is replaced mid-read answers 409
backup_changed, "replaced by a newer one while it was being read", rather
than the undecryptable error; a restore rolls back with the same code.

Pieces are sealed with a fixed associated-data label, so a value the same
key sealed for another purpose never opens as a piece; rotation re-seals
under the same label. A row holding both a single value and pieces, which
only an older release writing after a downgrade produces, is refused with
a message saying so, and the next weekly run replaces it. Rotation treats a
row deleted between its read and its write as gone rather than an error.
2026-09-26 01:49:02 +02:00
Marc-André Bombeck f55bd49f8d docs(backup): name the bucket listing the restore drill needs
The drill section said the drill needs nothing beyond the uploader's
GetObject and ListBucket, but the documented uploader grant is PutObject,
GetObject and AbortMultipartUpload. The drill lists the bucket to find the
newest object, so ListBucket is an addition, not something already granted.
2026-09-26 01:10:13 +02:00
Marc-André Bombeck d5a39603ca Merge branch 'fix/backup-chunked-storage' into release/v1.39.2 2026-09-26 01:03:25 +02:00
Marc-André Bombeck 1f046e68ac docs(backup): describe backups stored in pieces and the storage limit
The weekly-backup section still described one stored value capped at a
fifth of the heap and advised more memory. It now says how a copy is stored
and checked, that its size no longer depends on memory, what
BACKUP_MAX_STORED_MB limits and how to raise it, how older copies are read,
and how key rotation handles both forms. It also states that a 512 MB
container is below the app's own working set during a backup.
2026-09-26 01:02:53 +02:00
Marc-André Bombeck 1e09f30eff fix(backup): store a backup in sealed pieces instead of one value
A stored backup was one value in data_backups.data. v1.39.1 wrote it a
piece at a time but still joined the pieces into that one value, and one
value has to pass through the app whole, so a copy was capped at a fifth of
the heap: 105 MB in the default 1 GB container. An account with 1.75
million readings is past that and could not be backed up at all (#1031).

A copy is now kept as ordered pieces of about a megabyte in the new
data_backup_chunks table (migration 0352). Each piece is sealed on its own
with AES-256-GCM, and its sealed header names the copy (a random stream id
kept on the row), its position and whether it is the last. A reader checks
every piece before it releases a byte, so a piece that is missing, moved,
altered, taken from another copy, or a copy cut short is refused with
backup.payload.undecryptable before a restore deletes anything, and the
second read during the restore checks each piece again.

The write is one transaction, so the previous copy stays whole and readable
until the new one commits. Pieces are written through the model API: a raw
query with a large parameter is kept alive by Prisma's query plan cache,
which left 160 MB of heap behind per hundred one-megabyte inserts.

Restore, preview, download, the restore job and the admin list read both
forms; copies written before this change keep their single value and still
restore. The heap-derived limit is gone. The one limit left is on storage,
BACKUP_MAX_STORED_MB (default 2048), and its message names the setting. Key
rotation covers the pieces, the wipe and account deletion take them with
their backup, and the backup plan lists the table as not carried.

Measured on an account of 2.6 million readings in a 1 GB container with web
and worker in one process: backup 87 s, 97 MiB in 96 pieces, preview 20 s,
download 25 s, restore 264 s with every reading back exactly, peak 567 MiB,
no restart.
2026-09-26 01:02:48 +02:00
Marc-André Bombeck f711beab20 fix(scripts): fall through on spent lookups, send the key in both places
A 429 on the lookup no longer waits for the Retry-After; the keyed upload
answers the same question. The source key goes in the query string and the
form. The closing summary and the guide point to Read with AI for deferred
documents instead of Index all.

Refs #1038
2026-09-26 00:38:26 +02:00
Marc-André Bombeck 499b7dd9a7 fix(documents): keep deferred imports local and meter every re-send
A document uploaded with aiRead=defer is now indexed locally by any
automatic path, because the indexer reads the marker from the row rather
than from the job. Index all for search leaves such documents out and no
longer counts them. Only an explicit Read with AI or Generate summary ends
the hold.

Uploads that send a body keep their slot of the hourly limit, duplicates
included; handing it back let a token send the same bytes under id after
id for free. One document takes at most 20 further source ids, beyond
which the upload answers 409 documents.inbound.sourceAliasLimit. The
query-string key check is metered on the lookup allowance it shares with
GET /api/documents/inbound/source.

Refs #1038
2026-09-26 00:38:26 +02:00
Marc-André Bombeck 25e1229057 docs(integrations): correct the document import guide
Name the Paperless-ngx webhook fields as the workflow editor shows them,
note that Paperless does not follow redirects, and date the double-brace
placeholders correctly: only {{doc_id}} needs 3.0. Say what a dry run
does not check, which re-sends count against which allowance, that Index
all leaves held-back documents alone, and that a workflow can hold AI
reading back with aiRead=defer.
2026-09-26 00:30:12 +02:00
Marc-André Bombeck bec79879b5 Merge branch 'feat/document-import-token' into release/v1.39.2 2026-09-26 00:22:43 +02:00
Marc-André Bombeck b0f9bbe530 fix(crypto): rotate the backups v1.39.x stored as one stream
A weekly or uploaded backup written by v1.39.x is a single ~hlgcm1. stream
in data_backups.data. Its key id sits behind the stream marker, which the
string codec's parser does not read, so key rotation filed every such row
as legacy, failed to decrypt it and counted it as an error. On a host that
ran v1.39.x that was every weekly copy, and the rotation never finished
clean.

Rotation now reads the key id of a streamed value and re-seals it as a
stream under the active key, without touching what it holds.
2026-09-25 23:54:34 +02:00
Marc-André Bombeck fabd691128 fix(backup): keep an empty provenance empty on restore
A current disaster-recovery backup writes aggregationProvenance for every
measurement, null included. The restore treated null like a missing field
and marked every Apple Health stats: row without a provenance as
LEGACY_UNKNOWN, which is meant only for backups too old to carry the field.
The nightly daily-mean fold writes exactly such rows, so on a large Apple
Health account a restore changed tens of thousands of readings it was
supposed to put back as they were (#1031).

Only an absent field now takes the legacy path.
2026-09-25 22:40:08 +02:00
Marc-André Bombeck 4af356f804 fix(scripts): skip known documents before download in the importer
Ask HealthLog whether a document is already held before downloading it
from Paperless-ngx or Papra, and send the source key in the query string.
Pin Paperless API version 9 (Paperless-ngx 2.16 and later), apply --since
locally for Paperless too, fall back to the file name for a blank title,
stop with a clear message when the HealthLog address redirects, and say
only that storage is full when the figures are withheld. The guide names
the minimum versions and the shared OTHER namespace.

Refs #1038
2026-09-25 22:35:12 +02:00
Marc-André Bombeck 10a1c3ca2e fix(documents): keep every import key deleted, answer re-sends cheaply
A keyed upload that matched a stored document by its bytes never recorded
its key, so deleting that document let the next import run store it again.
Such keys are now kept as aliases of the document, the source-key check
reads them, and the purge carries them into the ledger with the row's own.

A source key may ride the query string and is then answered before the
body is read or the hourly allowance charged; an upload answered as a
duplicate hands its slot back. GET /api/documents/inbound/source answers
whether a key is held, under the same documents:write scope, so an
importer can skip a download.

aiRead=defer is stored on the row. The summary catch-up, the summary job
and lab auto-staging skip such documents until an explicit Read with AI
or Generate summary clears the marker; backup and restore carry it.

A documents:write caller no longer sees the quota figures on a full vault.

Refs #1038
2026-09-25 22:35:11 +02:00
Marc-André Bombeck 100412a3a6 Merge branch 'feat/condition-body-site' into release/v1.39.2 2026-09-25 22:09:01 +02:00
Marc-André Bombeck be53bca0cc Merge branch 'feat/document-import-token' into release/v1.39.2 2026-09-25 22:09:00 +02:00
Marc-André Bombeck 645032ec97 fix(body-sites): skip the site suggestions read without the visits section
A delegate who may keep the illness journal but not read the visits
would be refused by GET /api/body-sites on every open of the condition
form, and each refusal writes an access-denied row. The field now asks
only when the grant covers the visits' section, and the condition page
shows the site as text rather than a link in that case.

Refs #1025
2026-09-25 22:08:30 +02:00
Marc-André Bombeck 14f0fc4d4f feat(body-sites): record a body site on conditions and add a body-site view
A condition (illness episode) can carry where on the body it sits, in the
person's own words and encrypted at rest, plus an optional side (LEFT,
RIGHT, BOTH). Same enum, codec and reasoning as the procedure's site.

- migration 0354: two nullable columns on illness_episodes, reusing the
  laterality type from 0349
- create and edit accept bodySite and laterality; on PATCH an absent key
  keeps the stored value, so an edit from the shipped iPhone app, which
  never sends either field, leaves them untouched
- GET /api/body-sites: the sites the record holds across visits and
  conditions, folded after the decrypt and bounded per kind; with site
  (and laterality) the visits and conditions there, one hop to their
  documents, lab results and visits. Read in the profile section;
  conditions only under an illness grant with the module on, and links
  into ungranted sections come back as unlabelled placeholders
- the link service reads document and visit links from the condition's
  end of the two existing tables
- /checkups gains a Body sites tab; the visit and condition forms share
  one body-site field pair that suggests sites already used; a
  condition's page links its site into the view
- the doctor report, the clinician page and the MCP doctor-visit summary
  name the site on conditions; the Coach illness block carries it
  sanitised, and MCP get_illness_recovery returns it fenced
- backup and restore carry both fields in both file kinds; the site is
  registered as ciphertext and rotates with the key
- i18n in all seven locales, OpenAPI regenerated

Refs #1025
2026-09-25 21:55:14 +02:00
Marc-André Bombeck 0d223fdd9c docs: add the document import guide
Document tokens, the Paperless-ngx workflow recipe, the import script for
Paperless-ngx and Papra, scheduling for Papra, storage, and
DOCUMENT_UPLOAD_LIMIT_PER_HOUR.

Refs #1038
2026-09-25 21:48:12 +02:00
Marc-André Bombeck 0257f2207a feat(scripts): import documents from Paperless-ngx and Papra
A single dependency-free Node 22 script that copies tagged documents from
Paperless-ngx (REST, original files) or Papra (API key, /file) into the
vault through a document token. Serial, one file in memory, waits on 429
Retry-After, and resumable through the server's source-key dedup. Supports
--since, --kind / --kind-map, --dry-run with sizes, and holds back automatic
AI reading unless --ai-read is given.

Refs #1038
2026-09-25 21:48:12 +02:00
Marc-André Bombeck 55a32ff7d1 feat(documents): add a document upload token for imports from other systems
A narrow `documents:write` token, minted cookie-only at
`POST /api/tokens/documents` and accepted by the vault upload route alone.
A scoped caller draws on its own hourly bucket per token
(`DOCUMENT_UPLOAD_LIMIT_PER_HOUR`, default 120) and gets a receipt
`{ id, duplicate }` instead of the stored row.

Uploads take optional `sourceSystem` / `sourceId` fields. The source key is
unique per account across live and deleted documents, and the tombstone
purge carries it to a small ledger, so re-sending a document the owner
deleted answers 200 `deleted: true` and stores nothing. `aiRead=defer`
indexes locally and skips the summary and lab staging.

The detail sheet shows where an imported document came from; backup and
restore carry both fields; Delete All Data clears the ledger.

Refs #1038, #938
2026-09-25 21:48:04 +02:00
Marc-André Bombeck af65f01fec Merge pull request #1037 from MBombeck/chore/deps-webauthn14-react
SimpleWebAuthn 14, React 19.3, CodeQL on push to main
2026-09-25 20:24:16 +02:00
Marc-André Bombeck e3bccc86d5 ci(codeql): analyse every push to main
A commit that reaches main without a pull request, such as an asset
uploaded through the web UI, was never analysed until the weekly run.
Run on push to main as well. Pull-request runs still cancel their
superseded heads; push runs are grouped per commit and never cancelled,
so back-to-back merges each keep their own analysis.
2026-09-25 19:55:56 +02:00
Marc-André Bombeck 76ca6bbb30 chore(deps): move to SimpleWebAuthn 14 and React 19.3
Bump @simplewebauthn/server 13.3.3 -> 14.0.2 and @simplewebauthn/browser
13.3.0 -> 14.0.0, and keep React on an exact pin at 19.3.0 with react-dom
and both type packages moved alongside.

SimpleWebAuthn 14 changes one default the server relied on: the verifier
used to accept every algorithm the library knew (EdDSA, ES256, ES512,
PS256/384/512, RS256/384/512, RS1) and now accepts only the three it
offers. Pass both lists explicitly so a registration that succeeded
before still succeeds, and so the offered list stays EdDSA/ES256/RS256
on a runtime that would otherwise prepend ML-DSA-44. The option JSON of
all four ceremonies, and verification against stored credentials, match
the 13.x snapshots unchanged.
2026-09-25 19:53:47 +02:00
Marc-André Bombeck 831fc9e0a7 test(auth): pin the WebAuthn wire contract against the real library
Every existing passkey test mocks @simplewebauthn/server, so a library
upgrade could change the options a browser or the iOS app receives, or
the algorithms the verifier accepts, without any test noticing. Drive
the real library with a software authenticator: snapshot the option
JSON of all four ceremonies, register and authenticate with each of the
ten algorithms the verifier has accepted, and verify an assertion
against a credential row stored the way earlier releases wrote it.
2026-09-25 19:47:11 +02:00
Marc-André Bombeck 39b8dd708c Merge pull request #1035 from MBombeck/release/v1.39.1
Release v1.39.1
2026-09-25 14:32:36 +02:00
Marc-André Bombeck 7a81318f27 docs(changelog): note the corrected all-time averages and counts 2026-09-25 14:14:26 +02:00
Marc-André Bombeck 1a21147b1a Merge branch 'fix/v1391-e2e' into release/v1.39.1 2026-09-25 14:11:25 +02:00
Marc-André Bombeck 1aa405cb44 fix(analytics): count each reading once in the all-time summaries
On the rollup path the all-time count, min, max and mean are composed
from DAY buckets plus one raw aggregate of the readings older than the
fold window. The bucket half read every DAY bucket the account had, the
raw half every reading before now minus five years, so a reading on any
day that had a bucket before that instant was counted in both. Such
buckets are common: the per-write hook folds whatever day it touches,
the Apple Health import folded whole spans until this release
clamped it, every fold snaps its start down to a whole day, and
nothing removes a bucket once the moving window has passed it. The
count came out too high and the mean leaned towards the doubled days,
while the live fallback reported the true figures for the same account.

Both halves now meet at the start of the window's first UTC day:
buckets from there on, raw readings before it. A reading lands in
exactly one half whichever buckets exist, so buckets already written
before the window need no repair.
2026-09-25 14:10:56 +02:00
Marc-André Bombeck 9b999233b3 Merge branch 'fix/v1391-e2e' into release/v1.39.1 2026-09-25 13:55:07 +02:00
Marc-André Bombeck aba147152a fix(dashboard): stop pre-window readings holding the second phase back
The snapshot's second phase (blood pressure in target, the per-context
glucose tiles, the Health Score) waits until weight, both blood-pressure
halves and steps have DAY buckets. The fold writes buckets only inside
the five-year window, so a type whose every reading is older than that
never gets one and the phase stayed null for good. Since the Apple Health
import now folds only inside the window too, an account that imported
years-old blood pressure or steps and nothing since lost those tiles and
its score with no explanation.

An uncovered gate type now holds the phase back only when it has a
reading inside the window, which is the case the backfill will still
reach. The extra query runs on the miss path alone and asks one indexed
EXISTS per uncovered type.
2026-09-25 13:48:31 +02:00
Marc-André Bombeck 42e35ffbf9 test(e2e): follow the restore to its job before reading the record
The restore route answers 202 with a job id and leaves the work to the
backup-restore queue. The journey still expected the synchronous 200 and
read the record straight after the click. It now asserts the queued
answer and its status route, polls that route until the job reports
succeeded (a failed job ends the wait with its code), and only then
checks what the restore put back and dropped. The job runs on the
pg-boss worker inside the server under test, as the manual backup pass
earlier in the same file already relies on.
2026-09-25 13:48:31 +02:00
Marc-André Bombeck a46d0b41c8 chore(release): v1.39.1 — large accounts, restores in the background, and medications kept as a record 2026-09-25 13:12:34 +02:00
Marc-André Bombeck 8700c17724 Merge branch 'feat/units-per-dose-mixed' into release/v1.39.1 2026-09-25 12:56:47 +02:00
Marc-André Bombeck 189edc728e Merge branch 'feat/medication-record-only' into release/v1.39.1 2026-09-25 10:32:11 +02:00
Marc-André Bombeck e1478a884d test(medications): pin the live-era floor, the nudge and the same-day edit cases 2026-09-25 10:31:22 +02:00
Marc-André Bombeck 367bc3fca5 fix(onboarding): say what happens after adding an as-needed or record-only medication 2026-09-25 10:03:10 +02:00
Marc-André Bombeck ff3ef9147c fix(coach): give no supply span for a GLP-1 medication kept as a record 2026-09-25 10:03:09 +02:00
Marc-André Bombeck 0e242cfea1 fix(telegram): do not offer or record doses of a record-only medication 2026-09-25 10:03:09 +02:00
Marc-André Bombeck 37c6b0e144 fix(medications): never mint a slot from before the live schedule era
The projector floored today's slots only on an empty archived era, the
reminder worker and the next-due reads on the newest revision boundary,
and the auto-miss pass on the creation instant alone. Switching tracking
back on and then moving a dose time the same afternoon therefore put the
morning dose on the card, and the next day's pass stamped it a miss; a
same-day times edit on any medication did the same.

One helper now names the live era start (the newest active revision's
boundary) and every path floors on it: the projector, the worker, the
doses card, the medication list, the MCP schedule tool and the auto-miss
pass, which leaves a placeholder minted after the switch for a slot
before it.
2026-09-25 10:03:08 +02:00
Marc-André Bombeck 1d1570733e fix(medications): leave record-only doses out of the nudge, the status model and the BP correlation
Three readers compute a rate straight from intake rows without reading a
schedule: the weekly compliance nudge, the adherence series behind the
general status, and the BP-versus-compliance correlation. They now read
tracked medications only. The structural guard covers intake-row readers
as well as schedule readers, with a whitespace-tolerant matcher, a floor
on the match count and a reviewed allowlist.
2026-09-25 10:03:08 +02:00
Marc-André Bombeck 1e040605be feat(medications): accept units per dose like 1.5 and let the editor enter them
A medication's units per dose, a schedule's override and a restored
backup now accept any value above 0 and at most 100 with at most four
decimal places, which is exactly what the Decimal(10,4) column stores.
Before, only whole numbers 1-100 and the fractions 1/4, 1/3, 1/2, 2/3,
3/4 passed, so one and a half tablets could not be recorded. A restore
now refuses a value no write route would accept.

The medication editor keeps its buttons and adds an Other field that
reads 1.5, 1,5, 1 1/2 and 1½, holds the step while the text does not
read, and previews the value it will save. The supply tab's packaging
dialog uses the same reader; it refused every non-whole value before,
so a medication at half a tablet could not have its packaging saved.
Cards and the supply tab show a whole number plus a fraction as 1½.

The rule, the input reader and the display format live in one module
without imports so the editor and the validators share them.

Refs #1034
2026-09-25 09:58:55 +02:00
Marc-André Bombeck e03cf7c2c8 Merge branch 'feat/medication-record-only' into release/v1.39.1 2026-09-25 09:37:27 +02:00
Marc-André Bombeck 854bdd5ca1 Merge branch 'feat/restore-background-job' into release/v1.39.1 2026-09-25 09:32:28 +02:00
Marc-André Bombeck d4c6e0fab2 docs(api): describe how a record-only schedule is kept on update 2026-09-25 09:25:40 +02:00
Marc-André Bombeck f482fc403c test(medications): replay the shipped app's schedule save on a record-only medication 2026-09-25 09:25:40 +02:00
Marc-André Bombeck e5236d2e6a fix(medications): keep a record-only schedule unless the write names trackIntake
The shipped iPhone app cannot see the schedule of a medication kept as a
record, because it is served with an empty schedules list. Its editor opens
such a medication as daily at 08:00 and, once any schedule field is touched,
sends a full replacement built from that default, plus asNeeded and oneShot,
and never trackIntake. On a record-only medication the update route now
drops schedules, asNeeded and oneShot from a write that does not name
trackIntake and applies the rest. The web schedule editor and the wizard
name the flag on every save.
2026-09-25 09:24:38 +02:00
Marc-André Bombeck 94ec9ab932 Merge remote-tracking branch 'origin/release/v1.39.1' into feat/medication-record-only 2026-09-25 09:20:15 +02:00
Marc-André Bombeck 0a5fa4b2ae fix(crypto): page the key-rotation walks by id, not by cursor
The corpus walk and the rotation script paged with Prisma's cursor and skip.
Prisma resolves that cursor by reading the page's last row again, so when
that row was hard-deleted before the next page (a backup replaced, a cached
response expired), the next page came back empty and the walk ended early.
The scan then counted fewer rows than the database holds, which could read
as nothing left on the old key while rows it never reached still were.

Both walks now ask for the rows whose id is greater than the last one read,
which needs no row to still exist.
2026-09-25 09:17:25 +02:00
Marc-André Bombeck 04a683ae07 fix(medications): refetch the daily reads after the track-intake switch 2026-09-25 09:15:18 +02:00
Marc-André Bombeck 2311f9b47d fix(insights): leave record-only medications out of the adherence storyline 2026-09-25 09:05:48 +02:00
Marc-André Bombeck 0095fda216 test(medications): count only a use of the intake-tracking vocabulary, not its import 2026-09-25 09:01:01 +02:00
Marc-André Bombeck b4c2706ec9 feat(medications): keep a medication as a record without tracking intake
A per-medication trackIntake flag (migration 0351, default on for every
existing and new row). With it off the dose, dates and schedule stay stored,
but nothing derives a due dose from them: the reminder worker, the manual
reminder check, the today projector, the auto-miss pass, the low-stock pass,
the doses card, the today list, the outstanding-dose badge, compliance and
its heatmap, the doctor report, the Coach, the BP-status gate, insights,
targets, achievements, the efficacy view and the MCP schedule tool all skip
it.

The medication wire serves such a medication with schedules: [] and the
stored rows in an additive recordedSchedules field, so a client that arms
local reminders from schedules stays silent without an update. Switching
tracking off or back on archives a schedule revision at that instant, the
untracked stretch with an empty payload, so it never counts as missed and
the projector does not put a dose from before the switch back on the card.

A structural guard freezes the set of schedule readers: each one filters on
the flag, derives from dueSchedules, shapes the wire with scheduleWireFields,
or is allowlisted with the reason it derives nothing due. The flag travels
through backup, restore and the medication CSV export.
2026-09-25 08:57:10 +02:00
Marc-André Bombeck 700de6d228 feat(medications): add the track-intake switch to the medication pages
The detail page leads the schedule tab with the switch and a one-line
explanation of each state; with tracking off it drops the reminder card,
the next-dose and adherence rows, and shows the stored schedule as the
record. The wizard summary carries the same switch. Cards, the table and
the detail header mark a record-only medication, which leaves the take and
skip buttons, the take-all set, the log-dose dialog and the dashboard quick
add. Strings in all seven locales.
2026-09-25 08:57:10 +02:00
Marc-André Bombeck 4897752c3c fix(backup): date a restored medication by its earliest record when the file has no date
Portable files exported before v1.39.1 carry no creation date for a
medication, so the restore stamped the restore time. The dose history reads
that date as the day the medication began to exist, and every miss before
it, including the day before the restore, dropped out of the record.

When the file has no creation date, the restore now uses the earliest thing
the file records for the medication: its first dose (scheduled, taken or
written), the start of its first schedule revision, its course start, its
first pause, dose change or side effect, and never a date after the restore.
A file that records nothing about the medication keeps the old default.
2026-09-25 08:53:38 +02:00
Marc-André Bombeck d7bc873691 fix(backup): answer an upload too large to store with 413
An uploaded file whose encrypted copy passes the size one stored backup may
have on this host (a fifth of the heap limit) stopped the store with
BackupBlobTooLargeError, which the route let through as a 500 and reported
to the error tracker. It is now a 413 with the numbers and the remedy in the
message and meta.errorCode backup.upload.too_large, and the refusal is
audited like the others. The store rolls back, so nothing is kept.
2026-09-25 08:51:00 +02:00
Marc-André Bombeck 3abbad048e fix(backup): never run a restore again after its data committed
A restore commits its transaction and then rebuilds the chart tiers. A
worker that stopped during that rebuild left the job running with a stale
heartbeat, and the boot sweep and the admission check treated it like any
interrupted job: the sweep queued it again, so the second run deleted and
re-wrote the account and lost whatever was written in between, and a second
interruption closed it with "rolled back, nothing was changed", which was
false.

The job now records `committedAt` (added to migration 0347, which has not
shipped) and awaits that write before the rebuild starts. The sweep and the
admission check close a committed job as `failed_after_commit`, never queue
it again, and evict the account's caches. The rebuild itself is left to the
nightly and boot passes that already rebuild missing tiers.

The module comment now says what an interrupted restore does (restarted
once, then failed) and what happens to other writes while a restore runs:
new rows are written at once, updates to rows the restore already deleted
wait on their lock until it commits or rolls back.
2026-09-25 08:49:45 +02:00
Marc-André Bombeck c327ae81d5 Merge branch 'feat/procedure-history' into release/v1.39.1 2026-09-25 08:23:34 +02:00
Marc-André Bombeck 25099a57b6 fix(checkups): lead a procedure card with what was done
In the procedure history every row carried the kind as its heading and
again as its badge. A procedure now leads with its reason, and the
practice moves to its own line beneath the body site.

Refs #1025
2026-09-25 08:18:06 +02:00
Marc-André Bombeck 0b28498d83 feat(doctor-report): add a surgical history section
New structured leaf SURGICAL_HISTORY in the history group and in the
standard template: every procedure that took place, oldest first, with
its date, what was done (the visit's reason), the body site with its
side and the outcome. Lifetime reference data like the immunization
record, so it ignores the report window. The PDF prints it as a table
and the clinician share page renders it; saved selections do not widen.

The FHIR bundle carries no Procedure resource, on the same terms as
visits: no REST route or capability entry exists for it.

Refs #1025
2026-09-25 08:11:42 +02:00
Marc-André Bombeck ad0d50fa28 feat(visits): record procedures and surgeries with a body site
A visit can be filed as a procedure or surgery (new EncounterKind
PROCEDURE) and carry a body site in the person's own words, encrypted at
rest, plus an optional side (LEFT, RIGHT, BOTH). An existing visit
switches to the new kind by an ordinary edit, keeping its date, reason,
outcome and links.

- migration 0349: enum value, laterality type, two nullable columns
- GET /api/encounters/procedures: the DONE procedures, newest first,
  searched after the decrypt over site, side and reason, with body-site
  choices and a total computed over the whole history
- create and edit accept bodySite and laterality on any kind
- /checkups gains a Procedures tab with a body-site filter; the visit
  form offers the site for a procedure and keeps it in view on any
  visit that carries one
- backup and restore carry both fields; the body site is registered as
  ciphertext and rotates with the key
- MCP get_visits narrows by kind and reads the whole record for
  procedures when no window is named; the Coach visit block names a
  procedure's site
- i18n in all seven locales, OpenAPI regenerated

Refs #1025
2026-09-25 08:11:37 +02:00
Marc-André Bombeck 934131ee3e Merge branch 'feat/restore-background-job' into release/v1.39.1 2026-09-25 08:10:06 +02:00
Marc-André Bombeck cb69f662ab fix(measurements): attribute named sleep stages from a bridge token to EXTERNAL
The named-stage arm took the body's source and so wrote MANUAL under a
scoped credential, while every other arm of the route resolves such rows
to EXTERNAL. It now resolves the source from the credential as well, and
a bridge segment stays apart from the same reading from Apple Health.
2026-09-25 08:04:31 +02:00
Marc-André Bombeck d0e321c54a Merge branch 'fix/v1391-contract-and-ingest' into release/v1.39.1
# Conflicts:
#	docs/api/openapi.yaml
#	src/lib/openapi/routes/measurements.ts
2026-09-25 08:04:30 +02:00
Marc-André Bombeck 7e654175b6 test(contract): pin the v1.39.1 wire changes as additive for shipped clients
Decoders written against the shapes the shipped iPhone builds read still decode every payload this release changes, and the old shapes still satisfy the new document: the new batch-entry fields and the error code stay optional, the profile time zone stays a required string, and the named sleep-stage answer sits beside the old create response rather than in place of it.
2026-09-25 07:39:07 +02:00
Marc-André Bombeck f443ab6615 feat(measurements): accept sleep stages by name on POST /api/measurements
A bridge such as Tasker or Home Assistant could only send sleep stages
through the batch route, in HealthKit's terms: the category identifier,
a stage codepoint from 0 to 5, and a value it had to work out in
minutes. It can now post one segment to `POST /api/measurements` with
`type: "SLEEP_DURATION"`, a `sleepStage` of `IN_BED`, `ASLEEP`, `AWAKE`,
`CORE`, `DEEP` or `REM`, and either `startDate` + `endDate` or
`measuredAt` (the end) + `value` (minutes).

The row is the one the batch route writes for the same segment, and the
dedupe is the batch route's: the opposite-source same-reading check,
then one reconcile over both unique identities. Without an `externalId`
the server derives one from the stage and both instants, so a re-post
answers 200 `duplicate`, a corrected start answers 200 `updated`, and a
new segment answers 201 `inserted`. The narrow `measurements:write`
token is accepted and still writes only MANUAL rows. Every other body
on this route behaves as before.

Requested in #972.
2026-09-25 07:39:07 +02:00
Marc-André Bombeck be112df972 fix(profile): report the time zone the server uses on /api/user/profile
`/api/auth/me` has reported the resolved zone, the stored one or the
instance default when the stored value is unusable, while
`/api/user/profile` returned the raw column. A client reading the
profile could cut days differently from the server, and sending the
value back in a PATCH was refused.

Both reads, and the profile PATCH answer, now go through one
`resolveStoredTimezone`. The field stays a string and always holds a
valid IANA name. The web account editor already reads the resolved
zone from `/api/auth/me` and saves through the validating timezone
route, so it shows the zone in use and can only write a valid one.
2026-09-25 07:39:07 +02:00
Marc-André Bombeck 0cc73d3c88 fix(ingest): treat upsert_failed as a retry in the nutrient and cycle batches
The nutrient batch docs told a client to log and drop an `upsert_failed`
entry. The route means the opposite: a write group failed on the
server's side and nothing was stored. The docs now say to send the
entry again on a later sync, and keep the three validation skips
terminal.

A retry under the same Idempotency-Key used to replay the cached
failure, because the 200 carrying `upsert_failed` was cached like any
other. Both the nutrient and the cycle bulk routes now mark that
response `no-store`, as the measurement batch already does for
`failed`, so the retry writes again.

The cycle bulk route already answered its validation refusal with
`cycle.bulk.invalid` and an over-cap batch with `cycle.bulk.too_large`.
Both are now pinned by tests and named in the route's 422 response.
2026-09-25 07:39:07 +02:00
Marc-André Bombeck a7682a9fed fix(measurements): name the batch validation refusal and the band an entry broke
The validation 422 from `POST /api/measurements/batch` now carries
`meta.errorCode: "measurement.batch.invalid"`, beside the existing
`too_large` and `source_not_permitted` codes, so a client can file the
rows as permanently refused instead of holding its anchor on a guess.

A `value_out_of_range` entry now also carries `convertedValue`, the
reading after conversion into the stored unit, and `range`
(`min`, `max`, `unit`), the band it was checked against. Both appear
only on that skip. A fraction sent where a percent was expected is now
visible in the response instead of looking like a sensor glitch.

Status codes, the envelope and every existing field are unchanged.
2026-09-25 07:39:07 +02:00
Marc-André Bombeck 74dedee645 fix(import): write Apple Health spot rows without Prisma's per-call heap
Each `createManyAndReturn` flush of the export import left about 5 MB of
heap behind until some two dozen calls had piled up. A 300 000-record
synthetic import under a 524 MB heap settled at 53 MB retained; a run of
back-to-back 600-row calls with nothing between them reached 212 MB.

Spot rows now go through the column-array `INSERT … SELECT FROM unnest`
the restore already uses, with `ON CONFLICT DO NOTHING RETURNING`, which
is what `createMany({ skipDuplicates })` emits. The same import holds
11.5 MB and finishes in 35 s instead of 55 s. Ids are minted in the
cuid() shape, defaults are written as the client would write them, and
integration tests compare the returned rows and the resulting table with
`createManyAndReturn` for fresh rows, conflicts on either unique
identity, and duplicates inside one call.
2026-09-25 07:39:07 +02:00
Marc-André Bombeck 47e9f7e81c feat(backup): run a restore as a background job with progress
Restoring a large account was one request: 94 s for 1.25 million readings.
A reverse proxy that cuts a request at 60 s (nginx's default) showed the
operator an error for a restore that went on to finish on the server.

The restore request now checks the typed confirmation, that the backup
exists and that its stored copy opens, admits one job for the account and
answers 202 with its id. The `backup-restore` queue runs the restore and
records its phase, counts and outcome on a `backup_restore_jobs` row
(migration 0347), which `GET /api/admin/backups/restores` and
`GET /api/admin/backups/restores/{id}` read back.

What a restore checks and writes is unchanged. The body moved from the
route into `restoreBackup` (src/lib/export/restore-backup.ts): every
refusal still happens before the first delete and the replacement is still
one transaction, so a failure part-way leaves the account as it was. While
it runs the account keeps showing its current data, and other writes are
neither refused nor held, as before.

- One restore per account: a partial unique index admits one queued or
  running job, and a second request gets 409 `backup.restore.active` naming
  the running job. A per-account advisory lock inside the transaction holds
  even if a worker thought gone is still writing.
- Time budget: the job's expiry is two hours and a file whose transaction
  limit would run past three quarters of it is refused before anything is
  deleted (`jobDeadline`, beside `jobBudget`).
- Resuming: the job writes a heartbeat every two seconds. A boot sweep
  queues a job whose worker stopped again from the start, at most twice,
  then fails it as interrupted. The admission check releases an abandoned
  job so it never holds the account's slot.
- The staged file is the stored `DataBackup` row, already encrypted at
  rest. It stays whatever the outcome, so a retry needs no new upload. The
  job records a digest of the copy and refuses one that was replaced while
  it waited.
- Failures carry a stable code and a sentence that says what to do.
- The console follows the job: phase and counts while it runs, the outcome
  after, and after a reload it finds the job again from the server. A poll
  that fails on the network is never shown as a failed restore. A web
  process separate from the worker evicts the account's caches when it
  first reports the restore finished. The success line goes through the
  outcome module, so an empty file is not drawn as a tick.

The model is registered in the backup plan (not carried) and the wipe plan
(wiped with the account); the queue in the maintenance registrar, the
subsystem surface and the job-fact allowlist; the new code in the error
catalogue; the routes in the OpenAPI contract. The tests that pin restore
semantics now drive the real route and the real job through one helper, and
`backup-restore-job.test.ts` pins the asynchronous contract itself.
2026-09-25 07:39:06 +02:00
Marc-André Bombeck ee23409b77 Merge branch 'fix/v1391-cycle-and-links' into release/v1.39.1 2026-09-25 07:38:34 +02:00
Marc-André Bombeck 17c31c37a5 fix(links): offer the unlink undo inside the sheet
The picker lives inside a modal sheet, and a toast sits outside it where
its button cannot be pressed while the sheet is open. The undo is now a
line under the chips that stays until the next change. The calendar's
intercourse diamond also grows a step so it reads as a diamond on a
phone rather than a dot.
2026-09-25 07:30:36 +02:00
Marc-André Bombeck 92ad5513c0 chore(db): renumber the placeholder repair migration to 0350
0346 is taken by the external-source migration that reached main first.
The repair touches only intake rows and depends on no other migration of
this release.
2026-09-25 07:25:29 +02:00
Marc-André Bombeck 702a13873d Merge branch 'main' into release/v1.39.1 2026-09-25 07:21:34 +02:00
Marc-André Bombeck 47e2520b9f Merge pull request #892 from Antiheld86/feat/measurement-source-external
Give ingested measurements their own source value
2026-09-25 07:21:30 +02:00
Marc-André Bombeck 6e05f86e7b fix(vaccinations): show a dose's linked documents and keep them on edit
A dose opened from the list carried no document links, since only the
detail read has them. The edit sheet showed an empty picker, and saving
any change sent that empty set, which the route reads as unlink
everything. The sheet now reads the dose's own links before it shows
them, and a save leaves the links alone unless they were changed.

A link to one dose or visit (/vaccinations?dose=, /checkups?visit=) now
scrolls to it and opens it for someone who may edit it.
2026-09-25 07:10:56 +02:00
Marc-André Bombeck 31f0d7c9fb fix(links): make the X the only unlink and let a chip open its record
A link chip was one button with an X drawn inside it, so tapping the
chip to open the linked record removed the link. The label now opens the
record (a dose, a visit, a condition or a document) and a separate X,
labelled with what it removes, unlinks, with an undo in the toast. Each
chip also carries its record's date, so several doses of one vaccine no
longer read as identical chips. The fix sits in the shared picker, which
is every chip list with this shape.
2026-09-25 07:10:50 +02:00
Marc-André Bombeck 0390d124cb fix(cycle): mark intercourse and other logged entries on the calendar
An intercourse entry left no trace on the month grid and the legend had
no entry for it. The day now carries a diamond marker, and anything else
logged that day with no marker of its own (a test, contraception,
spotting, a temperature, a mucus or cervix reading, a note) shows a
hollow ring, so a day with one of those logged no longer looks empty.
Both are named in the legend and in the cell's accessible label.
2026-09-25 07:05:03 +02:00
Marc-André Bombeck adec5bd045 fix(cycle): carry every logged day entry on the calendar read
The calendar grid carried flow, symptoms, BBT, the ovulation test and the
mucus reading, and dropped the rest of the day log: intercourse, spotting,
the pregnancy and progesterone tests, contraception and whether a note
exists. The published contract also promised the three cervix signs while
the route never sent them.

The intent fields resolve through the same reader the day-log read uses,
so an encrypted envelope reads the same on both, and the grid is served
under the same cycle grant as the day log. Additive fields; the contract
test pins the wire keys to the published schema.
2026-09-25 07:02:14 +02:00
Marc-André Bombeck 510dbfe273 chore(db): renumber the external-source migration to 0346
0342 sorts before migrations 0343 to 0345, which are already applied on
v1.39.0 instances. The next free number keeps the order linear.
2026-09-25 06:55:22 +02:00
Marc-André Bombeck 1205540585 chore(db): renumber the external-source migration to 0342
0336 was taken by the off-host backup ledger while this branch waited; the
schema change itself is unchanged.
2026-09-25 06:55:18 +02:00
Marc-André Bombeck e7597c7ac1 docs(changelog): leave the entry to the release commit
The text is unchanged and waits with the other release drafts; keeping it
in the branch made CHANGELOG.md collide with every release that shipped
while this waited.
2026-09-25 06:55:18 +02:00
Antiheld86 a099d813ee Document what EXTERNAL does to a contested day, and pin it
Review caught a behaviour change this branch causes but never wrote down.
`pickCanonicalSourceRows` takes the first ladder source present in a day's
bucket and filters the day to that source. Before, a typed reading and a
bridged one were both MANUAL, so both survived. Now MANUAL ranks, EXTERNAL
does not, and the bridged row leaves the canonical set on any day that also
has a typed one.

That reaches every surface needing one source per day — the daily totals
behind the charts, the health score, the doctor report, correlations, mood
crosstabs and personal-record detection. A day with only bridged readings is
untouched: nothing ranked is present, so the picker's pass-through keeps
everything.

The changelog says so in the user's terms, including the part that is a fix
rather than a change: two indistinguishable MANUAL rows were both counted,
which inflated a running total on a day somebody did both.

Four cases pin it, because it is emergent from a rank ladder and stated in
no single place: the contested day, the bridged-only day, the both-MANUAL
shape the change moves away from, and a stored ladder that names EXTERNAL
being honoured. Ranking EXTERNAL turns the first two red, which is the
review anybody adding it to a ladder should have to pass.
2026-09-25 06:55:17 +02:00
Antiheld86 9fc1413181 docs(measurements): label EXTERNAL and update the guide and contract
The measurements list already badges any row whose source is not MANUAL and
already builds its source filter from the shared enum, so both pick the new
value up on their own. What it needs is a name: `EXTERNAL` reads as a leaked
enum constant, and it is the only new value a user is expected to operate,
since it is an option in the filter and a badge on every bridged row.

Both label catalogues gain an entry. They are keyed by the enum, so a new
source without a label is a type error and the coverage guard fails the
suite — which is exactly what happened here, and is the reason this carries
a settings label too even though EXTERNAL sits on no priority ladder and so
never renders there.

The settings card's scope note and the Home Assistant guide both claimed
readings arrive "as if you had entered them by hand", which is no longer
true. Both now say the rows are marked as coming from an external device and
are still yours to correct, and the guide spells out that the payload must
not name a source at all.

The changelog entries go under Unreleased as Changed: v1.38.1 shipped the
token, so these describe a change to something people already have. They say
what that means in practice — rows written before this keep the old label
and cannot be sorted out afterwards, a batch re-push can duplicate because
the dedup key now carries the source, and an automation sending an explicit
`source` field has to drop it.
2026-09-25 06:55:17 +02:00
Antiheld86 112a029443 test(measurements): cover EXTERNAL provenance on both write paths
The write-smoke suite is `satisfies Record<MeasurementSource, SourceCase>`,
so growing the enum is a compile error until a case exists; the new one
goes through the ordinary single-entry POST, which is the production path.
It carries the trap this suite sets for you written down: `beforeEach`
seeds a session cookie and the caller resolver is cookie-first, so arming
only the authorization header resolves as that session and quietly writes
MANUAL — the case would then pass without testing anything. Both hardcoded
totals move 14 → 15.

In the bearer-scope suite the two rows that asserted MANUAL now assert
EXTERNAL, and three cases join them: a body naming MANUAL is refused on
each route (the widening from "names APPLE_HEALTH" to "names anything",
which nothing else covered), and a bridge-written row is still value-
editable by its owner through PUT. That last one guards the split between
the write allowlist and the correctable set — folding the two constants
back together value-locks every bridge row behind a 409, and this is what
notices.
2026-09-25 06:55:17 +02:00
Antiheld86 f94d358ade feat(measurements): write EXTERNAL from both ingest write paths
Under a `measurements:write` credential the row's source is now decided by
the server on both routes, and the body may not name one at all.

The 422 widens from "names APPLE_HEALTH" to "names any source". It was
narrow only because the forced value was MANUAL, so a body saying MANUAL
was never actually overridden. Now it would be — and overriding a client's
explicit assertion quietly is the thing both routes' comments rule out,
while honouring it would defeat the change: a bridge that kept sending
MANUAL would stay indistinguishable from a typed reading. Status and
errorCode are unchanged, and the documented Home Assistant payload sends no
source at all.

The single-POST predicate keeps reading the raw body: the create schema
defaults `source` to MANUAL, so after parsing "said MANUAL" and "said
nothing" are the same value. Both of that route's create sites resolve the
source, the array arm included — that is the combined BP + Pulse path a
bridge uses, and missing it would leave exactly those rows unbadged.

Two consequences worth naming. Bridge rows no longer join the
MANUAL/APPLE_HEALTH cross-source merge, so they can't be swallowed by a
rule written for the iOS adopt-on-pair case. And a bridge posting at the
same instant as a hand entry now lands both rows instead of a 409, which is
honest and does not double-count: the rollup collapse is per
(type, day, source) and MANUAL outranks the unlisted EXTERNAL.
2026-09-25 06:55:17 +02:00
Antiheld86 5ec361abec feat(measurements): mirror EXTERNAL in Zod, keep those rows correctable
Adds the `EXTERNAL_SOURCE` leaf beside `scopes.ts` and mirrors the value in
`measurementSourceEnum` so the read shapes and the sync decoder see it. It
stays out of `WRITABLE_MEASUREMENT_SOURCES`: a source a client could assert
would prove nothing about where a reading came from, and that constant is
published to clients as `ingest.writeAllowlist`.

The value-edit gate in `PUT /api/measurements/[id]` needs the other question
answered, though — whether the number is the user's own to fix — so it now
reads a separate `USER_CORRECTABLE_MEASUREMENT_SOURCES`. The 409 that
protects a Withings row exists because the value is the provider's reading;
the hardware behind an ingest token is the user's own scale, and locking
those rows would contradict what the settings card and the Home Assistant
guide promise. That is the only site reading the wider set.
2026-09-25 06:55:17 +02:00
Antiheld86 c2999c955d feat(measurements): add EXTERNAL measurement source
Rows pushed in through a `measurements:write` Bearer token are attributed
`MANUAL` today, so afterwards nobody can tell which readings came off the
scale and which were typed by hand. Give that write surface its own
`MeasurementSource` value, the way 0189 did for TELEGRAM and 0207 did for
MCP.

Enum extension only: purely additive, no row touched, `IF NOT EXISTS` makes
a rerun safe, and the value is not USED in the migration so Postgres'
same-transaction restriction does not bite. Declared last in the datamodel
so the Prisma member order and the physical order stay identical.

No backfill, and none is possible — `measurements` carries no actor or
token column, so a bridge-written MANUAL row is byte-identical to a typed
one. Existing rows stay MANUAL.
2026-09-25 06:55:17 +02:00
Marc-André Bombeck d81518b5bf Merge branch 'fix/large-account-jobs' into release/v1.39.1 2026-09-25 06:49:16 +02:00
Marc-André Bombeck e9449ece61 Merge branch 'fix/dose-history-pre-creation-slots' into release/v1.39.1 2026-09-25 06:49:15 +02:00
Marc-André Bombeck c757981638 fix(jobs): give the hourly rebuild the same time budget
The one-shot hourly rebuild of already-folded heart-rate, HRV and SpO2
days walks one account's whole folded history in one job with the
default fifteen-minute expiry, about fifty statements per day. Like the
drains it now stops between days once 75 % of the expiry has passed or
pg-boss aborts the job, and fails so pg-boss retries it (the boot send
allows three retries); a rebuilt day leaves the candidate set, so the
retry starts at the first day not yet rebuilt.
2026-09-25 02:05:19 +02:00
Marc-André Bombeck b7a26d3a4d fix(backup): resume an off-host run where its last attempt stopped
The off-host backup walked every account in one job with the default
fifteen-minute expiry, and a retry started again from the first account.
On an instance with one large record next to others, an attempt that
ran out of time spent its retry uploading the accounts it had already
done (#1031).

The run now stops between accounts once the job's time budget is spent
and fails, so pg-boss retries it. Every attempt of a job carries the same
creation time; an attempt skips the accounts whose ledger shows a success
since then, and keys its objects on that day, so a retry after midnight
still writes under the run's date. A new job uploads every account again,
and a retry whose accounts were all done passes.
2026-09-25 02:05:19 +02:00
Marc-André Bombeck 4242b454ce fix(import): fold rollups over the span the import wrote
After an Apple Health import the worker folded the rollup table from the
account's first measurement to its last, whatever the import carried, and
so also folded history older than the five-year window that the boot
backfill, its discovery and every read path keep to.

The import now records the oldest and newest instant it wrote
(`measuredSpan` on the job result), and the fold covers that span,
clamped to the fold window. On the seeded account of 1.25 million rows the
full fold took 12 s, the slowest statement 2.7 s against the 60 s
statement limit, so this is about the window rather than time.
2026-09-25 02:05:19 +02:00
Marc-André Bombeck 0a54a43799 fix(crypto): walk every encrypted column in bounded pages
Key rotation and the rotation status read every column that was not
flagged as a blob with one `findMany` over the whole table.
`Measurement.notesEncrypted` and `MoodEntry.noteEncrypted` are such
columns, so rotation loaded every measurement of the instance: 1.25
million rows on one large account (#1031), and the rotation status page
did the same on every view.

Every column is now walked with the id-cursor pages the blob columns
already used: 25 rows a page for blobs, 5 000 for everything else. The
maintenance script's own per-column walks page the same way. On the seeded
account with 1 460 notes to rotate, peak heap fell from 272 MB to 153 MB,
and it no longer grows with the table.

`scanned` now counts the rows that hold ciphertext for every column, as
it already did for the blob columns, rather than every row of the table
for some columns and only the ciphertext rows for others. The runbook
says so.
2026-09-25 02:05:19 +02:00
Marc-André Bombeck 7071fa91af fix(records): repair cumulative records in one transaction
The repair for the inflated cumulative records deleted the suspect rows,
committed, and then re-ran the detector. When the detector failed, which
a timeout on a large account or a restart can cause, the records stayed
deleted, and since discovery looks for the suspect rows the account was
never repaired again (#1031).

The delete and the re-derivation now run in one transaction, with the
detector reading through it, so they commit together or not at all. The
transaction gets five minutes; the detector took 19.8 s on the largest
seeded account.
2026-09-25 02:05:19 +02:00
Marc-André Bombeck 77bfa2f4e1 perf(records): find the best cumulative day a day at a time
The personal-record pass, every half hour for every account, read every
live row of each cumulative type into memory to find the best day. With
784 000 active-energy rows on one account (the per-sample rows pile up
when the nightly drain cannot finish, #1031) it ran a 524 MB heap out of
memory; the old code needed 1.1 GB of heap for that account.

It now reads the type in bounded keyset pages and handles one local day
at a time. The canonical-source pick it applies is per day, so the day
totals and the winner are the same; a tie still keeps the earliest day.
Measured on the same account: 189 MB peak heap, the same record. The
warm-up gate counts only up to its threshold instead of counting a whole
history.

`iterateSourcePages` and `iterateDayBuckets` in the consolidation base
take the row type as a parameter, and the day grouping can keep every row.
2026-09-25 02:05:19 +02:00
Marc-André Bombeck 237acc0002 fix(backup): export, upload and restore a large account as streams
An account of 1.25 million measurements could not export its data or be
restored from any backup (#1031). Measured in a 1 GB container:

- The full export and the passphrase export built the whole payload and
  its JSON string in memory; the app ran out of heap and restarted.
- The weekly backup's JSON is 662 MB, longer than any string V8 can hold,
  so `unpackBackupBlob` threw on every read. Restore, download and the
  restore preview all answered "could not be decrypted".
- Upload accepted 10 MB, a fraction of a large export.

Every reader and writer of a backup file now streams it:

- `scanBackupJson` reads a backup's bytes once, keeps every section but
  the named bulk arrays, and hands their elements out one at a time.
  `readStreamedBackup` uses it twice: a first pass that validates each
  measurement against the element schema and keeps the rest of the file,
  and a second pass that hands the measurements to the writer in batches.
  Stored copies and off-host objects are authenticated whole on their
  compressed ciphertext before any plaintext is read; only the
  decompression is streamed.
- Restore writes the measurements with one `INSERT … FROM unnest` per
  batch. Prisma caches a query plan per `createMany` row count, and one
  1 000-row plan kept about 145 MB alive, which alone put the restore past
  the heap limit. The transaction budget grows with the measurement count.
  The awards and ECG sections are handed the ids they reference that were
  written, not every written id.
- The export routes write the file into the response as it is produced.
  The passphrase export spools its ciphertext to a temporary file because
  the HLX1 format puts the tag first; the format is unchanged, so existing
  archives open as before.
- Upload accepts the raw body, JSON or gzip, up to the 512 MB request
  ceiling, checks it as it arrives and stores it in the same pass; the admin
  page compresses the file in the browser before sending it. Multipart stays
  for small files.
- Download streams the stored JSON; the preview counts measurements from
  the stream. The monthly restore drill and `scripts/restore-backup.ts`
  read the off-host object the same way; the script can write `.json.gz`.

On the seeded account in a 1 GB container: export 25 s at 389 MB peak,
passphrase export 25 s, both uploads 19 s, restore of the weekly backup
94 s at 554 MB peak, and export, upload and restore round-trip to exactly
the same rows. The encrypted-column guard now also recognises the raw SQL
statement that writes `DataBackup.data`.
2026-09-25 02:05:19 +02:00
Marc-André Bombeck 79ed62b7f9 chore(scripts): add a seed for an account the size of a multi-year import
`scripts/seed-large-account.ts` inserts about 1.25 million measurements
for one user, shaped like an Apple Health export plus the iOS sync: dense
heart rate, HRV and SpO2, the high-frequency mean types, export `stats:`
daily rows, recent per-sample cumulative rows and nightly sleep stages.
Everything is generated in Postgres, so a run takes seconds, and it ends
with ANALYZE. It is how the maintenance jobs in #1031 were reproduced and
measured; never point it at a database holding real data.
2026-09-25 00:32:10 +02:00
Marc-André Bombeck 9411a485c8 fix(backup): store the weekly and manual backup piece by piece
The backup streamed its JSON through gzip and the cipher, but kept the
stored copy as one string and handed that to Postgres in one parameter.
On a seeded account of 1.25 million measurements the copy is 64 MB of
base64, and the pieces, the joined string and the driver's copies of it
grew the process from 309 MB to 946 MB resident. A bare process needed a
heap limit above 400 MB to finish it (the new path finishes under 220 MB).
With the dense retention running beside it in a 1 GB container the
process died of heap exhaustion, and the backup job sat "active" until its
two-hour limit marked it "job timed out" (#1031).

`packBackupBlobInto` hands the stored copy on in pieces of up to 4 MB as
it is produced, and `storeBackupBlob` writes them into a temporary table
on its own transaction and assembles the row with one `string_agg`. The
process never holds the whole copy. The account's previous copy stays in
place until the new one is complete: a failure rolls back to it.

Measured on the seeded account in a 1 GB container, web and worker in one
process: the backup completes in about 30 s with the dense retention
running beside it, where v1.39.0 crashed within 30 s.

The streamed JSON also reports its progress to the job every 50 000 rows.
2026-09-25 00:32:05 +02:00
Marc-André Bombeck 1b45ebb99d fix(jobs): stop the long drains on a budget instead of at the expiry
pg-boss marks a job "job timed out" at its expiry and fires its abort
signal, but does not stop the handler. A drain that could not finish kept
writing after its job was declared dead, and the retry then ran beside it
over the same days.

The nightly drain tick and the per-user dense-retention and daily-mean
jobs now stop between days once 75 % of the job's expiry has passed, or
as soon as pg-boss aborts the job, and complete with `stopped_early`
instead of failing. What they folded is committed. A nightly tick that
stopped early after folding something sends itself again a minute later,
up to 24 times, so a first-time backlog after a large import drains the
same night; a run that folded nothing does not hand on, so a pass that
cannot move does not loop.

The expiries themselves stay at their defaults: with the passes bounded
per day and budgeted, a longer limit would only delay the signal.
2026-09-25 00:31:48 +02:00
Marc-André Bombeck f4b51cf134 perf(consolidation): fold a day at a time and batch the hourly writes
The consolidation drains (cumulative, daily mean, dense intra-day
retention, legacy steps) gathered a type's whole history into one array
before folding the first day. On an account of 1.25 million rows the
heart-rate array alone held about 230 MB, and the dense retention peaked
at 460 MB of heap against a 524 MB limit; in a 1 GB container running the
web server and the worker together the process died of heap exhaustion
within a minute and the job was later marked "job timed out" (#1031).

- Pages are now handed on one at a time and each local day is folded as
  soon as its last row has been read, so a pass holds one page and one
  day.
- The keyset cursor gains a redundant `measuredAt >= cursor` bound.
  Without it Postgres could not use the cursor as an index condition and
  re-read every earlier row on each page (47 ms and 248 000 filtered rows
  for one page halfway through the heart-rate history; 5 ms now).
- The dense fold resolves a day's hourly rows with one lookup and one
  insert instead of two lookups and a write per hour. On the seeded
  account the pass went from about 290 000 statements to 54 000.
- `shouldStop` lets a caller end a pass between days; the result says
  `stoppedEarly`. Days commit one by one and a folded day leaves the
  scan, so the next run continues at the first day not reached.
2026-09-25 00:31:40 +02:00
Marc-André Bombeck 32c3248b57 feat(jobs): log long-running, expired and cut-off jobs by queue
A job that ran into its pg-boss expiry left no trace in the app log. Most
handlers annotate a wide event nobody emits, pg-boss records an expiry only
in its own table, and a worker that dies of heap exhaustion writes one
FATAL line that names no queue. On a large account three queues failed
with "job timed out" for days and the log said nothing about them (#1031).

Every handler now runs inside `observeJob` (through `runJob`), which writes
`job.progress` every two minutes while a handler runs (elapsed time, heap,
RSS and the last progress the pass reported), `job.expired` when the job
passes its expiry while the handler is still running, and `job.finished`
when a long or expired run settles. At worker boot, `worker.boot.jobs_cut_off`
names every job a previous process was still running when it stopped.

The admin card's "job timed out" now says what the limit was and that the
cause is either a run too slow for it or a restart while it ran.
2026-09-25 00:31:30 +02:00
Marc-André Bombeck 47c7c71802 fix(medications): read a pinned dose the same as the dose on its own
Automatic matching counts a dose taken up to an hour before a slot's
on-time window as on time. A dose pinned to the slot was judged from the
window's start instead, so the same dose read on time unpinned and late
once pinned. A pinned dose now uses the same early grace, and the
confirmation says so plainly: the dose counts as if it had been logged for
the slot, on time or late depending on when it was taken.

Refs #1028
2026-09-24 19:54:37 +02:00
Marc-André Bombeck eafef5adeb fix(medications): keep a recorded miss from before the medication's creation
The history view treated every auto-miss anchored before the medication's
creation as the today projector's placeholder and dropped it. That is true
only on the creation day. History that arrives from before the creation, a
restore of an older file for one, can carry real misses, and those vanished
from the history and the rates.

The creation stays the boundary of expected doses: an earlier one, the
first recorded dose or the course start date, would read every day between
it and the creation that no row names as missed, and an import carries
takes and skips only, so those misses would be invented. Before it, every
recorded take, skip and miss claims its slot. Only rows that record nothing
are dropped: a pending row, and an auto-miss within the day before the
creation, which is where the projector's placeholders sit.

Refs #1028
2026-09-24 19:53:42 +02:00
Marc-André Bombeck f028d9c55b fix(medications): never stamp a miss on a slot before the medication existed
The today projector mints a pending placeholder for every slot of the
current day, so a medication added in the afternoon carries placeholders
for that day's earlier slots. The hourly auto-miss pass stamped them as
forgotten doses a day later, and every reader that counts raw rows saw a
miss on a day before the medication existed: the miss-free streak broke on
the creation day. The dose history, the rates and the Coach already ignore
such a placeholder; the streak read the row as it was.

The pass now stamps a miss only on slots from the medication's creation on.
A placeholder before it stays pending, so the web and the app can still
offer the slot for logging and a dose recorded for it converges onto it. A
migration returns the placeholders an earlier pass already stamped. It
touches only rows that can be nothing else: server-minted, never acted on,
anchored before the creation but within the day before it, which is where
the projector's placeholders sit. An older auto-miss carried in with
restored history keeps its state.

Refs #1028
2026-09-24 19:52:39 +02:00
Marc-André Bombeck 8642d63b82 fix(backup): keep a medication's creation date through a portable restore
A portable export left the medication's creation instant out, so a restore
stamped the restore time instead. The creation instant is where a
medication's expected doses start, so the whole restored history then read
as predating the medication: its missed doses dropped out of every
adherence rate. The portable file now carries the creation instant as the
disaster-recovery file already did, and the restore, which already honoured
it, brings it back. A round trip pins both file purposes.

Refs #1028
2026-09-24 19:48:01 +02:00
Marc-André Bombeck a6b8c61a82 fix(medications): count only a recorded dose as taken in the calendar
The adherence calendar counted every off-schedule ledger row as a dose taken
on time. An orphaned skip or auto-miss, a row on an instant that is no slot
of the schedule, carries no taken time, yet coloured its day as taken. Such
a row now counts as taken only with a taken time; an orphaned skip reads as
skipped, and an orphaned auto-miss counts nothing, as it already does in the
rate.

Refs #1028
2026-09-24 19:46:24 +02:00
Marc-André Bombeck fa86c9e46c fix(medications): say what attributing a dose to a slot counts as
The confirmation promised that an attributed dose always counts as taken
late. It counts as on time when it falls inside the slot's on-time window,
which also covers a dose taken shortly before the slot's clock time, and
as late otherwise. The copy now says so in every locale, and a test pins
the split it describes.

Refs #1028
2026-09-24 19:40:28 +02:00
Marc-André Bombeck fe7cccfd46 fix(medications): attribute doses to slots from before the medication existed
A medication added at 16:05 with doses at 09:00, 14:00 and 21:00 showed its
creation day wrongly in "Last 90 days". The 14:00 dose, recorded afterwards
on its own slot, read as an off-schedule take "due" at 21:00, and a 09:00
row with no time appeared as off-schedule too.

The history route minted slots only from the creation instant, so the 14:00
slot never existed for the dose to land on, while the write path, which
mints the whole day, had filed it there. The 09:00 row was the pending
placeholder the today projector mints for every slot of the day, which the
auto-miss pass stamped a day later; with no slot to bind to it surfaced as
an off-schedule row.

The ledger now mints slots over the requested window and takes the
creation instant as the floor of expected slots: a slot before it appears
only when a recorded dose claims it (a take by its window or its pin, or a
skip), and a pending or auto-missed placeholder on it is dropped. The first
archived schedule era also covers the stretch before the creation, so an
edited schedule behaves the same.

Every adherence surface tallies the same ledger with the same floor, so the
detail rates, the calendar and the ledger bar agree on that day. The doctor
report, the Coach and the adherence chips previously read the slots before
a medication existed as missed whenever their window started earlier; they
now read nothing there.

Refs #1028
2026-09-24 19:40:27 +02:00
Marc-André Bombeck 9328a4298d Merge pull request #1030 from MBombeck/release/v1.39.0
Release v1.39.0
2026-09-24 13:47:51 +02:00
Marc-André Bombeck ecfa837dea chore(release): v1.39.0 — AI becomes optional, and a switched-off module leaves the whole app 2026-09-24 13:30:44 +02:00
Marc-André Bombeck 53bd7098da Merge branch 'fix/v139-review-server' into release/v1.39.0 2026-09-24 12:48:05 +02:00
Marc-André Bombeck 8a09adc1c0 fix(cycle): answer a delete of an already deleted cycle without moving anything
The cycle delete now runs the shared removal, which finds live starts only.
A second delete of the same cycle read nothing to remove; the route now says
so explicitly and answers 204 before the transaction, and the tombstone the
first delete left stays as it was.
2026-09-24 12:43:41 +02:00
Marc-André Bombeck 70dba821be perf(measurements): fold each source before picking the canonical one
The live daily fold ranked every row by source before folding, which sorted
the whole window twice. A year of per-minute heart rate (525,600 rows) took
about 0.55 s per series on Postgres 16, with both sorts spilling to disk.

The fold now aggregates per source and bucket in one hashed pass and then
keeps each bucket's ladder-canonical source. Folding the canonical source's
rows is the same as folding that source's group, so the numbers do not
change; the same year reads in about 0.29 s. A new integration case pins the
canonical pick, mean, count and spread for a day with three sources.
2026-09-24 12:37:51 +02:00
Marc-André Bombeck 503e69488a Merge branch 'fix/v139-review-client' into release/v1.39.0 2026-09-24 12:32:31 +02:00
Marc-André Bombeck e822154936 fix(cycle): give back a start that a mis-tapped earlier start folded in
A start logged within one period before an existing start folds that start
into itself and soft-deletes it, since the two are one period entered out of
order. Nothing recorded which start was folded, so taking the earlier start
back could not bring the later one back: a mis-tap on the 5th with a real
start on the 10th, then deleted, left the 10th gone and the cycle before it
reopened.

Migration 0345 adds menstrual_cycles.absorbed_into_id. The folded row names
the start that absorbed it; removing that start restores it, re-derives its
own end and hands its days back to it. The column is needed because a
soft-deleted row alone cannot tell a folded start from one the person
deleted, and the audit trail is not state a removal can read. Deleting a
cycle directly now runs the same shared removal as deleting its day-log.
2026-09-24 12:30:39 +02:00
Marc-André Bombeck d38ca7737e fix(measurements): offer only measurement types whose module is on
The measurement form, and with it the add menu's Measurement entry,
listed sleep and glucose with those modules switched off. It now filters
its types through the surface map's type ownership, which a test holds
equal to the ownership the server gates measurement types on, and a
default or last-used type that is switched off falls back to the first
offered one.
2026-09-24 12:24:47 +02:00
Marc-André Bombeck f28153c832 fix(tz): refuse bare UTC offsets as a timezone
The runtime accepts "+05:30" as a zone id, so isValidTimezone let it through,
but Postgres reads a bare offset in AT TIME ZONE with the POSIX sign (east
of UTC is negative), and the day-grain SQL aggregates would cut every day on
the wrong side of UTC.

isValidTimezone now accepts named zones only: whatever the runtime resolves
to a bare offset is refused, while named zones, their aliases, UTC and the
Etc/GMT family stay accepted. Every write that already validated through it
refuses offsets now, and the screener and mood linked-context request schemas
validate their zone too. A value stored before this change can still sit in
the database, so the SQL call sites that read the stored zone directly (the
dashboard summary, achievements, the doctor report, the tiered AI context)
fall back rather than splice it, as the resolver and the day aggregates
already did.
2026-09-24 12:23:00 +02:00
Marc-André Bombeck a15a148667 fix(insights): hold the scores strip until the cycle ring is decided
For a cycle-tracking account the strip painted Strain first and swapped
it for the cycle ring once the calendar read landed, moving the row
under the reader. The ring's decision now reports while it is pending,
and the strip keeps its skeleton until then.
2026-09-24 12:22:52 +02:00
Marc-André Bombeck e49997bf97 fix(settings): offer Coach links only while the Coach can open
Settings → Coach's sources pointer and the About-me follow-up questions
linked to /coach whatever the Coach's state. Without a provider or
consent the Coach page sends the visitor straight back to Insights, so
the link only bounced. Both now follow the Coach capability; the
questions themselves stay readable.
2026-09-24 12:21:21 +02:00
Marc-André Bombeck fbe2cd5833 fix(settings): say precisely what withdrawing AI consent stops and deletes
The confirmation said the AI features stop straight away, and the
withdrawn line that no health data goes to an AI provider. The Coach and
Insights need the receipt only when they use the AI access the server
provides, so on an own key or a local model they keep working, and the
model-written notes are kept while another consent still covers
Insights. Both strings now say so in every locale, and a guard pins the
copy next to the resolver rule it describes.
2026-09-24 12:20:14 +02:00
Marc-André Bombeck f700a7c0f1 fix(coach): let the capability table decide the about-me question consent
The aboutMeQuestions capability admits an ai_insights_only receipt, but the
question generator ran its own gate that demanded a Coach receipt, so a
person whose capability read available still got the fallback questions on
an operator-held chain.

The generator now runs the shared wire re-check (aiEgressRefusal) for the
aboutMeQuestions key, so the receipt kinds and the rule for when one is
needed come from the capability table alone.
2026-09-24 12:19:11 +02:00
Marc-André Bombeck 8d60690b4a fix(insights): give the setup hint's dismiss button a 44 px target on phones 2026-09-24 12:18:24 +02:00
Marc-André Bombeck 091e4b84cb fix(backup): fold a pre-0343 Coach availability key on instance restore
Migration 0343 moved the operator's Coach answer from module availability
into the Coach switch and folded every live row. Restoring the instance
settings from an older file wrote the dead coach key back into module
availability and left the Coach switch on, so a Coach the operator had off
came back.

The restore now applies the same fold: coach false in the file's module
availability switches the Coach off, and the key is dropped either way.
2026-09-24 12:18:00 +02:00
Marc-André Bombeck a2282a498c fix(encounters): give the visit form's link pickers their own query keys
The visit form's lab and episode pickers fetched with their own page
sizes under the same keys as the Labs list and the illness pages, which
fetch with others. Whichever read landed first served the other: the
picker could see 50 episodes instead of 100, or the Labs list a 200-row
page as the whole list. The picker reads now have keys of their own,
under the lab and illness roots so writes still evict them.
2026-09-24 12:17:56 +02:00
Marc-André Bombeck aeb8930ce1 test(e2e): assert slots the AI-off overview can actually paint
Three assertions in the AI-optional overview spec named slots that no
longer exist anywhere in the tree, so they held whatever the page did.
They now name the error primitives the overview paints on a refused read
and the Coach hand-offs that paint only while the Coach is available, and
the no-provider journey checks that /coach goes back to the overview.
2026-09-24 12:16:57 +02:00
Marc-André Bombeck 2c1e0f5bca fix(ai): drop model text whose consent was withdrawn while the call was in flight
A consent withdrawal purges the stored status notes, briefing, reaction
lines and workout paragraphs in its own transaction, but a provider call
that was already in flight still persisted its reply afterwards, bringing
the text back under a consent that no longer existed.

The consent rule now runs once more after the reply arrives, against the
provider that actually answered and with a fresh receipt read: in
runStatusCompletion (status notes, workout paragraphs, narratives, derived
assessments), before the briefing commit, and before the reaction-line
commit. A refused reply is dropped; the spent tokens stay on the ledger.
2026-09-24 12:15:56 +02:00
Marc-André Bombeck 15cce33a28 fix(documents): keep the link pickers from deleting a link made elsewhere
A dose or a visit can link documents from its own form, and a
document's sheet can link doses and visits; both ends write the same
table, and the sheet writes the whole set on every tap. Dose and visit
writes left the document reads alone, and the sheet seeded its pickers
from a detail cached for five minutes, so the first tap there after
linking from the dose's form wrote a set without the new link and
removed it.

Dose and visit writes now evict the document root, the sheet reads the
document again on every open, and its pickers wait for that read before
they offer a change.
2026-09-24 12:15:36 +02:00
Marc-André Bombeck 28d491174e fix(onboarding): keep the tour from bouncing between the Coach and Insights
With no provider set up, a fresh self-host's default, the Coach module
is on but /coach redirects to /insights because the Coach is not
available. The tour read the raw module map, kept its Coach stop, pushed
/coach, was sent back to /insights and pushed /coach again on the
pathname change: a loop.

The tour now reads the same capability-folded map as the navigation, so
the Coach stop is not in the list. And a stop whose page redirects is
dropped after one navigation, in the direction the person was going,
instead of being pushed again.
2026-09-24 12:13:15 +02:00
Marc-André Bombeck bd58571d46 fix(coach): hold reminders while the Coach is unavailable
The daily sweep and the measurement-ingest hook surfaced due reminders into
a Coach conversation whatever the record's coach capability said, and the nag
cap then dismissed them after three ticks although no badge ever showed. The
app-open path already waited on the capability.

surfaceCoachReminders now holds every row while the coach capability is
unavailable (the same answer that keeps the badge dark), and the nag cap
neither charges nor dismisses a held user's surfaced rows. They surface on
the first tick after the Coach is back. The integration fixture gives its
users a provider and consent, and a held case covers the sweep, the nag cap
and the ingest hook.
2026-09-24 12:11:21 +02:00
Marc-André Bombeck 676bb2eff7 fix(ai): refresh the account's AI answer after every change to its inputs
Every AI surface reads its capability from the ai block on
/api/auth/me, but setting up or removing a provider, signing in to or out
of Codex, saving the fallback chain, the central-Codex opt-in, the
local-OCR switch, a minted consent receipt, the admin's server key and
central Codex, and a guardian's save inside a managed record evicted only
their own reads. The surfaces stayed on the old answer until a reload.

All of these writes, and the ones that already refreshed the payload
(consent, modules, Hide Coach, the operator's switches), now evict one
bundle, aiInputDependentKeys. A structural test holds every client write
to those endpoints to it.
2026-09-24 12:11:14 +02:00
Marc-André Bombeck 06251d7219 fix(ai): read AI switches, modules and consent afresh inside background jobs
A background job opens one wide event for its whole run, and the per-request
memo cached the operator switches, module availability, module preferences,
provider presence and consent kinds on it. The nightly status passes loop
over every candidate inside that one event, so a switch turned off mid-run
did not stop the remaining users, and the wire re-check read the same cached
answer.

memoizePerRequest takes a freshInBackground option; every input that decides
whether AI work may run sets it, so a background caller reads them on every
call while a request still reads them once.
2026-09-24 12:08:39 +02:00
Marc-André Bombeck 03ecb5bd52 fix(coach): keep stored plans and conversations reachable with the Coach off
The page gate matched /coach/plans and /coach/conversations to the Coach
module by the nav prefix, so with the Coach switched off by the operator
or hidden by the person both pages were replaced by the module notice and
never reached their read-only mode. Both are now stored-record pages the
gate leaves alone.

With the Coach off nothing in the navigation led there either. Settings
now carries a plans card, shown when plans exist, and the conversations
card links to the full list.
2026-09-24 12:05:52 +02:00
Marc-André Bombeck 4ae231d757 Merge branch 'feat/coach-reminders-readable' into release/v1.39.0 2026-09-24 11:58:46 +02:00
Marc-André Bombeck 6e45acfbc6 feat(coach): keep stored reminders readable and erasable with the Coach unavailable
Reminders are the person's own record, like the stored facts,
conversations and plans. The list and delete routes no longer ask the
Coach module; creating, confirming, resolving or rescheduling one stays
Coach use and is refused by POST and PATCH as before.

Settings -> Coach now always mounts the reminders card (shown with Hide
Coach on only when reminders exist), and Settings -> AI lists them through
the stored-memory block while Settings -> Coach is out of reach. With the
Coach unavailable the card is read-only: every reminder can be read and
deleted, while keep / done / dismiss are not offered.
2026-09-24 11:57:42 +02:00
Marc-André Bombeck 5e5d33ecf8 feat(coach): keep stored plans readable and erasable with the Coach unavailable
Plans are the person's own record, like the stored facts and
conversations. The list and delete routes no longer ask the Coach
module, and the plans page turns read-only instead of redirecting to
Insights: every plan can be read and removed, while confirming or moving
one stays Coach use and is refused by the PATCH route as before.
2026-09-24 11:48:15 +02:00
Marc-André Bombeck e0ece41e21 Merge branch 'feat/ai-web-surfaces' into release/v1.39.0 2026-09-24 11:37:10 +02:00
Marc-André Bombeck b7830c3a72 test(e2e): cover Insights and the Coach memory without AI
Adds the AI-optional journeys: the overview with AI switched off by the
operator and with no provider (no AI requests, no refusals, one setup
hint, remembered dismissal), and on an account of its own, withdrawing AI
consent deletes the stored briefing, and a hidden Coach's conversation is
read and deleted from Settings, AI.

Specs that drive AI surfaces against mocked routes now serve an available
capability map through /api/auth/me, since the web no longer assumes AI
is on until told otherwise.
2026-09-24 11:36:30 +02:00
Marc-André Bombeck e72441743f fix(settings): never report a failed consent read as a withdrawal
The AI consent card turned any failed read of the receipt (a rate limit, a
network drop) into "Withdrawn" and offered a grant. It now says the read
failed, with a retry. The Coach history note is one sentence.
2026-09-24 11:36:29 +02:00
Marc-André Bombeck a6c65bd37e fix(insights): give the cycle ring a score cell only when it has a dial
The scores strip reserved a cell for the cycle ring, and dropped Strain to
make room, whenever the cycle module was on. Without an active cycle the
ring renders nothing, so the row showed a gap where Strain used to be. The
overview now asks the same calendar read whether there is a dial today.
2026-09-24 11:10:48 +02:00
Marc-André Bombeck 5f6a0e42b4 refactor(web): retire the feature-flag reader for the capability map
The web no longer reads GET /api/feature-flags: useFeatureFlags and its
query key are gone, and use-ai-capability gains the two readers the Coach
pages and the operator notice need. A structural guard fails when web code
reads the retired projection, and when a module requests an AI route
without being registered with the capability that gates it.

Adds the copy for every new state in all seven locales and drops the
per-card no-provider strings.
2026-09-24 11:05:59 +02:00
Marc-André Bombeck 3d85445e50 feat(settings): explain operator switches and keep the Coach memory reachable
Settings, AI says which AI features the server's operator switched off and
shows the one setup hint while no provider is configured. The consent
withdrawal says what it deletes and what stays, and a document-reading
consent on file gets its own withdrawal. Regenerate follows the briefing
capability and the connection test names an operator refusal.

The Coach memory (facts and stored conversations) is never gated on the
Coach: Settings, Coach always shows it, and Settings, AI shows it while
the Coach page is out of reach, whenever rows exist.

Onboarding offers AI only where it can be set up here: the done-screen
panel and the getting-started row go away while the operator has AI off
or inside somebody else's record.
2026-09-24 11:05:54 +02:00
Marc-André Bombeck 4449b34ac7 feat(documents): gate document, lab and medication reading on their capabilities
Reading a document, scanning a lab report and turning a medication
description into a schedule follow documentAi, labsOcr and
medicationExtract. Unavailable, the action is not offered. With only the
document-reading consent missing, the place that reads asks for it and
grants exactly that (ai_extraction), nothing wider.

Refusals are read by meta.errorCode: a 403 is no longer always called a
missing consent, and a spent daily budget no longer shows the rate-limit
sentence.
2026-09-24 11:05:49 +02:00
Marc-André Bombeck 48d97ef70d feat(insights): render AI parts from the capability map, never as errors
The daily briefing, the hero's briefing paragraph, the trend sentences and
the status notes follow the briefing and statusText capabilities: hidden
while unavailable, never an error card or a per-card "connect a provider"
state. The advisor and status reads only fire while their capability is
available; a 403 settles as an outcome instead of throwing.

A failed comprehensive read no longer replaces the overview, and every
overview section is fenced so a section that throws becomes one error row.
The period review always renders its composed narrative. Cycle, breathing
and lab-change sections go through the surface map. One calm setup hint
appears on the overview while no provider is configured and one could be.

Signals, rhythm events and the mood patterns card say a failed read with a
retry, the score anatomy no longer calls a failed read insufficient data,
the catalog marks only the rows whose read failed, and workouts are not
probed while the module is off.
2026-09-24 11:05:44 +02:00
Marc-André Bombeck 61d912627d feat(coach): follow the coach capability at every entry point
The floating button, the drawer, the launch pills, the nav entry and the
Coach pages read the coach capability from /api/auth/me instead of
combining the operator switch with Hide Coach on their own. A missing
provider or consent now hides the Coach too, instead of opening one that
can only answer with an error.

Stored conversations stay reachable: while the Coach is unavailable the
conversation list turns read-only, opens a transcript in place and keeps
delete. Refusals before the stream opens are read by meta.errorCode and
each code has its own copy.
2026-09-24 11:05:38 +02:00
Marc-André Bombeck 114ff4b4eb test(sharing): read loadDocument as a headerless navigation sink
The connect and sign-in hand-offs moved from window.location writes onto
the loadDocument helper, and the guard stopped seeing them. Its reference
floor caught the drop. Watched red with a fenced thumbnail route handed to
loadDocument.
2026-09-24 10:57:45 +02:00
Marc-André Bombeck f893dae004 Merge branch 'test/v139-flag-mocks' into release/v1.39.0 2026-09-24 10:52:30 +02:00
Marc-André Bombeck c229829663 test(health-score): answer the provider probe in the configured-flag checks
The provider mock lacked `probeProviderChain`, so the capability loader
threw on every wire and read `check_failed`. It now answers "no
provider" like the rest of the mock, and the derived payload pins
`no_provider` so a starved loader fails the file.
2026-09-24 10:52:04 +02:00
Marc-André Bombeck 00f6eb6dcb test(measurements): mock the status re-warm where the mutation tail imports it
The bulk-delete, restore and by-external-ids suites mocked
`invalidateStatusInsightsForTypes` on the comprehensive-generate barrel,
while the shared post-mutation tail imports it from status-invalidation.
The mock was never called, the real re-warm ran the capability loader
against a stub database, and the "no invalidate" assertion could not
fail. The mock now sits on the imported module; the positive cases
assert the re-warm with the distinct types, the zero-row cases assert
its absence.
2026-09-24 10:52:04 +02:00
Marc-André Bombeck 863d32af5a test(ai): refuse feature-flags mocks that leave the loader's reader out
A structural check over src/ and tests/: every `vi.mock` / `vi.doMock`
of `@/lib/feature-flags` either uses the shared switches factory or
names `loadAssistantSwitches`. The matcher is whitespace-tolerant,
asserts a non-zero match count, and checks itself against planted
one-line, split, automock and `import()` forms.
2026-09-24 10:52:04 +02:00
Marc-André Bombeck 2c4dec08f1 test(ai): answer both switch readers from one source in flag mocks
Eight files mocked `@/lib/feature-flags` with `getAssistantFlags` alone.
The capability loader reads `loadAssistantSwitches`, so wherever it ran
it threw and every capability resolved to `check_failed`. A shared
factory now points both readers at the function the test drives.

Only the config-change chain reached the loader. Its fixture means AI
switched off by the operator; it now supplies the loader's other inputs
and asserts `operator_disabled` on the digest, so a starved loader turns
it red instead of passing on the failure path.
2026-09-24 10:52:03 +02:00
Marc-André Bombeck 48bfc1f987 refactor(navigation): name the full-document loads the client router cannot serve
Nine places assigned window.location.href directly: OAuth connects and
sign-in hand-offs that land on API routes answering with a redirect, and
the reload after account deletion. The newer Next lint rule reads each as
an in-app page change. They now go through one helper that says why a
document load is the right tool there.
2026-09-24 10:37:21 +02:00
Marc-André Bombeck c2005fd8f1 test(sharing): read the real assistant switches in the provider-origin checks
The file stubbed the old switch reader only, so the capability loader
failed and every capability resolved closed. The owner's positive control
then enqueued nothing, and the delegate's negative passed without a
provider on the record, proving nothing. The record and the owner now
carry a provider and consent, so the delegate case refuses for the
reason it names.
2026-09-24 10:32:41 +02:00
Marc-André Bombeck 9c7ddc13b3 Merge branch 'feat/ai-routes-insights-coach' into release/v1.39.0
# Conflicts:
#	src/app/api/insights/correlations/__tests__/route.test.ts
#	src/app/api/insights/correlations/route.ts
2026-09-24 10:26:56 +02:00
Marc-André Bombeck 3662d5139e chore(ai): drop the switch type import the retired gate left behind 2026-09-24 10:25:45 +02:00
Marc-André Bombeck d421aca7a1 Merge branch 'feat/module-surfaces' into release/v1.39.0 2026-09-24 10:23:25 +02:00
Marc-André Bombeck d8dc6ca8a7 fix(settings): answer a switched-off layout subpage with the module notice
/settings/layout/<module> is a URL a person can land on, so with its
module off it now shows the module notice in place, like every module
page, instead of bouncing to the Layout hub without saying why.
2026-09-24 10:18:04 +02:00
Marc-André Bombeck 5bd19573ea fix(insights): pass the record's module map to every correlation scan
The Coach correlations tool, the per-metric card and the period
narrative scanned every channel, so a switched-off module still fed
their statistics and the text a model was grounded on. The matrix's
modules option is now required, each caller resolves the record's map,
and the Coach skips the lab pass with labs off. A registry guard holds
every caller to resolving the map itself.

The mask's doc comment now states what it does to the false discovery
correction: fewer channels is a smaller family, so q-values of the
remaining pairs move and a borderline pair can cross the threshold.
2026-09-24 10:17:14 +02:00
Marc-André Bombeck 2143445da2 feat(ai): show stored model text inside a shared record as the owner would
Serving stored text and starting model work are separate questions. A
delegate may not start model work on somebody else's record, but reads
the owner's stored briefing, period narrative, status notes, workout
notes and Coach unread signal exactly when the owner would: those
readers now resolve the record's own capability state, not the
viewer's. Generation, warms and enqueues still ask as the viewer, so a
delegate's read of a stale narrative queues nothing. A hidden
model-written narrative is no longer overwritten by a deterministic
warm while AI is unavailable.

The sharing front door reads the digest's briefing lead again, and an
integration case pins both halves.

Refs #975
2026-09-24 10:17:00 +02:00
Marc-André Bombeck 7df260d62e fix(daily): send the morning briefing push with AI analysis off
The push refused outright while the `insights` module was off, which
now means only "AI analysis". The digest it reads already drops the
model-written lead and top signal in that case, so the push goes out
with the deterministic line (the score, or the day's items) and a
digest with nothing to say is still skipped. The `module-off` outcome
and its counter are gone.

Refs #975
2026-09-24 10:17:00 +02:00
Marc-André Bombeck c509afeb2e Merge release/v1.39.0 into feat/ai-routes-insights-coach
Brings in the jobs, stored-text and consent package and the extraction
routes. Conflicts resolved:

- The digest keeps its capability-driven reaction line and check-in,
  now through the shared `aiCapabilityForRecord`; the local copy of it
  is removed.
- The route inventories classify the extraction routes (documents,
  labs OCR, medication text, fenced chat and attachments) as actions;
  a capability call counts as the gate for the module inventory.
- With every caller moved, `requireAssistantSurface` and
  `AssistantDisabledError` are deleted. The `assistant.disabled.*`
  codes stay on the capability refusal, and the guard now asserts the
  retired gate is gone.
- `aiCapabilityToServe` answers whether stored model text may be shown
  from the record's own state, apart from who is reading.

Refs #975
2026-09-24 10:16:53 +02:00
Marc-André Bombeck ab0d1b4b71 Merge branch 'feat/module-surfaces' into release/v1.39.0 2026-09-24 10:10:11 +02:00
Marc-André Bombeck 1f7a52cd7a test(nav): name the surface map in the cycle entry's comment 2026-09-24 10:09:35 +02:00
Marc-André Bombeck 8eff500e9d test(e2e): prove a switched-off module leaves every surface it owns
A journey on its own account switches mood and medications on, proves
the Mood nav entry, the Mood and Medications pills, the mood trends slot
and both add-menu entries are there, switches both off through the
module route and proves each is gone, the trends row fills from pulse,
/insights/mood shows the module notice at the same URL, and no chart on
the way paints its error state.
2026-09-24 10:06:14 +02:00
Marc-André Bombeck 126c80cbc4 chore(i18n): drop the nutrients enable-error string no page shows any more 2026-09-24 10:06:14 +02:00
Marc-André Bombeck 72f0eccf27 test(weight): read the target cases through the status note table 2026-09-24 10:00:05 +02:00
Marc-André Bombeck 347e63d653 fix(dashboard): keep the derived score rings with AI analysis off
The hero rings read their owner from the surface map instead of their
own map, and the readiness, recovery and sleep score rings no longer
wait on the AI analysis switch: they are computed scores, not model
text. The dose ring still follows the medications module.
2026-09-24 09:58:27 +02:00
Marc-André Bombeck 2594045bef test(modules): hold every surface list against the surface map
Each family of ids must name a surface that exists (nav hrefs, sub-page
directories, section ids, widget ids, derived ids, Settings slugs,
correlation channels). Sub-pages, trend slots and correlation channels
must follow the owner of the types they plot, joined against the
dashboard's summary owners, and a pinned table covers the owners no
join can derive. The replaced per-surface keys and the redirecting page
guard are searched for in source, and the derived route's gate is
compared with the map entry by entry.

Broken on purpose before committing: dropping the sleep sub-page entry,
the mood trend entry or a nav entry, drifting a derived owner, and
reintroducing a per-destination key each fail by name.
2026-09-24 09:56:50 +02:00
Marc-André Bombeck 8ae0f75ecd fix(insights): leave switched-off modules out of the correlation statistics
The correlation scan still paired mood, sleep, glucose, adherence,
symptoms and weather with everything else after their modules were
switched off. The discovery matrix now drops every channel whose module
is off, read through the surface map, and the correlations route passes
the record's module map, skips the lab draws with labs off, and keys its
cache on the switched-off set.
2026-09-24 09:54:25 +02:00
Marc-André Bombeck e89f41710a Merge branch 'feat/v139-targets-and-links' into release/v1.39.0 2026-09-24 09:53:41 +02:00
Marc-André Bombeck 9f98636a43 fix(settings): read section and overview-block owners from the surface map
Settings sections and Layout groups no longer declare their own module
keys; they ask the surface map. The Insights overview arrange list marks
the breathing, labs changes and cycle blocks unavailable when their
modules are off, as the overview itself would not show them. The rows
stay in the list so a save keeps each block's place.
2026-09-24 09:51:55 +02:00
Marc-André Bombeck 81cb6aa63d fix(insights): let the trends row fill a switched-off module's slot from the next metric
selectTrendCharts takes the record's module map and skips every slot
whose module is off, on the briefing path and on the fallback row,
through the surface map. Sleep was never covered before, and the
fallback row shrank to two charts with mood off; it now reaches for
pulse. The row reads the module map itself.
2026-09-24 09:50:12 +02:00
Marc-André Bombeck 74154460fd fix(insights): hide the Medications and recovery metric pills with their modules off
The tab strip's slug map is gone; every pill asks the surface map by its
slug, the same entry the page notice reads. That adds the Medications
pill and the cardio recovery, six-minute walk and stair speed pills,
which stayed visible with their modules off.
2026-09-24 09:48:48 +02:00
Marc-André Bombeck 39ae034b8c fix(modules): route nav entries and module pages through the surface map
Navigation destinations, the bottom bar's fixed slots and the tour stops
no longer carry their own module keys; each asks the surface map by its
href. Insights has no owner there, so switching AI analysis off leaves
the Insights entry, slot and tour stop in place.

The shell's page gate now resolves Insights sub-pages by slug as well
as top-level pages, so /insights/mood, /insights/medications and the
recovery metric pages show the module notice when their module is off,
worded from the access reason, with the Settings link only for the
record's own switch. The per-page redirect guard, the achievements
redirect and the nutrients page's own notice are gone; nothing
redirects any more.
2026-09-24 09:48:12 +02:00
Marc-André Bombeck a4f8e6db27 fix(capture): leave Mood and Medication out of the add menu with their modules off 2026-09-24 09:48:05 +02:00
Marc-André Bombeck 15d6251ad2 feat(vaccinations): show the planned booster's renewal state on the log
Whether a vaccination is still current was known only on the checkups
page. The vaccination log now shows it on each antigen's heading:
the booster the person planned when they logged a dose, marked as
overdue, due soon (within 30 days) or scheduled, tinted only in the
first two cases.

The state is resolved on the server from the person's own confirmed
booster reminder and published on the list response as renewals, so
the web page and the native client read the same answer. Nothing is
worked out from age, history or the catalogue: an antigen without a
planned booster shows no state. Renewals are null for a grant that does
not reach the measurements section the reminders live in.

Refs #1005
2026-09-24 09:44:51 +02:00
Marc-André Bombeck 94e07d0d90 fix(dashboard): hide a switched-off module's widgets on every feed
The dashboard widget and summary maps are now views of the surface map.
The legacy dashboard feed painted the stored layout as saved, so the
medications card stayed with the module off; the mask the snapshot
applies now runs on that feed too, in the browser, from the same map.
The widgets route keeps returning the stored layout unmasked, because
Settings saves that value back.

The Today digest is the day's data and no longer waits on the AI
analysis switch, on the server prefetch or in the browser.
2026-09-24 09:42:17 +02:00
Marc-André Bombeck 91be6b2967 feat(modules): add one map from every surface to the module that owns it
SURFACE_MODULE names each surface a toggleable module owns (nav entries,
Insights pages, overview blocks, trend slots, add-menu entries, dashboard
widgets and summaries, derived scores, Settings sections, correlation
channels) as <kind>:<id>. isSurfaceVisible answers from it on the server
and in the browser, useSurfaceVisible reads it against the account.

The insights key owns no surface: it means AI analysis, and the Insights
area is data.
2026-09-24 09:39:58 +02:00
Marc-André Bombeck b480ac4543 feat(documents): link a document to visits and vaccinations from its own sheet
A document could show its visits read-only and its vaccinations not at
all, so a childhood record covering a dozen doses had to be attached
from a dozen dose forms. The document's detail sheet now lists the
visits and vaccinations it is filed against and, for someone who may
manage the vault, links and unlinks them in one place, with the records
dated near the document on top. Both ends write the same link tables
through the link service, so the dose's form and the document's sheet
cannot disagree about what is filed where.

The document detail response carries the linked doses, named by
catalogue slug or the person's own wording. It is null rather than
empty for a grant that opens the vault but not the health background,
so a shared page never claims to record no doses. The update route
takes a replace-set of vaccination ids, up to 100 so one record can
cover a whole primary schedule; ownership is re-checked, a foreign id
answers 404 and the change lands in the audit log beside the other link
fields. Linking from the dose suggestion now refreshes the sheet.

Refs #1024, #1005
2026-09-24 09:39:27 +02:00
Marc-André Bombeck 1f6a13e2f7 feat(ai): answer the status notes with a null note when AI is unavailable
The status family (the five metric cards, medication compliance, the
generic metric status and the biomarker assessment) asked the retired
switch and the `insights` module and refused with 403. The note is model
text and the card around it is data, so they are mixed reads now: while
the `statusText` capability is available the note is served and warmed
as before, with `ai` beside it; otherwise the answer is 200 with the
note null, `preparing: false`, `hasProvider` as provider presence only
and `ai` naming the reason, and neither the cache nor the warm queue is
touched. The generic metric status still reports `insufficient` from the
data. The mood card keeps its mood module gate.

Kept apart so it can be held back while the shipped iPhone app's
rendering of a 200 without a note is confirmed.

Refs #975
2026-09-24 09:30:23 +02:00
Marc-André Bombeck c9534b343e Merge branch 'feat/ai-jobs-stored-text' into release/v1.39.0 2026-09-24 09:29:54 +02:00
Marc-André Bombeck ce72fe226e refactor(ai): re-check every chokepoint through the one egress helper
The status chokepoint, the comprehensive briefing, reaction lines and
AI-composed nudges now ask `aiEgressRefusal` about exactly the chain they
are about to send to, instead of each pairing the operator-key check
with a surface receipt lookup of its own. The consent kinds come from the
capability table, so the wire and the published capability answer from
the same rule.

The document summary, its catch-up pass and the index backfill stop on a
closed switch or module before anything is picked, and leave "no
provider" and "consent needed" to the document pick, which re-checks the
wire for the provider it chose. A closed switch still only heals PENDING
to NONE; a withheld pick records UNAVAILABLE. The per-pick document
consent helper is removed, since nothing calls it any more.

The auto-read toggle mints the shared `AI_EXTRACTION_CONSENT_KIND`, and
the web grant helper goes back to minting the master grant only.

Refs #975
2026-09-24 09:29:00 +02:00
Marc-André Bombeck f46ed99def fix(links): offer the whole vault when linking a document to a record
The visit and vaccination forms asked the document list for a page of
200 while the route accepts at most 100. The refusal read as an empty
list, so the picker said "No documents yet." to anyone with a full
vault, and the only way a scan reached a dose was the seven-day
suggestion offered at upload. The visit form's condition picker had the
same problem against the episode list.

The document pickers now walk the vault page by page at the route's own
limit, so any document can be linked from a vaccination or a visit, and
one document can sit on as many records as it covers. Documents dated
within seven days of the record stay on top under their own heading,
the rest follow by month and are searchable. A failed read now shows an
error with a retry instead of passing for an empty list.

Refs #1024, #1005
2026-09-24 09:28:41 +02:00
Marc-André Bombeck f158f01f18 Merge branch 'feat/ai-extraction-routes' into feat/ai-jobs-stored-text
Brings in the extraction routes and the capability re-check at the wire
(`aiEgressRefusal`), so the jobs and stored-text work can share it.
Conflicts in the document routes, the fenced chat, the auto-read toggle
and its contract text resolve to the extraction branch: those files no
longer call the per-pick document consent helper.
2026-09-24 09:27:43 +02:00
Marc-André Bombeck 8f889cf942 feat(weight): give the weight status note the stored target
The weight status note's snapshot now carries the person's own target
band and which way is progress, and its comparison signal is framed as
higher-better below the band and lower-better above it instead of the
neutral target-band framing. The weight prompt tells the model to judge
changes against that target and keeps the loss pace and milestone
guidance for when losing is the goal. The target is folded into the
input fingerprint, so editing it regenerates the note even when no
weight reading moved.

Refs #1006
2026-09-24 09:24:25 +02:00
Marc-André Bombeck 9f1d1341f9 test(ai): state the mutation checks the AI route tests were run against 2026-09-24 09:22:50 +02:00
Marc-André Bombeck 1273a76a63 feat(weight): judge the weight trend against the stored target
The weight tile's arrow, 7-day delta and comparison caption were wired
as "up is bad", so a person below their own target who was gaining saw
every step toward it coloured as a setback. Movement is now judged
against the target they entered: below the band a gain is progress,
above it a loss is, and inside it holding steady is, with a move either
way shown neutral rather than orange. Without a stored target the tile
reads exactly as before; the height-derived band is not treated as a
target because nobody chose it.

The direction is resolved once on the server and published on the
dashboard snapshot as tiles.weightTrend, so the web tile and the native
client colour the same reading the same way. The personal-record
direction reads the same placement helper. The feature payload behind
the briefing, the overview analysis and the Coach now carries the
target band and which way is progress, so a narrative no longer calls a
gain a regression when gaining is the goal. The insights vitals grid
drops weight from its fixed "up is bad" set.

Refs #1006
2026-09-24 09:22:50 +02:00
Marc-André Bombeck ce5a340931 test(ai): prove Insights data, mixed reads and actions against Postgres
Three files walk the AI state matrix through the real handlers: every
data route answers the baseline's data under each state, and an ECG
upload is stored with AI off; mixed reads null the model text, name the
reason and enqueue nothing, and the dashboard hides a cached briefing on
the next read after a switch flip; the briefing and Coach actions refuse
with the exact code, capability and reason before any provider or cache
write. Existing files that seeded provider-less accounts now give them a
provider where the briefing or the Coach is under test, and the sharing
front door marks the digest by a due checkup, since model text is not
served inside somebody else's record.

Refs #975
2026-09-24 09:19:43 +02:00
Marc-André Bombeck 3309ac177c feat(ai): serve Insights and Coach data whatever AI says
Data never depends on AI. The Insights data reads no longer ask an AI
switch or the `insights` module (now only the AI analysis opt-out): ECG
list, detail and upload, rhythm events, derived scores, rule cards,
correlations and patterns, the baseline strip, health status, intraday
pulse, and the Today digest with its dismiss. Breathing screening moves
to the sleep module and lab changes to the labs module. Stored Coach
facts, conversations, message ratings and the seen stamp stay readable
and erasable while the Coach is unavailable. Cards now say
`provider: "rules"`.

Reads that mix data with model text answer 200, null the model text
and publish an `ai` state from the capability resolver, without warming
anything: comprehensive (`ai.briefing`, `ai.statusText`, `hasProvider`
from the presence probe), the derived assessment override, the period
narrative, nudge status, the seeded opener, about-me questions, the
workout paragraph, the pregenerate warm (`queued: false`), the Today
digest (lead, reaction line, check-in) and the dashboard briefing,
which is now applied per read after the snapshot cache. Hiding the
Coach no longer hides the briefing.

`insights/generate` GET and POST ask the `briefing` capability and
`insights/chat` POST the `coach` capability, with the typed refusal
envelope; a missing provider keeps the chat's `coach.provider.none`
frame and adds `reason`. The /coach page, the MCP ECG and intraday
tools and `aiAvailable` on the provider route follow the same answer.

An inventory of AI and data routes replaces the Coach gate inventory:
every route that asks a capability names it, and no data route asks.

Refs #975
2026-09-24 09:19:36 +02:00
Marc-André Bombeck 3917a2face feat(ai): resolve the AI capability before any background model work
Every AI job now asks its capability for the user before it builds a
snapshot, and skips with a `.skipped` annotation naming the reason: the
nightly pregenerate (briefing and statusText, each half on its own), the
status batch and the per-metric crons, the on-demand status worker, the
narrative cron, Coach nudges and their AI composer, the Coach memory
refresh, reaction lines, workout paragraphs, and the document summary,
catch-up and index jobs. Seven of these read no assistant switch at all
before, so the master switch now stops them too.

The cron candidate queries drop people who switched AI analysis off in
SQL, and no longer read `disableCoach` outside the Coach: hiding the
Coach hides the Coach. Coach nudges use the one presence probe, so a
central Codex account is no longer skipped; a missing consent still gets
the deterministic template. The arrival spine asks only the
provider-free half (switches and modules) before it enqueues, keeping
its module graph free of provider code.

Document reading needs an extraction receipt (ai_extraction or ai_full)
for any external provider; the auto-read toggle is the trigger, no longer
a consent shortcut, so a revoked receipt wins over a toggle left on. Lab
report scans get the same rule for a whole chain.

Two structural guards: every file that calls a provider is named with
the reason its call is admitted, and the chokepoints re-check a
capability; every AI job references its capability gate. An integration
matrix runs each worker under the refusing states with a provider spy.

Refs #975
2026-09-24 09:07:16 +02:00
Marc-André Bombeck b36c7b6697 feat(insights): serve status notes from the new table, only while available
Every status note reader and writer moves to InsightStatusCache: the
generators, the unchanged-data gates, the stale-while-revalidate read,
the ingest debounce, the previous-note prompt block and the
medication-compliance card with its per-medication lines. A stall now
opens a negative-cache window next to the note instead of a stub row
that shadowed it.

Stored model text is never served while its capability is unavailable,
whatever the reason: the status readers and gates check statusText, the
period narrative hides a model-written row while periodNarrative is
unavailable (the deterministic narrative is data and always shown), and
the daily digest drops reaction lines while reactionLines is
unavailable. A read-only miss now reports why (`unavailable` with the
capability's reason) and keeps hasProvider meaning provider presence, so
a withdrawn consent no longer reads as "no provider".

runStatusCompletion takes the capability as a required argument and
re-checks it before the provider chain is resolved, so a job queued
before a switch flipped still stops at the wire. The comprehensive
briefing re-checks briefing the same way. hasUsableStatusProvider is the
one presence probe.

Refs #975
2026-09-24 09:06:22 +02:00
Marc-André Bombeck 0c3195fd41 Merge branch 'feat/ai-extraction-routes' into release/v1.39.0 2026-09-24 09:05:54 +02:00
Marc-André Bombeck 8325f3964d feat(consent): add the extraction consent kind and purge on withdrawal
A new receipt kind, ai_extraction, covers reading documents, lab report
scans and typed medication text with an external model. Switching the
document auto-read on now mints ai_extraction instead of ai_full, so it
no longer grants the Coach or the analysis as a side effect. Existing
ai_full receipts keep covering everything.

DELETE /api/consent/ai/latest now runs through withdrawConsent: the
revoke and, when it leaves no receipt covering the analysis, the
deletion of the text a model wrote under it commit in one transaction.
That is the status notes, the cached briefing, model-written period
narratives, reaction lines and workout paragraphs. Coach conversations,
facts and plans and document summaries stay. The purge is audit-logged
as consent.ai.purge with counts only.

Refs #975
2026-09-24 09:05:09 +02:00
Marc-André Bombeck 2710dfc041 feat(insights): add an encrypted table for status notes
Status notes (the per-metric text a model writes) move out of audit_logs
into InsightStatusCache: one row per user, metric and locale, the note
encrypted at rest, upserted in place, with the input and snapshot
fingerprints and a separate negative-cache window.

Migration 0344 creates the table and deletes every audit_logs row whose
action matches insights.%-status.%. The notes are a regenerable cache and
the old rows are plaintext, so nothing is copied; the first nightly run
after the upgrade writes them again. Take a backup before applying.

The table is registered for key rotation, excluded from backups as a
regenerable cache, and deleted by Delete All Data.

Refs #975
2026-09-24 09:03:58 +02:00
Marc-André Bombeck b0bbd344a3 style: format the extraction capability suite 2026-09-24 08:51:52 +02:00
Marc-André Bombeck 059da3ceb0 test(ai): state the mutation results the extraction suite was run against 2026-09-24 08:50:17 +02:00
Marc-André Bombeck 660351be3a test(ai): prove the extraction capabilities against Postgres with a model spy
Each refusal is checked twice, at the response and at a spy standing in
for every model call, beside an all-open twin in which the spy is called.
Two background cases run the index and summary job handlers directly and
show that a job enqueued before document reading was turned off finds no
provider when it runs.
2026-09-24 08:47:35 +02:00
Marc-André Bombeck 005f645b8b docs(api): describe the extraction capability refusals
The document, labs-scan, medication-extraction, fenced-chat, attachment,
connection-test and auto-read operations document the capability they
answer under, the refusal envelope and codes, and the consent rule. The
two capability probes publish the capability beside the provider answer.
2026-09-24 08:45:06 +02:00
Marc-André Bombeck d239d31311 feat(ai): narrow the auto-read consent and refuse the connection test with AI off
Turning document auto-read on now mints an ai_extraction receipt instead
of ai_full, so it covers reading documents, lab reports and medication
text and no longer opens the Coach or the AI analysis. Receipts minted as
ai_full by earlier releases stay valid. The catch-up over stored
documents is only scheduled while documentAi is open for the record.

The AI connection test is an AI call, so it is refused with
assistant.disabled.enabled while the operator's master switch is off, and
fails closed with ai.unavailable when the switches cannot be read (403,
since the route never answers 5xx). A missing provider carries
ai.provider.none and a spent daily budget ai.budget.exceeded.
2026-09-24 08:45:03 +02:00
Marc-André Bombeck bd8ea9d86b feat(ai): gate document, lab and medication extraction on their capabilities
Reading a stored document (suggest, summary, extract, index, chat,
reindex), scanning a lab report and turning medication text into a
schedule now answer under documentAi, labsOcr and medicationExtract. The
operator's master switch and the new reading-documents switch stop the
work and the egress; a module off for the record, a delegate inside
somebody else's record, and a missing receipt refuse with the capability
envelope. Existing no-provider codes keep their status.

The document pick and the labs pick re-check the capability for the
provider they picked, immediately before anything is sent, so a job
enqueued before a switch flipped finds no provider and falls back to the
provider-free text layer. Consent follows the document rule for all
three: any provider that leaves the machine needs an ai_extraction or
ai_full receipt, answered for the provider actually picked.

The fenced Coach chat and attachments answer under coach and documentAi.
Uploads are always stored and indexed; the background summary is only
enqueued while documentAi is open. The capability probes report the
capability beside the provider answer and keep a read offered when only
the receipt is missing. medications/extract keeps its 503 for no provider
and adds ai.provider.none, and its budget refusal gains the
coach.budget.exceeded code.
2026-09-24 08:44:57 +02:00
Marc-André Bombeck a19900c854 feat(ai): re-check a capability at the wire
requireAiCapability answers at the top of a route, before a provider is
picked, and a job enqueued before an operator switch flipped runs long
after any route answered. aiEgressRefusal asks again about the providers a
caller is about to send to: the capability for the record (the request's
own resolution, or the job's for the record it names) and, for exactly
those providers, whether a consent receipt of the kinds the capability
table declares is active.

A pickDecides gate option leaves no_provider and consent_required to that
pick, for routes that read the chain in their own order.
2026-09-24 08:44:49 +02:00
Marc-André Bombeck c3ec437cad Merge branch 'fix/v139-server-bugs' into release/v1.39.0 2026-09-24 08:21:55 +02:00
Marc-André Bombeck 16ef75e729 fix(charts): cut days in the account's zone when a mount passes none
Several chart mounts (the medications page, the coach chat, the
recovery section) pass no zone, and the chart then fell back to a fixed
Europe/Berlin, so those charts cut and labelled days in Berlin for
every user whatever their profile said.

The chart now falls back to the signed-in account's zone, and only
before that has loaded to the shared DEFAULT_TIMEZONE the server's own
resolver ends on. /api/auth/me reports the zone the server resolves:
the stored one, or the instance default when the stored one is
unusable, so the client cuts days where the server does.

Refs #1026
2026-09-24 08:15:16 +02:00
Marc-André Bombeck 352de95854 Merge branch 'fix/v139-ui-bugs' into release/v1.39.0 2026-09-24 08:12:51 +02:00
Marc-André Bombeck 3170a622d1 fix(medications): report the dose-history window doses were read over
The dose-history response reported the slot window: `from` clamped
to the medication's creation, `to` the request's end. Recorded doses
are now read from the requested start and, for a dose recorded ahead
of its slot, up to that slot, so the response reported a narrower
window than the rows it carried.

`from` and `to` now report the window recorded doses were read over.
Both fields keep their shape; the OpenAPI descriptions say what they
mean.

Refs #1028
2026-09-24 08:12:23 +02:00
Marc-André Bombeck b77dbea6b1 fix(cycle): reopen a re-tapped start that has nothing after it
The earlier rule could leave a one-day cycle in front of a real start
when day two of a period was logged before day one. Tapping "My period
started this day" on the real first day folds the later start in, but
the re-tapped row kept the end date and length its vanished successor
had given it, so the repaired cycle stayed closed after one day.

A start with no cycle after it is open, so opening one now clears a
stale end and length. The repair of such a history is covered end to
end: the broken state is seeded as the old rule left it, the one tap
is made through the period route, and the result is a single open
cycle that owns every day of the period.
2026-09-24 08:11:14 +02:00
Marc-André Bombeck c41df33dd3 fix(cycle): read the phase crosstab as per-source day aggregates
The coach's cycle snapshot read a year of raw readings for the phase
crosstab, including steps, heart-rate variability and CGM glucose. On a
CGM account that is over 100 000 objects per snapshot.

The crosstab only uses each day's sum and count after picking one
source and device per day, and the pick depends only on which sources
and devices are present. readSourceDayAggregates returns one row per
type, day, source and device, and the day map now carries each row's
reading count, so the day values are the ones the raw readings give.

The 30-day clinical glucose reads stay raw: time in range, SD, J-index
and the risk indices are functions of individual readings, and a
sensor's rate bounds the window below 45 000 rows.

Refs #1023
2026-09-24 08:06:47 +02:00
Marc-André Bombeck 2f5d58dad2 fix(charts): read the 7-day range as daily rows
On a per-minute heart-rate stream the 7-day chart showed only the first
half of the week. The range read raw rows oldest-first under a
5000-row limit, and seven days of per-minute samples are 10 080 rows,
so the newest days never arrived.

The chart folds every range into days anyway, so the 7-day range now
asks for one row per local day like the longer ranges. The whole week
arrives whatever the sampling rate, and the 7-day and 30-day ranges
share one day boundary and one source pick per day. The 7-day range
still draws no spread band, so its picture is unchanged.

Refs #1026
2026-09-24 08:03:04 +02:00
Marc-André Bombeck e0b547a430 fix(measurements): offer every body-composition reading in the manual form (#1013)
The manual form keeps a hand-written type list, and the server's grew
past it: visceral fat, fat mass, fat-free mass, lean body mass and
muscle mass all had units and plausibility ranges on the server and
arrived from scales, but had no row to type a reading into. They have
rows now, with the scale's kg and lb units and a "rating" unit for
visceral fat in every language.

A new test derives the body-composition family from the server's own
categories and fails when a type in it is neither offered by the form
nor named with the reason it is left out (BMI, which is computed from
weight and height). It also checks each row's unit and placeholder
against the server.

Listing the four side by side exposed labels that named two different
readings with one word in French, Italian and Polish (body fat and fat
mass, fat-free and lean mass). Each now has its own name, which also
makes them resolvable by name for the MCP reads that used to refuse the
ambiguous words.
2026-09-24 08:02:11 +02:00
Marc-André Bombeck cb12882aff fix(labs): keep the biomarker picked after "Save and add another" (#1029)
The reset after "Save and add another" cleared the biomarker and passed
the picker `undefined`, which switched it to its own internal state. It
went on showing the marker it last held while the form value was empty,
so the next save refused with "Pick a biomarker first" under a visibly
picked marker, and a later pick could land on the first catalogue entry.

The picker is always controlled now (an empty pick shows the
placeholder), and "Save and add another" keeps the marker, the draw date
and the visit, clearing only the reading, its note and its printed
range. Focus moves to the value field for the next entry.
2026-09-24 08:02:11 +02:00
Marc-André Bombeck e9e060083c fix(cycle): list symptoms one per line with the intensity beside them (#1001)
Selecting a symptom grew its chip inline with the 1-4 intensity
selector, which reflowed the wrapping row and moved the chips after it,
often out from under the finger reaching for the intensity. Each symptom
is now its own row: the toggle on the left, the intensity on the right.
The intensity's space is laid out whether or not it is shown, so a
selection changes colours and reveals it in place and nothing moves.
The intensity stays optional and out of the tab order until the symptom
is picked. Long names wrap instead of truncating.
2026-09-24 08:02:10 +02:00
Marc-André Bombeck 7d25bb7352 fix(cycle): log past dates as themselves, in any order (#1004)
The log sheet took its "Day N" header and its "period ended" button
from the verdict, which is the answer about today. A January date opened
in September read "Day 2", and a back-dated period could only be closed
on dates where today happened to be a bleeding day, so the button came
and went as unrelated months were filled in.

The calendar read now carries, per date, the cycle day of the logged
cycle that date belongs to (null before the first start, after today, or
past the verdict's ceiling for an open cycle) and whether a one-tap
period end can land there. The sheet reads both off the grid day for the
date it opened on.

Saving a new entry with nothing picked used to write an empty row: the
request succeeded, the sheet closed and the calendar had nothing to
draw, which read as a save that did nothing. Save now needs something to
store and says what, and an emptied existing entry still saves. The
sheet also stops writing until the opened date's own entry has loaded,
because until then it held the previous date's row id and a quick Save
patched the wrong day.

On the server, a start recorded a few days after an earlier one is the
same period entered in the other order: opening the earlier start now
folds the later one into it instead of leaving a one-day cycle in front
of it, and a bleed too far before the next start to be its first day and
too close to be a cycle of its own no longer infers a start. Opening or
removing a start re-attributes the day-logs whose cycle changed.
2026-09-24 08:02:00 +02:00
Marc-André Bombeck f434ba7d29 test(ai): follow the retired Correlations switch and the closed default
The Coach gate inventory lists the correlations route with the routes
no assistant switch owns. The seeded-question test gives the switch
read a settings row, since a read that fails no longer opens every
switch.
2026-09-24 07:59:49 +02:00
Marc-André Bombeck 5a0b6ee153 fix(insights): fold dense measurement reads per day in SQL
A single account syncing heart rate from a watch took the worker down
within half an hour. The status cards' graded series read the last 91
days of raw rows, bounded in time but not in rows, so a stream sampled
every minute or faster materialised six or seven figures of objects on
every refresh and the read ran into the statement timeout.

Add readDayAggregates, which folds one type into per-day sum, count, min
and max in Postgres (optionally split into age segments and filtered to
the metric's plausibility domain), and move the readers that folded raw
rows into days in memory onto it: the graded series (recent, weekly and
the cold-tier fallback, for every type), the vitals day-mean fallback
behind the personal band, the tiered context's recent days and the plan
review. Recent, weekly and monthly buckets are identical to the raw
fold; the cold-tier yearly slope now runs over day means.

On 91 days of per-minute pulse the graded series now allocates 1.6 MB
where it allocated 62 MB, while the raw read alone holds 22 MB.

A structural guard freezes the remaining untaken measurement reads in
the worker and insight directories: each must name a sparse literal
type or carry a listed reason.

Refs #1023
2026-09-24 07:56:39 +02:00
Marc-André Bombeck 88cea09c7b fix(measurements): cut chart day buckets at the user's midnight
Switching a chart from 7 to 30 days moved steps, active energy,
flights and distance totals onto neighbouring days. The 7-day range
buckets raw rows by the user's calendar day; the 30-day range read the
DAY rollup tier, whose buckets are UTC days, and the chart labelled each
bucket's UTC-midnight start in the user's zone. East of UTC a sample
shortly after local midnight counted on the previous day; west of UTC
every bucket read one day early.

The daily series (the chart read and the batched dashboard read) and the
aggregate=daily|weekly|monthly list now fold live in the user's zone and
return the instant of local midnight, so every range and every summed
metric shares one day boundary. The fold runs in Postgres and returns
one row per day; about 0.1 s for 90 days of per-minute samples. Windows
longer than the DAY cap still step up to the coarser rollup tiers.

Refs #1026
2026-09-24 07:56:33 +02:00
Marc-André Bombeck fccc44f7f1 test(ai): run the 0343 data steps against seeded rows
The Coach availability fold and the AI analysis carry-over for people
who hid the Coach are read out of the migration and run twice against
rows shaped like an upgrading instance, including a malformed
preference blob and the concurrency token.
2026-09-24 07:54:59 +02:00
Marc-André Bombeck b7a72489ed test(ai): pin the account payload's capability block against Postgres
Each state changes one layer against a fully set-up account and checks
the capabilities it owns: master switch, Reading documents, no
provider, the operator's key with and without consent, hiding the
Coach, the AI analysis opt-out, the workouts module, the single Coach
switch, a delegate, and a guardian limited to the operator's key.
2026-09-24 07:53:28 +02:00
Marc-André Bombeck cc4934897c docs(api): describe the AI capability block and refusal meta
AccountPayload gains ai with the AiCapabilities, AiCapabilityState,
AiUnavailableReason and AiProviderState components. The feature-flags
route is marked deprecated, drops correlations and documents
documentAi. The error envelope's meta documents capability, reason and
module, lists the assistant.disabled switches, and the catalogue
carries the three new ai codes.
2026-09-24 07:51:16 +02:00
Marc-André Bombeck 464522f315 feat(ai): publish capabilities on the account payload
GET /api/auth/me gains ai: the state of every capability and the
provider block, resolved for the active record and masked to the
grant like moduleAccess. The authority comes from the switch the
payload already resolved, so a delegate reads not_permitted_for_record
and a guardian is limited to the operator's key.

useAiCapability is the web reader and fails closed until the payload
arrives. GET /api/feature-flags becomes a deprecated projection of the
operator switches with a Deprecation header and a link to its
successor.
2026-09-24 07:49:14 +02:00
Marc-André Bombeck 7c757520f1 feat(ai): capability loader, gates and refusal envelope
loadAiCapabilityInputs reads the switches, module access, provider
presence and active consent kinds for one record in parallel, memoised
per request, and fails closed to check_failed. requireAiCapability,
getAiCapability and aiCapabilityForJob resolve for the request's
record, masked to the active grant like moduleAccess, or for a job's
record under the worker's authority.

apiHandler renders AiUnavailableError as one envelope with errorCode,
capability, reason and module. Existing codes stay: the operator
family keeps assistant.disabled.<switch>, modules keep module.disabled,
consent keeps consent.ai.required. New codes are ai.record.notPermitted,
ai.provider.none and ai.unavailable.
2026-09-24 07:46:12 +02:00
Marc-André Bombeck 1be2392c81 feat(ai): one provider presence probe
probeProviderChain describes the chain that would serve a record
without decrypting, building a client or refreshing a token: which
entries hold a credential, in chain order, whether each reads images,
the in-browser OCR opt-in, and where the credential comes from. It
applies the provider-work authority, appends the central Codex only
behind the opt-in, and falls back to the legacy provider only for an
empty chain. hasAnyConfiguredProvider and resolveProviderAvailability
now answer through it.
2026-09-24 07:39:56 +02:00
Marc-André Bombeck a7888a9011 feat(ai): replace the Correlations switch with Reading documents
The operator switches become master, Coach, Daily Briefing, Status
notes and Reading documents. Correlations goes: it gated statistics,
not anything a model writes. Reading documents covers the document
vault, lab scans and medication extraction.

The Coach module's operator availability now follows the Coach
switch, so there is one place to turn the Coach off server-wide. The
migration folds a stored Coach availability of false into the switch,
and gives everyone who hid the Coach the AI analysis opt-out, since
hiding the Coach no longer stops nightly briefing and status notes.

A switch read that fails now fails closed. The insights module is
described as AI analysis in every locale, and the switch guard now
keeps both retired switches out and freezes the callers of the old
operator-only gate.
2026-09-24 07:36:47 +02:00
Marc-André Bombeck c8a01ac3ed feat(ai): resolve AI capabilities from their layers
A pure resolver turns operator switches, module access, provider-work
authority, provider presence and consent receipts into one state per
capability, reporting the outermost reason. The document provider rank
moves to its own module so the resolver and the document routes read
the same order.
2026-09-24 07:26:33 +02:00
Marc-André Bombeck a5fdf675e1 feat(ai): add the capability vocabulary and table
One frozen table names every AI capability with the operator switch,
owning modules, consent rule, modality and provider order that decide
it. The reason enum is listed in precedence order. No I/O, so the
resolver, gates, contract and guards can all depend on it.
2026-09-24 07:23:57 +02:00
Marc-André Bombeck 01cd755de6 fix(medications): keep recent doses in the trailing history window
The Verlauf ledger dropped doses the full history showed. Three windows
ended too early or started too late:

- The server clamped the window floor to the medication's creation
  instant and filtered recorded doses by the same floor, so a dose
  logged for earlier the same day on a medication added afterwards
  fell out of "Last 90 days". The creation floor now bounds minted
  slots only; recorded doses use the requested window.
- A dose taken inside its window before the slot's own time is stored
  on the slot anchor, which still lay past the window end. The read
  horizon now reaches the latest recorded anchor within a day, without
  minting later upcoming slots.
- The client pinned from/to at mount and reused them on every refetch,
  so a dose added after the tab opened stayed hidden until a reload.
  The window is now resolved when the request fires and only "from"
  travels; the query key carries the window length instead of instants.

Refs #1028
2026-09-24 07:22:06 +02:00
Marc-André Bombeck aa58495cbe Merge pull request #1007 from muhdusama/medfix/apple-health-scheduled-mirror
fix: allow scheduled Apple Health medication mirrors
2026-09-20 23:47:32 +02:00
muhdusama 24ff031f7a fix: preserve legacy compliance response contract 2026-09-21 07:17:13 +10:00
Marc-André Bombeck 50717c567a docs: keep README screenshots on one line (#1022) 2026-09-20 20:15:57 +02:00
dependabot[bot] edb613bf2b chore(deps): bump docker/setup-buildx-action from 4.3.0 to 4.4.1 (#1020)
Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 4.3.0 to 4.4.1.
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/37fe631027851001ddb9b187196cc803df7f5f0e...f87e5991a6d7451dcb8d9637bfbc97413f497069)

---
updated-dependencies:
- dependency-name: docker/setup-buildx-action
  dependency-version: 4.4.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-20 19:00:55 +02:00
dependabot[bot] 9402e48936 chore(deps): bump docker/build-push-action from 7.3.0 to 7.4.0 (#1019)
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 7.3.0 to 7.4.0.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/53b7df96c91f9c12dcc8a07bcb9ccacbed38856a...c3c9e263c25d99ce0380d002d59b67737d91b0dc)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-version: 7.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-20 19:00:44 +02:00
dependabot[bot] 2c640683a7 chore(deps): bump undici from 8.10.0 to 8.10.2 (#1018)
Bumps [undici](https://github.com/nodejs/undici) from 8.10.0 to 8.10.2.
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v8.10.0...v8.10.2)

---
updated-dependencies:
- dependency-name: undici
  dependency-version: 8.10.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-20 19:00:31 +02:00
dependabot[bot] fd8431ae47 chore(deps-dev): bump eslint-config-next from 16.2.12 to 16.3.5 (#1015)
Bumps [eslint-config-next](https://github.com/vercel/next.js/tree/HEAD/packages/eslint-config-next) from 16.2.12 to 16.3.5.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/commits/v16.3.5/packages/eslint-config-next)

---
updated-dependencies:
- dependency-name: eslint-config-next
  dependency-version: 16.3.5
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-20 18:24:50 +02:00
Marc-André Bombeck 271cebeead Merge pull request #1014 from MBombeck/MBombeck-patch-1
Enhance README with additional images
2026-09-20 17:50:30 +02:00
Marc-André Bombeck 6b1b061b0b Enhance README with additional images
Added images for insights, resting pulse, medications, and coach chat to the README.
2026-09-20 17:22:36 +02:00
Marc-André Bombeck 749f3682c0 Add assets 2026-09-20 17:18:05 +02:00
muhdusama 41d47c3184 fix: mark mirror adherence not applicable 2026-09-20 21:48:20 +10:00
muhdusama c223b6d77d fix: scope Apple Health schedule exemption 2026-09-20 20:46:47 +10:00
Marc-André Bombeck ac59e68a54 Merge pull request #1012 from MBombeck/docs/app-store-links
docs(readme): point at the App Store listing
2026-09-20 11:52:47 +02:00
Marc-André Bombeck 325e94a8f9 docs(readme): point at the App Store listing
The iOS client left public beta. The badge row, the navigation lines and
the iOS section named TestFlight only, which now reads as the single way
in. Both routes stay, with the price and the free-code offer stated
rather than left for someone to discover on the store page.
2026-09-20 11:36:27 +02:00
Marc-André Bombeck 0195c59667 Merge pull request #1010 from MBombeck/release/v1.38.25
Release v1.38.25
2026-09-20 11:10:30 +02:00
Marc-André Bombeck 4f31b4b025 chore(release): v1.38.25 — readings that never arrived, and an import that said no 2026-09-20 10:53:24 +02:00
Marc-André Bombeck 6291c95b5a Merge pull request #1009 from MBombeck/fix/import-export-xml-name
fix(import): find the export XML whatever iOS named it
2026-09-20 00:33:54 +02:00
Marc-André Bombeck c405f15ef0 fix(import): find the export XML whatever iOS named it
The archive member was matched against the English lowercase spelling
alone. iOS writes that file name in the phone's language and some
versions capitalise it, so an ordinary export could arrive as
Export.xml or a translated name and was refused with a message telling
the reader their export was invalid.

The basename now matches in any capitalisation, and a single XML member
at the top of the archive is taken as the translated spelling. Apple's
clinical-document file never qualifies: it sits beside the real export
and would parse to nothing. When no member qualifies the error lists the
XML members the archive does hold, so the next report arrives with the
answer in it.

Refs #1008
2026-09-20 00:14:26 +02:00
muhdusama 30e454fb83 fix: allow scheduled Apple Health mirrors 2026-09-20 00:26:05 +10:00
Marc-André Bombeck c183d1862e Merge pull request #1003 from MBombeck/fix/cycle-symptom-severity-null
fix(cycle): accept a symptom logged without an intensity
2026-09-18 19:33:22 +02:00
Marc-André Bombeck 6113855b19 chore(openapi): regenerate after the symptom severity change 2026-09-18 19:10:39 +02:00
Marc-André Bombeck bff083f532 fix(cycle): accept a symptom logged without an intensity
Picking a symptom without tapping an intensity is how most of them are
logged. The sheet sends severity null for those, the schema took a number
or nothing at all, and the day log came back 422 with two issues for two
symptoms. All the sheet could say was "Could not save. Try again.", and
the cycle saved fine as soon as the symptoms were removed, which sent
people looking in the wrong place.

Nothing else disagreed: the link row has always stored an unrated symptom
as a plain presence, and the writer already maps a non-number to NULL.
Only the gate at the door refused it, on both the create and the patch
path, and no test touched either schema.

Refs #1001
2026-09-18 18:51:38 +02:00
Marc-André Bombeck 1fe90f3fab Merge pull request #1000 from MBombeck/fix/hk-percent-tolerance
fix(apple-health): take a percent from a fraction or an already-scaled client
2026-09-18 16:58:59 +02:00
Marc-André Bombeck 9d9e8570f7 fix(apple-health): take a percent from a fraction or an already-scaled client
Shipped iOS builds multiply oxygen saturation and body fat by 100 before
upload. The importer scaled them again, so 0.97 was stored as 9700, the
plausibility guard rejected the row as out of range inside an HTTP 200,
and the client treats that skip as final and moves its HealthKit anchor
past the sample. Every reading of those two types was lost, silently, on
every install that syncs them.

The contract says values travel raw and the server scales, and that is
what the OpenAPI description publishes. One comment in the schema said
the opposite, that the client must multiply by 100 first, and that is
the line the app was built against. It is corrected here.

The five percent-shaped HealthKit identifiers now take either spelling:
a value above the fraction ceiling is already a percent and passes
through, anything at or below it is scaled. The domains do not overlap,
and the per-type range guard still rejects what is impossible either
way. Current app builds stop losing readings without an app release.

The tests pin both spellings, the range after conversion, and that the
tolerant converter covers the percent class and nothing else: waist
circumference uses the same factor to turn metres into centimetres, and
a blanket change made a 1.02 m waist into 1.02 cm.

Refs MBombeck/healthlog-iOS#7
2026-09-18 16:40:11 +02:00
Marc-André Bombeck 244d0e4b69 Merge pull request #999 from MBombeck/release/v1.38.24
Release v1.38.24
2026-09-16 18:48:07 +02:00
Marc-André Bombeck 5188b28ea6 chore(release): v1.38.24 — Insights loads without the assistant, and the database stays current 2026-09-16 18:27:51 +02:00
Marc-André Bombeck bf728ff552 Merge pull request #998 from MBombeck/dependabot/npm_and_yarn/types/node-26.5.1
chore(deps-dev): bump @types/node from 26.1.1 to 26.5.1
2026-09-16 15:47:54 +02:00
Marc-André Bombeck c2ec2b76cf Merge pull request #994 from MBombeck/dependabot/npm_and_yarn/sonner-2.0.8
chore(deps): bump sonner from 2.0.7 to 2.0.8
2026-09-16 15:47:26 +02:00
dependabot[bot] 34182cbb4f chore(deps-dev): bump @types/node from 26.1.1 to 26.5.1
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 26.1.1 to 26.5.1.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 26.5.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-16 13:23:10 +00:00
dependabot[bot] 4ac11c71cb chore(deps): bump sonner from 2.0.7 to 2.0.8
Bumps [sonner](https://github.com/emilkowalski/sonner) from 2.0.7 to 2.0.8.
- [Release notes](https://github.com/emilkowalski/sonner/releases)
- [Commits](https://github.com/emilkowalski/sonner/compare/v2.0.7...v2.0.8)

---
updated-dependencies:
- dependency-name: sonner
  dependency-version: 2.0.8
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-16 13:10:36 +00:00
Marc-André Bombeck 629731120a Merge pull request #997 from MBombeck/dependabot/npm_and_yarn/jose-6.2.12
chore(deps): bump jose from 6.2.10 to 6.2.12
2026-09-16 15:09:43 +02:00
Marc-André Bombeck c33a88b282 Merge pull request #993 from MBombeck/dependabot/npm_and_yarn/napi-rs/canvas-1.0.9
chore(deps): bump @napi-rs/canvas from 1.0.7 to 1.0.9
2026-09-16 15:09:20 +02:00
Marc-André Bombeck 19ba97e3fc Merge pull request #990 from MBombeck/dependabot/npm_and_yarn/sax-1.6.1
chore(deps): bump sax from 1.6.0 to 1.6.1
2026-09-16 15:08:31 +02:00
dependabot[bot] 9db3770ea3 chore(deps): bump @napi-rs/canvas from 1.0.7 to 1.0.9
Bumps [@napi-rs/canvas](https://github.com/Brooooooklyn/canvas) from 1.0.7 to 1.0.9.
- [Release notes](https://github.com/Brooooooklyn/canvas/releases)
- [Changelog](https://github.com/Brooooooklyn/canvas/blob/main/CHANGELOG.md)
- [Commits](https://github.com/Brooooooklyn/canvas/compare/v1.0.7...v1.0.9)

---
updated-dependencies:
- dependency-name: "@napi-rs/canvas"
  dependency-version: 1.0.9
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-16 12:06:47 +00:00
dependabot[bot] fade5d467e chore(deps): bump sax from 1.6.0 to 1.6.1
Bumps [sax](https://github.com/isaacs/sax-js) from 1.6.0 to 1.6.1.
- [Commits](https://github.com/isaacs/sax-js/compare/v1.6.0...v1.6.1)

---
updated-dependencies:
- dependency-name: sax
  dependency-version: 1.6.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-16 12:06:47 +00:00
dependabot[bot] 453c1141a7 chore(deps): bump jose from 6.2.10 to 6.2.12
Bumps [jose](https://github.com/panva/jose) from 6.2.10 to 6.2.12.
- [Release notes](https://github.com/panva/jose/releases)
- [Changelog](https://github.com/panva/jose/blob/main/CHANGELOG.md)
- [Commits](https://github.com/panva/jose/compare/v6.2.10...v6.2.12)

---
updated-dependencies:
- dependency-name: jose
  dependency-version: 6.2.12
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-16 11:54:00 +00:00
Marc-André Bombeck 6f562c05ca Merge pull request #992 from MBombeck/dependabot/npm_and_yarn/nodemailer-10.0.9
chore(deps): bump nodemailer from 9.1.1 to 10.0.9
2026-09-16 13:53:51 +02:00
Marc-André Bombeck 78996e6ba5 Merge pull request #996 from MBombeck/ci/pin-trivy-installer
ci(security): pin and verify the Trivy installer
2026-09-16 13:46:41 +02:00
Marc-André Bombeck 01cc7197fb Merge pull request #995 from MBombeck/chore/postgres-major-ignore
chore(deps): keep PostgreSQL majors out of the update stream
2026-09-16 13:46:37 +02:00
Marc-André Bombeck c79cd3a0ed Merge pull request #982 from MBombeck/fix/insights-without-assistant
fix(insights): keep the overview reads open with the assistant switched off
2026-09-16 13:39:54 +02:00
dependabot[bot] 4b32bad6e9 chore(deps): bump @tanstack/react-virtual from 3.14.5 to 3.14.12 (#991)
Bumps [@tanstack/react-virtual](https://github.com/TanStack/virtual/tree/HEAD/packages/react-virtual) from 3.14.5 to 3.14.12.
- [Release notes](https://github.com/TanStack/virtual/releases)
- [Changelog](https://github.com/TanStack/virtual/blob/main/packages/react-virtual/CHANGELOG.md)
- [Commits](https://github.com/TanStack/virtual/commits/@tanstack/react-virtual@3.14.12/packages/react-virtual)

---
updated-dependencies:
- dependency-name: "@tanstack/react-virtual"
  dependency-version: 3.14.12
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-16 11:16:53 +00:00
Marc-André Bombeck 3da671c7c3 chore(deps): drop the separate nodemailer types
nodemailer 10 is a TypeScript rewrite and ships its own declarations, so
the hand-added @types/nodemailer package now shadows them with the types
of a release two majors old. The email sender keeps its default import
and its Transporter type from the package itself.

The new floor is Node 20; the image and the engines field are on 22.
2026-09-16 13:08:48 +02:00
Marc-André Bombeck a6b150c36e ci(security): pin and verify the Trivy installer
The Trivy install step piped a script fetched from a tag straight into a
shell. A tag can be moved to other content, so the job ran whatever the
ref pointed at, with the runner's privileges, and the Scorecard check
flagged it as an unpinned download-then-run.

The script now comes from the commit the tag points at, is checked
against its SHA-256 before it runs, and the binary version stays what it
was.
2026-09-16 13:05:21 +02:00
Marc-André Bombeck 6058590872 chore(deps): keep PostgreSQL majors out of the update stream
The compose ecosystem added last change did its job on the first run and
immediately proposed 16.15 to 18.6. A PostgreSQL major changes the
on-disk format, so merging that would hand self-hosters a container that
cannot read their data directory without pg_upgrade or a dump and
restore. Minor releases keep arriving as reviewable PRs; a major is a
project decision with a migration path behind it, not a weekly bump.

The guard grows a case for the ignore rule, so dropping it fails rather
than quietly re-opening the door.
2026-09-16 13:05:14 +02:00
Marc-André Bombeck 2b512501db fix(insights): leave mood out of the trends row when its module is off
The tab strip already hides the Mood pill when the mood module is off, but
the trends row still charted mood, both from a briefing finding and in its
blood pressure / weight / mood fallback. selectTrendCharts now takes the
metrics to leave out, and the overview passes mood when the module is off.

Refs #975
2026-09-16 12:56:09 +02:00
Marc-André Bombeck c7f7a2925f fix(insights): keep the overview reads open with the assistant switched off
With the assistant switched off on the server, the Insights overview did
not load. Its main read, /api/insights/comprehensive, was gated on the
Coach surface, and the derived tiles, the ECG list, strip and live ingest,
and the rhythm events were gated on the status-card surface. The master
flag forces every surface off, so all of them answered 403 and the page
replaced the whole overview with an error.

None of these handlers calls a provider or returns assistant prose. They
now gate on the insights module only, like health-status, labs-changes and
patterns already do. comprehensive had no module gate of its own, only the
Coach gate, so it gains the insights module gate the other five already
call. Routes that serve generated text keep their gate.

The route-gate inventory moves the six files onto the not-Coach-owned
list, four OpenAPI descriptions drop the gate they no longer have, and a
comprehensive test pins a 200 with the master flag off.

Refs #975
2026-09-16 12:55:43 +02:00
dependabot[bot] c46874060d chore(deps): bump nodemailer from 9.1.1 to 10.0.9
Bumps [nodemailer](https://github.com/nodemailer/nodemailer) from 9.1.1 to 10.0.9.
- [Release notes](https://github.com/nodemailer/nodemailer/releases)
- [Changelog](https://github.com/nodemailer/nodemailer/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodemailer/nodemailer/compare/v9.1.1...v10.0.9)

---
updated-dependencies:
- dependency-name: nodemailer
  dependency-version: 10.0.9
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-16 10:40:05 +00:00
Marc-André Bombeck 114f8e9fa6 Merge pull request #988 from MBombeck/chore/postgres-minor-watch
chore(deps): move the database pin to 16.15 and watch it
2026-09-16 12:36:58 +02:00
Marc-André Bombeck 79c4c3631f chore(deps): move the database pin to 16.15 and watch it
The bundled PostgreSQL was pinned to 16.14 while 16.15 had been out for
five weeks. The pin itself is deliberate, a database change should be
reviewable rather than whatever the registry serves on pull day, but
nothing watched it: Dependabot was configured with the docker ecosystem,
which reads the Dockerfile and never opens a compose file, so no update
PR was ever raised. CI and the integration suite meanwhile run against
the floating 16-alpine, so the shipped database was older than the
tested one.

Adds the docker-compose ecosystem so each PostgreSQL minor release
arrives as a reviewable PR, moves the pin to 16.15, and pins both halves
with a test that fails if the exact minor or the watch is dropped.
Refs #987
2026-09-16 12:19:09 +02:00
Marc-André Bombeck 0ec05c3c5a Merge pull request #986 from MBombeck/release/v1.38.23
Release v1.38.23
2026-09-15 23:42:32 +02:00
Marc-André Bombeck 6f4e39acf6 chore(release): v1.38.23 — MCP connects from Chrome again, and lab scans can go past six an hour 2026-09-15 23:01:17 +02:00
Marc-André Bombeck ed8a93afc2 feat(labs): make the lab-scan limit operator-tunable
A self-hoster scanning a stack of lab reports ran into a fixed six scans
an hour with no way to raise it. LABS_OCR_LIMIT_PER_HOUR now sets the
per-user ceiling (default 6, clamped to 1-1000, falling back to the
default when unset or not a number), the same shape as
DOCUMENT_AI_LIMIT_PER_HOUR. It is on the compose whitelist, in the
production example, the env manifest and the AI provider guide.

The route also charged the slot before it had looked at the request, so
a malformed body, an unsupported or oversized file, a PDF that could not
be rendered or a scan the daily budget refused still used up the hour.
Those failures hand the slot back now; a scan that reached the provider
keeps it. The 429 carries meta.retryAt. Refs #985
2026-09-15 23:01:10 +02:00
Marc-André Bombeck 8457e4ffcb Merge pull request #984 from MBombeck/fix/mcp-consent-form-action
fix(mcp): let the consent screen return to the connecting client
2026-09-15 15:03:58 +02:00
Marc-André Bombeck 530c8f40fe test: allowlist the consent journey's origin-only goto
The MCP consent journey navigates to /api/version only to give the page
an origin, then registers the OAuth client with the page's own fetch.
That evaluate reads no DOM, the same shape as the allowlisted vaccination
seed, and the consent page after it is gated on the Allow button.
2026-09-15 14:39:09 +02:00
Marc-André Bombeck 864566d882 fix(mcp): let the consent screen return to the connecting client
After Allow on the MCP OAuth consent screen, Chromium-based browsers
stayed on the page although the grant was issued. The page carried the
app-wide CSP form-action 'self', and Chromium applies form-action to the
redirect that follows the form post to the client's redirect_uri.

The authorize route now owns the CSP of its responses and the proxy
leaves that exact path alone. The consent page allows form-action for
its own origin plus the origin of the redirect URI the route has just
validated against the resolved client, and only https or http origins
qualify. Every other response from the route keeps form-action 'self'
with default-src 'none'. The redirect after the decision is now 303,
which tells every browser to follow a form POST with a GET. Refs #983
2026-09-15 14:06:27 +02:00
Marc-André Bombeck 7b7a77b292 test(e2e): walk the MCP consent screen back to a loopback callback
A connector signing in through the MCP OAuth consent screen gets stuck
after Allow in Chromium: the grant is issued, but the browser never
reaches the client's callback. Only a real browser enforces the page's
CSP on that redirect, so this is a browser journey. It registers a
client with a local loopback callback, clicks Allow and requires the
callback to receive a code, state and issuer. It runs against the second
server, which now carries APP_URL because the MCP surface fails closed
without a configured origin. Refs #983
2026-09-15 14:03:18 +02:00
Marc-André Bombeck 970c89a5e7 Merge pull request #979 from MBombeck/fix/e2e-smtp-stub-port-range
test(e2e): draw the SMTP stub port below the ephemeral ranges
2026-09-14 00:39:28 +02:00
Marc-André Bombeck ef585c34c4 test(e2e): draw the SMTP stub port below the ephemeral ranges
The stub port was drawn from 49152-65535. Linux assigns local ports for
outgoing connections from 32768-60999, so the drawn number could already
be held by a client socket the runner had opened, and the notification
journey failed in beforeAll with EADDRINUSE although no other stub was
listening. The port now comes from 20000-32767, below the Linux and
macOS ephemeral ranges.
2026-09-14 00:20:58 +02:00
Marc-André Bombeck a3d813ad7b Merge pull request #964 from MBombeck/dependabot/npm_and_yarn/lucide-react-1.44.0
chore(deps): bump lucide-react from 1.34.0 to 1.44.0
2026-09-13 23:59:34 +02:00
Marc-André Bombeck be2809fd13 Merge pull request #976 from MBombeck/fix/e2e-more-hub-after-picker
test(e2e): wait for the capture picker to close before opening More
2026-09-13 23:40:27 +02:00
dependabot[bot] 9af911a2a9 chore(deps): bump lucide-react from 1.34.0 to 1.44.0
Bumps [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) from 1.34.0 to 1.44.0.
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.44.0/packages/lucide-react)

---
updated-dependencies:
- dependency-name: lucide-react
  dependency-version: 1.44.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-13 21:24:49 +00:00
Marc-André Bombeck 203f1135a2 test(e2e): wait for the capture picker to close before opening More
The mobile smoke test pressed Escape on the capture picker and tapped
the More button straight away. While the picker's close animation still
covers the bottom nav, that tap lands on the overlay and the hub never
opens, which failed the lucide-react update once. The test now waits
until the picker is hidden.
2026-09-13 23:24:02 +02:00
Marc-André Bombeck 755d48444f Merge pull request #966 from MBombeck/dependabot/npm_and_yarn/playwright/test-1.63.0
chore(deps-dev): bump @playwright/test from 1.62.1 to 1.63.0
2026-09-13 23:22:47 +02:00
dependabot[bot] 59300e809d chore(deps-dev): bump @playwright/test from 1.62.1 to 1.63.0
Bumps [@playwright/test](https://github.com/microsoft/playwright) from 1.62.1 to 1.63.0.
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.62.1...v1.63.0)

---
updated-dependencies:
- dependency-name: "@playwright/test"
  dependency-version: 1.63.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-13 20:46:57 +00:00
Marc-André Bombeck 869766c508 Merge pull request #974 from MBombeck/fix/e2e-malformed-switch-payload
test(e2e): pass an unswitched auth payload through the corrupting route
2026-09-13 22:45:03 +02:00
Marc-André Bombeck 76d80fbed4 test(e2e): pass an unswitched auth payload through the corrupting route
The malformed-payload journey installs its /api/auth/me route before it
clicks the switch. When the owner session read its own payload again in
that window, the helper threw inside the route handler: the throw came
before fulfill, so its catch never saw it, the test failed, and the
teardown's unroute then hit a closed page. It showed up on the Playwright
1.63 branch, whose timing opens that window more often. An unswitched
payload now passes through unchanged, and the test asserts that at least
one switched response was actually corrupted before trusting the refusal.
2026-09-13 22:20:15 +02:00
Marc-André Bombeck 66b0dbb67b Merge pull request #968 from MBombeck/dependabot/npm_and_yarn/prisma-7.10.0
chore(deps): bump prisma from 7.8.0 to 7.10.0
2026-09-13 22:18:21 +02:00
Marc-André Bombeck 0ddf8de9bf Merge main into the Prisma 7.10 update 2026-09-13 21:17:11 +02:00
Marc-André Bombeck c3871289ee Merge pull request #973 from MBombeck/fix/e2e-session-call-origin
test(e2e): give an unnavigated page an origin before a session call
2026-09-13 21:17:08 +02:00
Marc-André Bombeck 99ddf0db5d test(e2e): give an unnavigated page an origin before a session call
The setup flow specs answer questions through these helpers before their
first real navigation. That case still went through page.request, which
shares the runner's keep-alive agent, and a stale socket failed an answer
with read ECONNRESET on the dependency update branches. The page now opens
the public version endpoint first and sends the call with its own fetch.
2026-09-13 20:58:04 +02:00
Marc-André Bombeck 7787a5cf5e Merge main into the Prisma 7.10 update 2026-09-13 20:33:18 +02:00
Marc-André Bombeck 36ff3e7cb9 chore(deps): move the Prisma client and the image CLI to 7.10
The bump raised the CLI to 7.10.0 but left @prisma/client at 7.8.0 and
the migration CLI the image installs under /opt/prisma-cli at 7.8.0, so
the generated client, the one that ships and the one that migrates would
have come from two releases. All three are 7.10.0 now.
2026-09-13 20:33:17 +02:00
Marc-André Bombeck b794a256d0 Merge pull request #970 from MBombeck/dependabot/npm_and_yarn/pdfjs-dist-6.3.289
chore(deps-dev): bump pdfjs-dist from 6.2.108 to 6.3.289
2026-09-13 20:22:08 +02:00
dependabot[bot] a5b5faec83 chore(deps): bump prisma from 7.8.0 to 7.10.0
Bumps [prisma](https://github.com/prisma/prisma-cli/tree/HEAD/packages/prisma) from 7.8.0 to 7.10.0.
- [Release notes](https://github.com/prisma/prisma-cli/releases)
- [Commits](https://github.com/prisma/prisma-cli/commits/HEAD/packages/prisma)

---
updated-dependencies:
- dependency-name: prisma
  dependency-version: 7.10.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-13 17:50:31 +00:00
dependabot[bot] 2d92c16729 chore(deps-dev): bump pdfjs-dist from 6.2.108 to 6.3.289
Bumps [pdfjs-dist](https://github.com/mozilla/pdf.js) from 6.2.108 to 6.3.289.
- [Release notes](https://github.com/mozilla/pdf.js/releases)
- [Commits](https://github.com/mozilla/pdf.js/compare/v6.2.108...v6.3.289)

---
updated-dependencies:
- dependency-name: pdfjs-dist
  dependency-version: 6.3.289
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-13 17:48:39 +00:00
Marc-André Bombeck 9e81369279 Merge pull request #965 from MBombeck/dependabot/npm_and_yarn/vitejs/plugin-react-6.1.1
chore(deps-dev): bump @vitejs/plugin-react from 6.1.0 to 6.1.1
2026-09-13 19:42:21 +02:00
Marc-André Bombeck 2ad84c97d4 Merge pull request #969 from MBombeck/dependabot/github_actions/pnpm/action-setup-6.1.0
chore(deps): bump pnpm/action-setup from 6.0.10 to 6.1.0
2026-09-13 19:42:18 +02:00
Marc-André Bombeck 2f1dadabb9 Merge pull request #967 from MBombeck/dependabot/github_actions/codeql-action-8213001b74
chore(deps): bump the codeql-action group with 3 updates
2026-09-13 19:42:15 +02:00
Marc-André Bombeck 293ddcb3ee Merge pull request #971 from MBombeck/release/v1.38.22
Release v1.38.22
2026-09-13 19:10:26 +02:00
Marc-André Bombeck f293d31850 test(e2e): send the setup flow calls over the page's own connection
The setup flow helpers read the account, the dashboard layout and wrote
answers through page.request, which shares the runner's keep-alive agent
with every other API context. A socket the server had already closed on
its idle timeout failed one answer with read ECONNRESET, and CI counts
the passing retry as a failure. The calls go through the page's fetch
now, as the record session specs already do; before the first navigation
there is no origin, so that case keeps the API context.
2026-09-13 18:54:54 +02:00
Marc-André Bombeck 2207bb1114 chore(release): v1.38.22 — a channel test waits until you save 2026-09-13 18:28:47 +02:00
Marc-André Bombeck 3bb08c3c8a fix(settings): hold the channel test until changes are saved
The webhook, ntfy, email and Telegram test routes send through the
saved channel config. After a field changed, the card kept showing the
Saved note from the last save and Test still ran, so it reported on the
old settings: a webhook switched to the Gotify format was tested with
the generic body and Gotify refused it. The note now disappears on a
change, and the test button stays off with a save-first hint while the
form differs from what is saved. Refs #947
2026-09-13 18:28:47 +02:00
dependabot[bot] 6fb7a3835f chore(deps): bump pnpm/action-setup from 6.0.10 to 6.1.0
Bumps [pnpm/action-setup](https://github.com/pnpm/action-setup) from 6.0.10 to 6.1.0.
- [Release notes](https://github.com/pnpm/action-setup/releases)
- [Commits](https://github.com/pnpm/action-setup/compare/0977fd99725f1db4007ccb2928dbb4e90d06cc86...ea17c68df8912ef543352723c149a84f56e3d413)

---
updated-dependencies:
- dependency-name: pnpm/action-setup
  dependency-version: 6.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-13 15:55:28 +00:00
dependabot[bot] 52c1da6034 chore(deps): bump the codeql-action group with 3 updates
Bumps the codeql-action group with 3 updates: [github/codeql-action/init](https://github.com/github/codeql-action), [github/codeql-action/analyze](https://github.com/github/codeql-action) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action).


Updates `github/codeql-action/init` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/cdf488f595d80d6e07e03d4674febd5ab45fa938...b96794f015dfd88f77b49b1c93e0fa7110f94c63)

Updates `github/codeql-action/analyze` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/cdf488f595d80d6e07e03d4674febd5ab45fa938...b96794f015dfd88f77b49b1c93e0fa7110f94c63)

Updates `github/codeql-action/upload-sarif` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/cdf488f595d80d6e07e03d4674febd5ab45fa938...b96794f015dfd88f77b49b1c93e0fa7110f94c63)

---
updated-dependencies:
- dependency-name: github/codeql-action/init
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: codeql-action
- dependency-name: github/codeql-action/analyze
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: codeql-action
- dependency-name: github/codeql-action/upload-sarif
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: codeql-action
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-13 15:54:49 +00:00
dependabot[bot] 530d2849bb chore(deps-dev): bump @vitejs/plugin-react from 6.1.0 to 6.1.1
Bumps [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) from 6.1.0 to 6.1.1.
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.1/packages/plugin-react)

---
updated-dependencies:
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.1.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-13 15:53:54 +00:00
Marc-André Bombeck d4766a580b Merge pull request #963 from MBombeck/release/v1.38.21
Release v1.38.21
2026-09-13 15:38:09 +02:00
Marc-André Bombeck 8c8e03a6eb chore(release): v1.38.21 — channel tests say why they failed, and Gotify gets its format 2026-09-13 15:18:20 +02:00
Marc-André Bombeck 669058d37c Merge the review fixes for channel tests 2026-09-13 15:17:36 +02:00
Marc-André Bombeck 3dece61cc8 Merge the review fix for record settings the grant cannot manage 2026-09-13 15:17:36 +02:00
Marc-André Bombeck d4fa7d5913 Merge the review fixes for the service worker and the Loki note 2026-09-13 15:17:36 +02:00
Marc-André Bombeck 60dfffc7ad docs(api): name each channel's own credentials in test errors
The ntfy and webhook 502 descriptions shared one list of refused credentials that neither channel fully has. Each now names its own, including the userinfo and long path segments of a webhook URL. The email description names the TLS, protocol and envelope cases.

Refs #947
2026-09-13 14:50:33 +02:00
Marc-André Bombeck 32eaf7a29e fix(admin): show each channel's cause in the notification test toast
The admin test response carried a code and status per channel that nothing rendered. The toast now lists each failing channel with the translated cause and the HTTP status or SMTP code. The relay reply is no longer part of that response, and the ntfy error no longer echoes the topic, which the sender treats as a secret.

Refs #947
2026-09-13 14:50:33 +02:00
Marc-André Bombeck 2480c9fa55 fix(notifications): refuse encoded and path-borne secrets in replies
Userinfo and each query value are decoded on their own, so one malformed escape no longer discards every other secret in the URL. A reply is compared with each secret in literal, JSON-escaped and percent-encoded form, and URL path segments of 16 or more characters count as secrets, which covers the token in a Discord or Slack webhook URL and an n8n webhook id.

Refs #947
2026-09-13 14:50:33 +02:00
Marc-André Bombeck f81cdf8768 fix(notifications): name TLS, protocol and envelope faults in email tests
A STARTTLS failure (port 465 set up as 587) and a protocol error now read as connection_failed, and an envelope or message refused without a reply code as upstream_rejected. They used to fall through to the 500 for an unnamed failure.

Refs #947
2026-09-13 14:50:33 +02:00
Marc-André Bombeck a11e5991cf test(settings): read a real failure response through the test button
The fetch and envelope reading move into runConnectionTest, which the button calls. A test stubs the fetch with the 502 envelopes the notification test routes send and asserts the rendered code, HTTP status, SMTP code and relay reply, so dropping the meta extraction fails it.

Refs #947
2026-09-13 14:50:32 +02:00
Marc-André Bombeck 6a663dfc27 fix(notifications): record a relay refusal at warn, not error
A 502 from a channel test reports the user's relay or mail setup, not a fault on this server, yet the status alone raised every press to an error-level event. The event builder gains a ceiling for the status-derived level, and the test routes cap it at warn on the 502 path. The 500 for an unnamed failure stays at error, and explicit elevations are unaffected.

The notifications guide notes that a reverse proxy which replaces 5xx pages hides the detail, so the card falls back to Test failed.

Refs #947
2026-09-13 14:50:32 +02:00
Marc-André Bombeck 45ee70acb7 fix(settings): list record content only where the grant manages it
The anamnesis page writes through requireRecordAuth("manage",
"profile"), which refuses a grant whose sections do not reach profile.
The Settings list and the navigation entry checked only the level and
the record kind, so a MANAGE grant scoped away from profile would be
offered a page whose saves are refused.

Record-content destinations now name the section they write, and are
listed only when the active record's manageable sections include it.
A destination without a named section is never listed. The shell and
the navigation read the same predicate. MANAGE grants are whole-record
today, so managed profiles and adult MANAGE shares list what they did
before.

Refs #939
2026-09-13 14:49:56 +02:00
Marc-André Bombeck 873e9cb4fb fix(pwa): keep a subscribed worker registered behind a gateway
A same-origin auth gateway that answers an expired session with a 200
sign-in page returns HTML for both the navigation and the /api/version
probe, which read as another app. The worker then unregistered and
destroyed the Web Push subscription, which nothing re-creates, so
reminders stopped without notice.

The worker no longer unregisters while the registration holds a push
subscription, or when the lookup is unavailable. It deletes its caches
and passes requests to the network for the rest of its life instead.
The probe now sends same-origin credentials, so a valid gateway cookie
reaches HealthLog.

Refs #847
2026-09-13 14:45:31 +02:00
Marc-André Bombeck b1331de130 docs(env): name the unspecified address among refused Loki hosts
The Loki block listed link-local and metadata addresses as the only
refused destinations; 0.0.0.0 and :: are refused too.

Refs #947
2026-09-13 14:45:30 +02:00
Marc-André Bombeck 6b146c25d9 fix(settings): stop telling people the webhook URL must be public
A notification target on a private network has been reachable since the
operator allowlist for private origins arrived; the hint under the URL
field and the guide still said the address had to be public.
2026-09-13 14:31:24 +02:00
Marc-André Bombeck 4306bf1aec Merge channel tests that report the other end's answer, and the Gotify format 2026-09-13 14:30:14 +02:00
Marc-André Bombeck f89dda81a6 test: point the prefix drift guard at the shared matcher
The guard read src/lib/idempotency.ts for the hle_ prefix, which moved to src/lib/secret-shape.ts with the matcher. It now asserts that the shared matcher refuses an hle_ token and that the idempotency cache imports and calls it, so a private copy of the pattern would fail it too.
2026-09-13 14:24:37 +02:00
Marc-André Bombeck e788b53be0 docs(notifications): describe what the webhook sends and Gotify setup
The outbound payload was documented nowhere. The webhook section now shows the generic body and the Gotify body as the Test button sends them, what each field carries, and how to point the webhook at Gotify: a URL ending in /message, the application token in an X-Gotify-Key header, and the Gotify format.

Refs #947
2026-09-13 14:19:48 +02:00
Marc-André Bombeck fafb5cdc08 feat(notifications): add a Gotify payload format to the webhook
Gotify's POST /message types priority as an integer, so the generic body, which sends the word, was refused with a 400 before the token was ever the question. The webhook card now offers a payload format: generic, which stays byte for byte what it was, and gotify, which sends title, message, an integer priority and extras.

Priorities follow the Gotify Android client's channel thresholds: 5 for routine events (audible), 8 for medication reminders (the lowest heads-up value), 10 for urgent events. The extras declare plain text and carry the event name, masked to reminder in discreet mode as the generic body does.

The choice lives in the encrypted channel config, so no migration: an absent format is generic, only gotify is written, and a save that omits the field keeps the stored choice. GET returns the resolved value. The sender comment no longer suggests an Authorization Bearer header for Gotify, which takes X-Gotify-Key or a token query parameter.

Refs #947
2026-09-13 14:19:48 +02:00
Marc-André Bombeck f1aebcc3bf Merge private Loki shipping and the service worker that leaves a foreign origin 2026-09-13 14:17:25 +02:00
Marc-André Bombeck e34c5db45e fix(pwa): confirm a foreign origin before the worker retires
A reverse proxy with a response-header allowlist strips
X-HealthLog-Page from every real HealthLog page, and the worker then
unregistered on each load and dropped Web Push subscriptions.

A successful page without the marker now only sends requests to the
network while the worker asks /api/version with no-store and a manual
redirect. It deletes its caches and unregisters only when the answer
positively is not HealthLog: a 404, a non-JSON 2xx, or JSON without
the version shape. A failed probe, any other status or the HealthLog
shape resumes normal service. buildSha may be null on a self-built
image, so only its presence is checked.

Refs #847
2026-09-13 14:16:52 +02:00
Marc-André Bombeck 92606f6409 feat(settings): show the status and reply of a failed channel test
The test-connection callout now appends the HTTP status or SMTP reply code the route reports, and shows what the relay answered on a line beneath it. The reply is rendered as a React text child, so markup in it is shown as characters.

Adds the upstream_rejected message in all seven locales.

Refs #947
2026-09-13 14:13:55 +02:00
Marc-André Bombeck dd5dd1e45e docs(nav): correct two comments about utilities and manage invites
The More hub carries feature destinations only; Settings and
Notifications sit in the top-bar menu. The browser-only refusal for a
manage invitation comes from the transport check, which runs before and
independently of the second-factor step-up.
2026-09-13 14:12:54 +02:00
Marc-André Bombeck 7d40103616 Merge Settings inside a profile you look after 2026-09-13 14:12:18 +02:00
Marc-André Bombeck f6a890df8a fix(notifications): answer a failed channel test with its cause
The webhook, ntfy and email test routes turned every delivery failure into a bare 500, so the settings card could only say "Test failed" while the server knew the relay had answered 400. A failure at the other end, or on the way to it, is now a 502 with meta.errorCode, the upstream HTTP status or SMTP reply code, and for webhook and ntfy what the relay answered when that is short and holds no credential. The codes reuse the test card's vocabulary; upstream_rejected is new, for a relay that accepted the connection and refused the payload. The private-origin 422 is unchanged, and only a failure the server cannot name stays a 500.

The guard that pinned the bare 500 now asserts the opposite, with the reason in its name.

The admin fan-out test reports the same code and status per channel, and tests the webhook and email channels, which it used to list as an unknown channel type.

Refs #947
2026-09-13 14:10:35 +02:00
Marc-André Bombeck c93a384db8 Merge pull request #933 from MBombeck/dependabot/npm_and_yarn/tanstack/react-query-5.102.8
chore(deps): bump @tanstack/react-query from 5.101.4 to 5.102.8
2026-09-13 14:09:38 +02:00
Marc-André Bombeck 8c345f600e feat(notifications): keep what the relay answered on a failed send
The webhook and ntfy senders now carry up to 200 characters of a non-2xx response body on the send outcome, with control and formatting characters removed. The body is dropped when it looks like a credential or echoes the header value, auth token, topic or a URL token. Nothing stores it; the ledger row and channel state keep the reason code as before.

Transport faults without a status now say whether they were a timeout or a refused connection, and the email sender maps SMTP failures into the same vocabulary with the reply code. Both exist so the test routes can answer with the cause instead of a bare 500.

Refs #947
2026-09-13 14:04:40 +02:00
Marc-André Bombeck 4a49120fcf fix(i18n): say the manage invite asks a second factor only if set
Offering manage access is refused outside a browser session, and the
second factor is asked only when the account has one. The note under
the manage option and the browser-only error said the factor was
always asked. Reworded in all seven locales.
2026-09-13 14:03:21 +02:00
Marc-André Bombeck 60a5783534 test(e2e): walk to a managed profile's Modules settings
Switch into the managed record, follow the sidebar Settings entry to
the profile card and on to the Modules card, then repeat from the
phone-width user menu. Asserts the entry's target, the absent
Notifications entry and the record id on each card, after the shell
has loaded.

Refs #939
2026-09-13 14:03:17 +02:00
Marc-André Bombeck 9dcef3b0e2 fix(nav): offer Settings inside a record that has Settings pages
A self-hoster looking after a managed profile could not find Settings
after switching into it: the utility entries vanished for every shared
record, while the Settings shell lists the profile's own configuration
and the section gate admits it.

The utility tail now answers for the record on screen. Settings is
offered when the shell lists at least one section for it and links to
the first one: the profile card for a managed profile, the anamnesis
page for an adult share at manage. Read and write shares, and a
refused or pending switch, get no utility. Notifications stays hidden
under every switch. The desktop sidebar footer and the mobile user
menu read the same list; the footer identity block stays a plain
block.

Refs #939
2026-09-13 14:03:16 +02:00
Marc-André Bombeck f5fc713783 refactor(settings): share the record section predicate
Move the rule that decides which Settings sections a shared record
lists out of the settings shell and into the record-settings
classification module, next to the inventory it reads. The shell
filters through it unchanged; the navigation reads the same answer
in the next change, so the two cannot disagree about whether a record
has Settings pages and where they start.

Refs #939
2026-09-13 14:02:56 +02:00
Marc-André Bombeck cd44a85537 fix(pwa): let the service worker leave an origin HealthLog left
The worker is registered with scope / and serves /_next/static/*
cache-first. A self-hoster who stopped HealthLog and started another
app on the same port kept getting HealthLog's cached chunks until they
unregistered the worker by hand.

The proxy now marks every page response with a presence-only
X-HealthLog-Page header. When a successful navigation arrives without
it, the worker stops handling requests for the rest of its life,
deletes its own caches and unregisters, and hands the page through
untouched. A network failure keeps the offline fallback, and a
redirect or error status is never read as another app, so a gateway
in front of a stopped HealthLog does not drop the Web Push
subscription.

Refs #847
2026-09-13 14:00:11 +02:00
Marc-André Bombeck afb26251e5 fix(logging): ship to a private Loki and report failed pushes
LOKI_ENDPOINT is read only from the server environment, so the push now
dials its exact origin through the pinned operator-approved resolver
instead of the public-host pin that refused a Loki on the operator's
own network. Link-local, metadata and unspecified addresses stay
refused.

A thrown push or a non-2xx answer used to vanish in an empty catch. It
now writes one line to stderr per reason at most every five minutes,
naming the Loki origin, the reason and the dropped event count, without
credentials. The endpoint accepts both the base URL and the full push
URL; the second form used to double the path into a silent 404.

Refs #947
2026-09-13 13:57:33 +02:00
Marc-André Bombeck 15f0e499f9 refactor: share the secret-shape matcher from one leaf
The idempotency cache refuses to persist a body carrying a HealthLog token or an AI provider key. The notification test routes are about to refuse echoing such text too, so the pattern moves to src/lib/secret-shape.ts instead of being written a second time. Behaviour of the cache is unchanged.
2026-09-13 13:56:58 +02:00
dependabot[bot] fabdfea6e2 chore(deps): bump @tanstack/react-query from 5.101.4 to 5.102.8
Bumps [@tanstack/react-query](https://github.com/TanStack/query/tree/HEAD/packages/react-query) from 5.101.4 to 5.102.8.
- [Release notes](https://github.com/TanStack/query/releases)
- [Changelog](https://github.com/TanStack/query/blob/main/packages/react-query/CHANGELOG.md)
- [Commits](https://github.com/TanStack/query/commits/@tanstack/react-query@5.102.8/packages/react-query)

---
updated-dependencies:
- dependency-name: "@tanstack/react-query"
  dependency-version: 5.102.8
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-13 11:50:05 +00:00
Marc-André Bombeck 75760b606a Merge pull request #962 from MBombeck/docs/compose-run-migrations
Run the manual migration inside the stack
2026-09-13 13:21:49 +02:00
Marc-André Bombeck 6a5ad9d9dc docs(ops): run the manual migration inside the stack
The update runbook ran migrations with a plain docker run and an
.env.production file. No setup guide creates that file, and a plain
docker run starts outside the Compose network, where the database's
service name does not resolve, so the step waited thirty seconds and
gave up with a connection error.

It uses docker compose run now, which starts the one-off container in
the stack with the app's own environment. Refs #961
2026-09-13 13:03:41 +02:00
Marc-André Bombeck d1bab391fc Merge release v1.38.20
Signing in no longer tells anybody which addresses have an account here.
2026-09-11 16:41:29 +02:00
Marc-André Bombeck 0568c76076 chore(release): v1.38.20 — signing in no longer says who has an account here
Bump the version, the service-worker fallback and the OpenAPI document,
and add the CHANGELOG entry for v1.38.20.
2026-09-11 16:15:58 +02:00
Marc-André Bombeck 9bf78e32d6 Merge remote-tracking branch 'origin/main' into fix/close-account-enumeration 2026-09-11 16:01:25 +02:00
Marc-André Bombeck 660d6b39be Merge release v1.38.19
The first run tells you what is actually true about your account, an invitation link behaves, and the AI you ask a question to has budget left when you ask it.
2026-09-11 14:56:05 +02:00
Marc-André Bombeck 93874af99b fix(api): record the retirement against the release that carries it
v1.38.19 was cut before this change and still answers on the path, so
naming it as the version that removed the route would be wrong in the
published contract from the day it appears.
2026-09-11 14:39:30 +02:00
Marc-André Bombeck 625763982b Narrow a spent email budget to the field, and record both refusals
A refused address change returned before the update was built, so every
other field in the same request went with it. The settings form posts
the whole profile at once, so somebody who had spent the budget could
not save a timezone or a height for an hour and was told it was about
email addresses. The address is now dropped and the rest of the save
lands, reported through the existing rejectedFields key with the code
`rate_limited`; the 429 is kept for a request that asked for nothing
else, where a partial success would be a lie.

The comment claiming an audit row beside each question was inverted:
both refusals returned before the row is written, so only the answers
that told the caller nothing were being recorded. The two answers worth
detecting write their own rows now.

The stored address is normalised before the "has it changed" comparison.
Registration writes it as typed, so an account created with capitals did
not match its own address and paid for its first ordinary save.
2026-09-11 14:36:58 +02:00
Marc-André Bombeck 3ace3aad35 Answer 410 for the removed account-discovery path
The path stood in the published contract, so a caller outside this
repository can hold a reference to it whether or not we can name one. A
bare 404 reads as a broken deploy or a misrouted proxy, which is exactly
the reading that kept a client retrying a removed path for twelve days
once before. Registering the retirement makes the edge answer 410 with
the removing version and no replacement, and republishes the path as
gone rather than erasing it from the document.
2026-09-11 14:36:47 +02:00
Marc-André Bombeck 6a4e1f61c8 chore(release): v1.38.19 — the setup says what is true, and the AI has budget left when you ask
Bump the version, the service-worker fallback and the OpenAPI document,
and add the CHANGELOG entry for v1.38.19.
2026-09-11 14:36:38 +02:00
Marc-André Bombeck 10d6dc8099 Guard the dummy mint, not only the dummy verification
The dummy hash was awaited as an argument to the verifier, so a rejected
mint threw before the verifier was reached and before the catch on it
could apply. The promise was created once at import, and a rejected
promise stays rejected, so one failed mint under memory pressure would
have made every unknown identifier answer 500 while a real account
answered 401 — a cleaner oracle than the timing gap this closes, and
passkey-only accounts locked out of the password form until restart.

The mint is now awaited inside the guarded region, is lazy rather than
an import-time cost in every process that touches this module, and is
dropped on failure so the next refusal mints again instead of inheriting
a cached rejection. A failure leaves a log line; the answer is false
either way. The tests cover a rejecting mint, not only a rejecting
verify.
2026-09-11 14:36:27 +02:00
Marc-André Bombeck 80426697db Record why registration checks duplicates before hashing
With the discovery endpoint gone, this is the remaining anonymous path
that answers whether an address is registered. The 409 already gives
that away, so the work asymmetry ahead of it costs nothing today. It
would become the whole answer the moment somebody unified the status
code without moving the check after the hash, so the ordering now says
it is load-bearing.
2026-09-11 14:36:19 +02:00
Marc-André Bombeck 4460047910 Merge the coach cap counting only the tokens the operator paid for
Background insights can no longer use up the day before somebody asks a question; a fifth of the daily limit is held back for what a person does by hand.
2026-09-11 14:18:21 +02:00
Marc-André Bombeck a602437649 Merge the ledger wait
The test slept fifty milliseconds and read; it waits for the rows now.
2026-09-11 14:13:06 +02:00
Marc-André Bombeck fe420f76d8 Cap the profile email-address conflict answer
Changing the profile address asks whether another account already holds
it, and the answer is 409 versus 200 — an existence check over every
address on the instance, open to any signed-in caller. Neither route
that reaches it had a ceiling of any kind and the API wrapper supplies
no default, so the only bound on a sweep was the network.

Both routes now share one per-account bucket, ten an hour, charged
before the question is asked so a refused caller learns nothing. Only a
request whose address actually differs from the one on file is counted,
so re-saving a settings form that carries the unchanged address stays
free. The refusal is the standard 429 with Retry-After and the
X-RateLimit triple, carries `profile.update.emailRateLimited`, and is
published on both operations.
2026-09-11 14:05:25 +02:00
Marc-André Bombeck 6a5fb338b1 Make every login refusal cost the same verification
Sign-in returned the moment it found no account, or an account carrying
no password hash, before it reached the verifier. An account that did
have a password paid a full Argon2id verification at 19 MiB and t=2. The
three refusals answered with the identical 401 body and three very
different durations, so the clock told an anonymous caller whether an
address is registered and whether it carries a password.

`verifyPasswordOrDummy` verifies against a stand-in hash minted once per
process at the same cost parameters real hashes use, and returns false
whenever there is nothing to verify, so the passkey-only account takes
the same path as one with a password. The dummy arm discards its own
verdict and swallows a throw, so no outcome there can be read as a
success or answer with a different status.
2026-09-11 13:59:42 +02:00
Marc-André Bombeck 6ef139c7b2 Remove the anonymous account-discovery endpoint
`POST /api/auth/check-user` answered, for any typed identifier and with
no credential at all, whether an account exists and whether it carries a
passkey or a password. Its header called that the intended contract with
the native client; it is not one any more. The native client never calls
it, and no web surface in this repository does either.

Removed without a replacement: the route, its two test files, the
OpenAPI operation and its two schemas, the surface's mention in the
rate-limiter doc comment, the bucket expectation in the auth-surface
rate-limit test, and the login route's comment pointing at it. No stub,
no deprecation shim, no 410 arm — there is no caller to keep.
2026-09-11 13:56:49 +02:00
Marc-André Bombeck 49acba440a Merge remote-tracking branch 'origin/main' into test/settle-ledger-poll 2026-09-11 13:53:31 +02:00
Marc-André Bombeck 585b55fd49 Merge the setup flow saying only what the account's state supports
An invitation link no longer offers to register while you are signed in, the connect step says what is true about a provider, and the AI offer waits until the provider has actually answered.
2026-09-11 13:53:19 +02:00
Marc-André Bombeck 83c54a6b79 test(integration): wait for the ledger row, not for fifty milliseconds
The delivery ledger is written without awaiting the result, so the row
appears some time after the dispatch returns. The test slept a flat fifty
milliseconds and then read, which holds on a warm machine and loses on a
loaded runner: the assertion reported an empty ledger as though the
dispatch had not recorded the skip.

It polls for the rows now, up to five seconds, and fails with a message
naming how many it found. The claim is that the row is written, which is
what the code promises; that it is written within fifty milliseconds is
not.
2026-09-11 13:43:19 +02:00
Marc-André Bombeck 7436a0fcba Merge main — the test-infrastructure fixes from the shared suite
Brings in the truncate retry, the socket fix for the record-fence spec that
failed this branch's second e2e shard, and the corrected absence assertions.
2026-09-11 13:22:43 +02:00
Marc-André Bombeck 92ba0513d2 Merge three harness defects that made checks lie
A truncate that lost a deadlock, a spec reading through a stale pooled socket, and fifteen absence claims asserted before anything had rendered.
2026-09-11 13:21:49 +02:00
Marc-André Bombeck 9cefaecf94 test(e2e): anchor absence claims on a rendered surface
The protected shell renders its hydration gate for every child until
/api/auth/me resolves, so after a goto, a reload or an exit click nothing
exists yet: no nav, no top bar, no banner, no page body. Fifteen absence
assertions across twelve specs were asserted inside that window. Each was
true because the surface had not rendered, and each would have stayed green
if the thing it forbids came back.

Every site now waits for a positive marker of the loaded state first: the
document sheet's footer download action, the settled integrations card
rather than the family attribute its skeleton shares, the top bar after an
exit, the page's own heading, the delegate's own marker, the Coach FAB. Two
skeleton-absence waits are replaced by waits on the content that follows.

delegated-writes had a different cause: it asserted the bulk selection bar
absent although no row was ever selected, so it passed for an owner too. The
gate is one level earlier - below MANAGE no row carries a checkbox at all -
so the test asserts that instead, with the bar and the row delete kept as
backstops.

No sleeps added, no timeouts raised, no claim weakened.
2026-09-11 13:00:56 +02:00
Marc-André Bombeck 82d4a32726 fix(onboarding): the path CTA breaks onto two lines at phone width
The connect step's new attention and credentials tiles link to the
integrations page with a label that names a path — "Open Settings →
Integrations". The button base is `whitespace-nowrap` with a fixed height and
`shrink-0`, so at 390 px the German and French renderings could neither shrink
nor wrap: the control ran 27 px past the viewport. The pre-existing connect
card was unaffected, its label being a short verb phrase; the path label and
the tiles that carry it are new, which is why the sweep passed before.

The CTA is bounded to its card, allowed to break between the words of the
path, and allowed to grow for the second line, with the 44 px tap target kept.
No copy moved, so the seven catalogues stay as they are.
2026-09-11 12:57:10 +02:00
Marc-André Bombeck bcef5aeeee fix(ai): hold a reserve so the chat is never locked out by jobs
The background ceiling applied only when the operator funded the chain, so on a
chain the operator does not pay for the automatic generators and the chat shared
one undivided ceiling and the first could still take all of it. That is the
configuration the recommended remedy for the original lockout produces — put the
personal Codex account first — so the guarantee was missing on exactly the setup
it was written for.

The ceiling is now expressed as what it is meant to protect. Background work may
run until the day's spend would leave less than a fixed reserve for whoever is
waiting on an answer, on both cost owners. A reserve and a quota look alike at
the boundary and mean opposite things in the middle: a quota stops useful
generation on a day nobody was ever going to interrupt, while a reserve costs it
nothing until the moment it would take the last of the day. An account
generating 1.45 million tokens of insights on its own plan keeps every one of
them and the chat still holds 400 000.

INTERACTIVE_RESERVE_SHARE replaces JOB_SURFACE_SHARE. The old name described a
quota over the jobs rather than a floor under the person waiting, and a name
that states the opposite of the intent is what put the wrong comparison in this
ledger twice already.

The fraction is a default an operator will want to change. The setting and its
documentation are separate work.
2026-09-11 12:55:52 +02:00
Marc-André Bombeck a889f4b1e2 test(e2e): read the session back through the page, not the shared pool
The offline fence spec already sends its account switch with the page's
own fetch, because every Playwright API context in the runner shares one
keep-alive agent and can be handed a socket the server closed on its idle
timeout. The read on the next line still went through that agent, and it
failed with read ECONNRESET on all three attempts, which fails the run
because CI treats a flaky test as a failure on purpose.

It reads through the page now, like the write above it. The two remaining
calls on the shared context sit in finally blocks that swallow their
errors, so they cannot fail a test.
2026-09-11 12:43:30 +02:00
Marc-André Bombeck 42b9aefdfd test(integration): retry a truncate that lost a deadlock
The suite wipes the database between files with one TRUNCATE, which needs
the strictest lock on every table at the same time. The server writes in
thirty-nine places without awaiting the result, so one of those can land
after the test that caused it has returned, and Postgres then picks the
truncate as the deadlock victim. It failed an unrelated file twice in two
days and passed on the rerun both times.

The truncate is retried up to four times, on that one error and no other,
with a short back-off. Three cases hold it there: a deadlock that clears,
an error that is not a deadlock and must not be retried at all, and a
deadlock that never clears and must still fail. All three go red without
the retry.
2026-09-11 12:38:31 +02:00
Marc-André Bombeck b565edc48d docs(ai): drop planning vocabulary from the ledger comments
CLAUDE.md forbids planning shorthand in committed artefacts, and this branch
introduced 74 lines of it across source, tests, a schema field and two
migrations. Someone reading the migration SQL in a year has no way to resolve a
wave letter or a round number, and a comment that points at something outside
the repository names no reason at all.

Three passes. A version followed by a parenthetical keeps the version and loses
the parenthetical, because the version says since when something holds. A
sentence that leaned on the vocabulary to carry its meaning is rewritten to
state the reason directly: the arrival reservation now says it was refused over
money the operator never spent, rather than naming the defect a wave existed to
remove. Three test titles carried the marker in the name itself and are renamed
to what they pin.

Comments only. No behaviour, no renames beyond those three titles.
2026-09-11 12:37:54 +02:00
Marc-André Bombeck 45599c527e fix(demo): the profile route writes only the baseline fields in the demo
Allowlisting `PUT /api/auth/profile` so the setup flow's baseline step could
finish also handed every visitor the shared demo account's contact email, its
display name, its full name and its insurer fields: the allowlist admits a
path and a method, and every field the handler behind it writes comes with
them. The justification beside the entry named three fields; the entry
admitted eleven.

The write is narrowed on the server, in `applyProfileUpdate`, to height, date
of birth and sex while `DEMO_MODE` is set — not in the client, which is the
party the allowlist exists to distrust. It happens ahead of the email conflict
check, which would otherwise answer "is this address registered here?" to
anybody who can open the demo. The display-name box goes read-only there, as
the anamnesis card already is, so nothing accepts input it will discard.

The entry's comment now lists what the handler writes and what is admitted.
2026-09-11 12:22:47 +02:00
Marc-André Bombeck 655eafa757 Merge internal markers out of six published API descriptions
Somebody reading the API document has no way to know what B1 or B6 mean.
2026-09-11 11:40:53 +02:00
Marc-André Bombeck ceefbc5571 fix(onboarding): a receipt on file is not evidence the provider works
The consent branch of the done screen's AI panel painted "insights work for
you right now" on the strength of the receipt alone, reading no health at all.
A person who had consented — including one who had just tapped the offer — was
told a dead provider was serving them. That is the claim-nobody-measured
defect closed at the offer end of the same panel, still open at the other.

The positive sentence now needs a healthy verdict as well. A consented account
on a provider that failed reads the same "not answering" note as anybody else,
and on an unmeasured one the panel claims nothing. The panel's four variants
are pinned across all three health states in every arm.
2026-09-11 11:38:31 +02:00
Marc-André Bombeck 87cf0dc215 docs(api): drop the internal markers from six published descriptions
Six operation descriptions in the API document opened with a version and
a bracketed letter-number code from the notes the work was planned in.
A client author reading the document has no way to know what B1 or B6
mean, and they mean nothing outside those notes. The version stays,
since it says when the operation appeared.
2026-09-11 11:23:28 +02:00
Marc-André Bombeck 34caeeea3c test(onboarding): the AI panel names the variant it settled on
The panel paints before its status query answers, and every variant inside it
is conditional, so an assertion that a variant is absent could pass on a
question that had simply not been answered yet — which is how the journey for
the unmeasured-provider case passed on a retry against the very defect it was
written to catch.

The panel now carries the variant it settled on, absent until it has settled,
and the three journeys wait on that instead of racing it. The third journey
covers the state a freshly deployed instance is in before its first AI call:
no offer, and no claim of an outage either.
2026-09-11 11:15:39 +02:00
Marc-André Bombeck 71305338bb Merge release entries in the reader's language
Every release entry since 1.35.2 rewritten so a reader can tell what changed for them.
2026-09-11 11:11:26 +02:00
Marc-André Bombeck c66bcbc295 feat(admin): the AI card shows the day's spend split by who paid
The provider-health route answered a spendToday payload that nothing rendered,
which is the pattern the two-ended rule exists to stop. It is also the screen
the operator opens when a surface refuses on budget, and the one mixed number
could not answer the question that raises: a day at 1.24 million tokens is
alarming until the card says that 151 200 of them were the instance's own key
and the rest ran on the users' own plans. The operator ceiling is enforced
against the second figure. Copy lands in all seven locales.
2026-09-11 11:11:17 +02:00
Marc-André Bombeck 7b21840630 fix(ai): the arrival reaction reserves through the shared ledger gate
The arrival-reaction claim carried its own copy of the reservation upsert so
the write could ride the claim transaction. The copy drifted: it learned to
write operator_tokens and kept gating on the day's mixed total, at the halved
background ceiling. On the row the wave was written for, 1.2 million tokens
served by the user's own plan, the reaction was refused all day at half the old
ceiling, reproducing the defect the wave exists to remove on the one surface it
forgot to convert. reserveBudget now takes the transaction client, so both
writes still roll back together and there is no second copy left to drift.

The row also remembers who paid for its reservation. The supersede refund in
data-arrival has no chain to ask and could only reverse the total, so the
operator share of every superseded reservation stayed on the row forever,
walking the operator's ceiling upward against spend that never happened. A
supersede is routine, not an edge case: any second measurement of the same kind
on the same local date before the worker runs. The resume path re-derived the
owner from a chain the health ledger may have reordered since, which leaks the
same way or drains another request's balance.

A structural guard makes the invariant executable. Every INSERT column list,
SET clause and RETURNING list that names one counter must name the other, and
the set of files holding raw ledger SQL is pinned. Both defects above were a
grep away and both would have failed this test.
2026-09-11 11:11:12 +02:00
Marc-André Bombeck 18ed57b867 fix(ai): every surface keeps a ceiling on the day's mixed total
The owner split left an operator-funded chain with no ceiling at all. Its arm
compared operator_tokens, and that counter returns to roughly zero on every
reconcile the user's own plan settled: on the 2026-09-11 evidence the shared
key answered 500 and codex served, so the counter never grew, every job
reservation was admitted forever, and a runaway client loop could write an
unbounded row. A pre-existing concurrency contract caught it from the other
side, two reservations that must not both pass one cap both passing.

reserveBudget now refuses when the owner's counter is over its cap OR the day's
mixed total is over the abuse ceiling, and a background surface gets its share
of that ceiling too, so background spend is bounded on the total and not only
under a counter the operator's key never fills. The surface is a required
argument, so the type checker enumerated every reservation site.

The hop guard learns the same lesson: an operator-funded fallback hop is now
rationed at the calling surface's ceiling rather than the full operator cap. A
job admitted under the job share could previously spend the whole 200 000 once
its chain fell back onto the shared key, which is the original defect reached
by the fallback path.

The job share applies only where the operator pays for the chain. Multiplying
whichever ceiling the chain resolved halved background generation for a
self-hoster on a local model, who costs the operator nothing.

Refusals now name the ceiling they hit and whose it was. A refusal used to emit
the day's mixed total and nothing else, which on an operator refusal is not the
counter that tripped.
2026-09-11 11:11:01 +02:00
Marc-André Bombeck 41596d1cb8 docs: comments name what the code does, not how it was built
Thirty-one files carried internal build vocabulary and anchors pointing at
notes that are not in the repository: a reader of `checklist.ts` in a year
would find its rationale keyed to a research id they cannot open, inside a
comment that also names an internal build stage. Two test titles carried the
same anchors.

The version tags and the whole of the reasoning stay; only the vocabulary and
the dangling references go, with the few sentences that were built around an
anchor rewritten to stand on their own.
2026-09-11 11:03:04 +02:00
Marc-André Bombeck bdc23f34ff test(e2e): the instance-wide journeys run in one project only
`onboarding-ai-offer.spec.ts` seeds the operator's AI key into `app_settings`
and replaces every `provider_health` row for both shared provider tags, then
restores both. Its own header says the inputs are instance-wide and it
configures serial mode, but serial mode only orders tests within a file: the
spec was absent from the project filter, so the mobile project ran it in a
second worker concurrently with the desktop one, each holding and clearing
state the other was asserting on — and any other spec reading AI availability
alongside them.

`invite-registration.spec.ts` joins the list for the smaller reason its
neighbours carry: two projects registering from one address share the same
five-per-fifteen-minutes budget.
2026-09-11 10:58:50 +02:00
Marc-André Bombeck ba29a5e471 fix(onboarding): no shared-provider offer where the grant cannot be made
The done screen's one-tap button posts `POST /api/consent/ai/web`, a path the
demo instance's edge allowlist refuses — correctly, since the demo is a single
shared account and a receipt one visitor minted would turn the operator's
provider on for everyone after them. The button was offered anyway, so a
visitor who took it got the generic "give it another try in a moment" toast on
the one screen whose whole purpose is not to say things it cannot back.

The route withholds the offer under `DEMO_MODE`, which leaves the panel in its
neutral form, claiming nothing either way.
2026-09-11 10:58:25 +02:00
Marc-André Bombeck 97174f470d fix(demo): the shared demo account takes no free text and no new record
The demo allowlist had grown two entries it should not carry. The demo is one
published account every visitor signs into, so `PUT /api/coach/about-me` was
an anonymous write of arbitrary text into the Coach prompt, persisted for
every later visitor until the next reseed; it is gone, and the baseline step's
anamnesis card renders read-only under `DEMO_MODE` so no visitor meets the
refusal as a failed confirm. `POST /api/managed-profiles` bought nothing: the
route opens with a fresh-MFA requirement the demo account cannot satisfy, so
the guardian arm was limited to finishing without the profile either way.

The baseline profile write stays, and the block's preamble now describes what
is actually admitted and why the two refusals are refusals.
2026-09-11 10:57:42 +02:00
Marc-André Bombeck 4c2175a584 fix(auth): the register page reads a session off the account payload
`isAuthenticated` holds the last-known state off a localStorage marker when
`/api/auth/me` fails at the transport level or with a 5xx, so the shell does
not sign people out on a blip. The register page gated its "already signed in"
panel on that flag, and on that path there is no account payload: an invited
household member opening the link during a 502 window was shown "You are
signed in as ." and a sign-out posting to the failing endpoint, with no way to
register at all.

The gate is now the payload itself, which is the only positive evidence of a
session and is equally absent while the probe is in flight.
2026-09-11 10:55:33 +02:00
Marc-André Bombeck 5c194cc9b9 fix(settings): a fresh managed connection reads as connected again
The managed-record integration projection mapped the ledger's new `unknown`
state to `disconnected`, but that mapping runs after the connection map has
already established a real credential. A guardian who connected Withings on a
child's record saw "Not connected" until the first hourly sync landed, beside
a row whose own `connected` field said true — an invitation to revoke and redo
the grant they had just made.

`state` on this projection reports that a pipe exists, not that it is live;
liveness is the sync verdict the card beside the pill already reads. With no
ledger row and a credential present, the pipe exists.
2026-09-11 10:54:56 +02:00
Marc-André Bombeck e991fdf65d fix(onboarding): a guardian is not told their own modules are leaving
The confirm screen derived "Out of the navigation: …" from the acting
account's module map and rendered it in every arm. In the "someone I look
after" arm the completion never touches that account: it applies the
derivation to the managed record, or, when none was created, to nothing at
all. So a parent answering for a child was told Workouts, Cycle and Documents
were leaving their own navigation when nothing was going to move.

The arm now derives the list from an empty map, which makes it empty, and the
sentence disappears with it.
2026-09-11 10:54:14 +02:00
Marc-André Bombeck 65a62350ea fix(onboarding): the AI panel claims an outage only when one was seen
The done screen folded the `unknown` provider verdict into `unhealthy` and
painted "This instance's provider is not answering right now." `unknown` is
an empty `provider_health` table, which is the state of every instance until
its first AI call — so the most common path through the screen made a claim
about something nobody had measured. It now falls to the neutral panel, which
says nothing either way; the offer is withheld in both cases as before.

The projection itself drew the same unearned conclusion from staleness alone:
a quiet instance whose last success was two days old read `unhealthy` without
any failure behind it. A verdict now needs an observed one — a row whose last
outcome was a failure — and a merely old success reads `unknown`.
2026-09-11 10:53:41 +02:00
Marc-André Bombeck f6472c8bc8 docs(changelog): drop what the 1.38.18 entry said about its own checks
The entry claimed the setup screens leave room for longer translations
and pass the accessibility check, which describes how the work was
verified rather than anything a reader gets, and it mentioned the demo
instance, which is ours and not theirs. What remains is that the setup
is available in every language the app has.
2026-09-11 10:53:07 +02:00
Marc-André Bombeck ff51b72cd1 chore(db): renumber the operator-token migration into the series
The branch numbered the coach_usage column migration 0341 over a 0340 that
exists on no branch. Prisma orders lexicographically, so the gap is inert for
migrate deploy, but a later 0340 merged after this ships applies out of order
and makes prisma migrate dev complain on every developer machine. The series
now runs 0339, 0340 with no hole.
2026-09-11 10:50:21 +02:00
Marc-André Bombeck f9eef5d46e docs(changelog): say what changed for the reader, not how it was checked
The entries for every released version since 1.35.2 were written from the
inside of the release process. They counted routes and modules, named
helpers and test files, and explained which check would catch a
regression. A person who uses the app, or hosts it for a family, could
not tell from them what had changed for them.

Each of those entries is rewritten: what someone saw, why it happened,
what happens now, and what they have to do, in that order, with the
paragraphs sorted by who they are for. Nothing is dropped. Every issue
number, contributor, environment variable, route, field, error code and
figure a reader can check is still there, in fewer and plainer words.
Headings, their order and their dates are untouched.

Entries between 1.27 and 1.34 keep their shape; only the sentences that
described a test or a sweep rather than a behaviour are restated. Older
history is left as it stands.
2026-09-11 10:47:50 +02:00
Marc-André Bombeck 1885b7867d Merge wave D — the shared provider is offered only when it is known to work
The done screen's assistant panel stops claiming that the instance's
provider already serves the person. A tri-state read over the operator's
own provider ledger decides between a one-tap offer that mints the
consent receipt, a plain "not answering right now" note, and today's
setup link; anything unknown, any read error, a managed profile and an
operator who has switched the assistant off all fall to no offer.

# Conflicts:
#	e2e/setup/global-setup.ts
2026-09-11 10:25:19 +02:00
Marc-André Bombeck 4d7b326fda Merge wave B — the connect step reads liveness, not a latched field
A provider with no sync history reports "unknown" instead of "connected",
so a fresh account is no longer told a device it never linked is already
delivering; the connect step resolves the sync verdict into four honest
tiles, records the flow's result only for a connection that is actually
serving, points an unconfigured provider at its credentials, and steps
over a source the account already has.
2026-09-11 10:24:54 +02:00
Marc-André Bombeck 3642bbe4de Merge wave C — the flow cannot strand, mislead or silently switch off
The getting-started checklist's data queries follow the same setup rule as
its visibility, so a settled account stops being told to do what it has
done; a failed completion leaves the confirm screen usable; an empty
multi-select is no longer recorded as an answer; the confirm screen names
the modules a run would take out of the navigation; the settings links it
offers work before the first completion; and demo mode can fill the
baseline it is shown.
2026-09-11 10:24:48 +02:00
Marc-André Bombeck 30339d8f7d Merge wave A — the invitation link lands on registration, never on login
The invite landing is public in the client shell as well as the proxy, the
edge answers the redirect itself so no shell mounts, and registration
refuses to run over a live session instead of silently swapping the
caller's cookie for the new account's.
2026-09-11 10:24:43 +02:00
Marc-André Bombeck b750e0bc7d feat(admin): the AI readout separates operator-paid tokens
The provider-health endpoint showed delivery health only. When a surface
refuses on budget the operator's next question is which ceiling he hit,
and one mixed token figure cannot answer it: a day at 1.24 M tokens looks
alarming until you see that 151 200 of them ran on the instance's own key
and the rest on the users' plans.

`spendToday` carries the day's key and both counters, aggregated across
accounts. The operator ceiling is enforced against `operatorTokens`, so
that is the figure the readout puts beside the total.
2026-09-11 10:18:26 +02:00
Marc-André Bombeck d3196ee69e fix(ai): background generation cannot spend the interactive day
The automatic generators — status and reference cards, the briefing, the
arrival reaction, the nudge, document summaries and the index backfill —
reserved against the same ceiling as the chat. On the operator's account
that meant 150-330 ledger rows a day, 172 metric generations before
06:42Z, and a ceiling already spent when he opened the chat.

Every background surface now reserves through
`resolveDailyCapFor("job", chain)`: half the cost owner's ceiling, all
job surfaces together. The interactive routes keep the whole ceiling, so
a day of background work can no longer take the user's own away.
2026-09-11 10:09:34 +02:00
Marc-André Bombeck 2c46712e13 fix(ai): the operator cap counts only tokens the operator paid for
The reservation compared the day's TOTAL against whichever ceiling the
chain resolved, and the chain walker's hop guard did the same. On an
account whose background jobs run on the user's own ChatGPT plan, both
saw a total the operator had not paid for: the chat refused at 06:42Z
with 513 539 tokens against the 200 000 operator ceiling, and the
fallback hop to the shared key was closed on the same arithmetic.

An operator-funded chain is now measured against `operator_tokens` and a
user-plan chain keeps its abuse ceiling on the total; the hop guard reads
the operator share too. A day of turns the user's own plan paid for can
no longer lock anyone out of the operator's ceiling.
2026-09-11 09:56:44 +02:00
Marc-André Bombeck d2f47e3bb5 fix(auth): the refusal code joins the published catalogue
Two structural guards caught the new gate. The error-code catalogue is derived
from the route tree on every run and fails in both directions, so a code the
server emits and does not publish is a client that cannot branch on it; the
session-surface guard freezes the short list of files under `src/app` that
resolve a caller without `requireAuth`, and the register route now belongs on
it — `requireAuth` is the wrong gate there twice over, since it would throw at
the anonymous caller the route exists for and this route wants the ABSENCE of a
session.

The code is `auth.already_authenticated` rather than the bare
`already_authenticated`: the catalogue's own header rules that new codes are
dot.case, and it sits beside `auth.mfa.code_invalid` in the same family. The
OpenAPI document renders the catalogue into the ErrorEnvelope description, so
it is regenerated.
2026-09-11 09:51:32 +02:00
Marc-André Bombeck 3fc06d0b10 test(e2e): the connect journey covers the fall-through too
Running the two cases in parallel let each walk the other's account state, so
they go serial like the sibling journeys. The second case also asserted the
wrong thing: with a Q2 area answered as well, an already-delivering source
correctly falls through to `log-reading` — that IS the fix. Split into three:
nothing connected, a connection with somewhere to fall to, and a connection
that is the only task the answers name.
2026-09-11 09:47:43 +02:00
Marc-André Bombeck badef28e96 feat(ai): the daily ledger records which tokens the operator paid for
`coach_usage` counted one number per (user, day). A turn served by the
user's own ChatGPT plan after the operator's shared key answered 500 was
therefore charged to the operator-cost cap, and the operator's chat was
locked out every morning by background work he pays for himself.

The ledger gains `operator_tokens`: the share of `total_tokens` served by
an operator-funded provider. `reserveBudget` books a reservation to the
owner of the chain's primary and `reconcileSpend` settles it against the
provider that actually served, both inside the same statements as the
total so concurrent requests can never see one counter without the other.
Every call site names its cost owner and its serving hop; the argument is
required, so a new surface cannot inherit the old blind accounting.
2026-09-11 09:42:14 +02:00
Marc-André Bombeck 0290554d36 test(e2e): an invite link registers from a cookie-less window
Every layer of the invite chain had unit coverage and the chain was broken
anyway: the proxy test proved the edge admits the landing, the page test proved
it redirects onto the registration form, and neither could see that the
redirect arrives in an RSC flight payload after the shell has already flushed.
The operator's path — mint an invitation, open the URL in a private window,
reach a usable form — was exercised by no spec at any level.

The new spec mints a real invitation in the admin UI and opens it twice: once
in a genuinely cookie-less context, asserting both where the visitor lands and
that they never passed through the sign-in page, and once in the admin's own
window, asserting the explaining panel and that the admin's session survives. A
third case pins the server half through the wire. Against `origin/main` all
three fail — the anonymous visitor lands on `/auth/login`, the panel does not
exist, and the registration POST answers 201 over a live session.

The minted URL gains a test id so the spec reads it from its own element
rather than from the first paragraph in the ticket.
2026-09-11 09:40:26 +02:00
Marc-André Bombeck e5cfdc9fdf test(e2e): the AI offer follows the shared provider's health
Two runs on one account, and the only difference between them is a row in
provider_health: a success inside the freshness window brings the offer and
the tap leaves an active ai_full receipt; a dead credential inside its
cooldown brings 'not answering' and no button at all.

The seed is instance-wide because the projection is - a fresh account's own
ledger is empty by construction - so the spec runs serially and puts the
operator key and the ledger rows back afterwards. The offer path asserts
that no provider was called: the flow reads a projection and never probes.

Verified as a real check, not a tautology: moving the seeded success from 30
minutes to 25 hours ago makes the offer case fail.
2026-09-11 09:36:07 +02:00
Marc-André Bombeck bda18f9e2d test(profile): the edge proxy is not a profile submitter
The demo allowlist names a path and a method as data, which reads to the
submitter matcher exactly like a request expression. proxy.ts submits
nothing and has no answer to read, so it is excluded by name.
2026-09-11 09:35:17 +02:00
Marc-André Bombeck dfa5b9a5e0 test(e2e): the connect journey asserts after the status resolves
No journey reached the connect arm: bp answers `manual`, visit answers
`file`, and the child path ends at confirm. The a11y sweep opened the screen
and asserted the connect card was visible — which it was, for the few hundred
milliseconds before the status envelope resolved, so the sweep passed through
the defect rather than catching it.

The new journey answers Q4 with a wearable and asserts only after
`GET /api/integrations/status` has settled: nothing is claimed for an account
with no connection and no result is stamped on its behalf, and a connection
seeded as delivering is acknowledged rather than offered. The a11y sweep now
waits for the tile the screen settled on instead of the frame before it.
2026-09-11 09:31:59 +02:00
Marc-André Bombeck 982c35287d fix(demo): the setup flow's baseline writes are allowlisted
A demo visitor who typed a height on the confirm screen got a 403 and a
generic toast, and the "someone I look after" arm could only take
"Finish without the profile": the profile PUT, the self-context PUT and
the managed-profile POST were missing from the demo allowlist, so only
the empty-form path completed.

All three are added, pinned per method as the rest of the list is. None
of them creates health data.
2026-09-11 09:26:10 +02:00
Marc-André Bombeck a6dedffdb8 fix(onboarding): no dead settings links before completion
Both Settings links on the confirm screen are page routes, and the
onboarding cookie that sends every page route back into the flow is
cleared by the completion this very screen calls. On a first run they
could not go anywhere.

They now render as plain text until the flow has been completed once.
The words stay, because where a setting lives is true either way.
2026-09-11 09:25:28 +02:00
Marc-André Bombeck e9e4a4b44d fix(onboarding): confirm names the modules leaving the nav
The screen listed what the answers switch on and said everything else
stays one click away under Settings, Modules. That is true of
reachability and false of the navigation entry: a module the answers do
not ask for is written off by the completion's derivation.

It now names those modules, read through the registry's own merge rule
and intersected with the map the navigation shows today, so nothing is
claimed about a module the account payload says nothing about.
2026-09-11 09:24:36 +02:00
Marc-André Bombeck 8d81ac0708 fix(onboarding): a connected source is acknowledged, not offered
`chooseFirstResultTask` read the answers alone, so an account whose WHOOP had
been feeding the dashboard for months was sent to go and connect WHOOP. It
takes the delivering sources now; the server still picks from the answers,
having no status in hand, and the screen re-picks once the envelope resolves.

The fall-through stops where there is nowhere to fall to: a person whose one
answer is an already-connected source keeps the step and is told what was
found, rather than ending the flow on no result at all.
2026-09-11 09:22:18 +02:00
Marc-André Bombeck be7fbe37d5 docs(access): the grant card says the invitee needs an account
A sharing invitation carries no link and nothing is e-mailed — it is addressed
to an account that already exists on this instance, and the person accepts it
from inside their own session. The card's input hint already named the account
requirement and left the rest unsaid, so an inviter looking for a link to send
had nothing to find and no reason to stop looking. The card now names where the
invitation turns up, in all seven locales.
2026-09-11 09:16:24 +02:00
Marc-André Bombeck da58d16642 fix(onboarding): the connect step reads the sync verdict
The step decided "connected" from the ledger's `state` and had one piece of
copy for every outcome: "the first sync is in progress". That sentence was
false for a connection delivering for months, and worse for one the person
has to repair — the screen said everything was fine while the grant was gone.

`connectSourceView` resolves the envelope entry into one of four tiles and
says whether the flow may record its result. Only `pending_first_sync` and
`fresh` may; `stale` is acknowledged without being claimed as new; `stalled`,
`failing`, `reauth_required` and `parked` name the state and link at the page
that can change it. An unresolved envelope paints no tile at all.

A source the instance cannot connect — a BYO provider with no client pair, a
shared-app provider with no app — now points at the credentials instead of
offering a "Connect" button onto a card that has none.
2026-09-11 09:15:32 +02:00
Marc-André Bombeck ce3c844a58 fix(auth): an invitation never registers over a live session
`POST /api/auth/register` read no session at all, so a request carrying a valid
`healthlog_session` was handled exactly like an anonymous one and the
unconditional `createSession` at the end replaced the caller's cookie with the
new account's. An admin opening his own invite link to check it was signed out
of his admin account and into a stranger's onboarding, his previous session row
still valid server-side and no longer reachable.

The route now resolves the optional session first and refuses with 409
`already_authenticated`, before the rate-limit bucket is spent and before the
invitation is consumed, so a signed-in visitor neither burns a use nor locks
the door for the person the invitation is for. The register page renders an
explaining panel with a sign-out button in place of the form, so nobody has to
fill three inputs to discover the refusal; signing out returns to the same
invitation rather than to the login screen. Copy lands in all seven locales.
2026-09-11 09:15:11 +02:00
Marc-André Bombeck 77a09a5080 fix(onboarding): an empty multi-select is not an answer
Q2, Q4 and Q6 let "Weiter" write an answer with nothing ticked. On Q2
that answered "no areas", which is what switched every optional module
off for somebody whose click meant "no preference"; on Q6 it marked the
step done while recording no unit at all.

An empty selection now yields no body, so the primary button is dead
until something is chosen. Skip stays the way past, and Skip is the
conservative derivation the completion route already applies.
2026-09-11 09:14:34 +02:00
Marc-André Bombeck 74ae672373 feat(onboarding): the done screen offers the provider only when it works
The card read one field and made two claims from it: that insights work,
and that no setup is needed. The first was a presence read - it knew a key
existed, never that it answered - and the second skipped the consent
receipt the egress actually needs, so the person who believed the note met
a consent.ai.required refusal on their first briefing.

Four branches now, one button. The offer appears only when the server says
the shared provider is known to work and nothing forbids it, and the tap
posts the affirmative web intent. An unhealthy or unknown verdict paints
'not answering' with no button. When the offer is refused for a reason that
is not health, the panel stays neutral rather than blaming the provider.
The note survives for the one state it was ever true of: consent on file.

The sample, the ladder, the 'fully useful without' line and the setup link
are identical in every branch. Copy in all seven locales.
2026-09-11 09:13:23 +02:00
Marc-André Bombeck 0e79b195b0 fix(onboarding): a failed completion leaves confirm usable
The baseline form raised its pending flag and lowered it on only two of
three exits; the success path went through the confirm screen's finish(),
which caught its own error and returned normally. A failed completion
therefore disabled both buttons until the page was reloaded.

The reset now lives in a finally, finish() rethrows so the form sees the
failure, and the two managed-arm buttons report it themselves. The step
passes before the completion run off a ledger ref, so a retry after a
failure midway no longer re-sends a step the ledger already carries.
2026-09-11 09:12:36 +02:00
Marc-André Bombeck cfca84a294 fix(auth): the invite landing redirects at the edge, no shell, no race
The proxy now answers `/invite/<token>` with a real 307 onto
`/auth/register?invite=…` (or a bare `/auth/register` when the segment fails
the `hlv_` shape gate), carrying the baseline transport headers plus the
no-store / noindex / no-referrer hardening the token-in-path surface has had
since v1.17.0.

Before this the redirect came from the landing page, which Next delivers in the
RSC flight payload rather than as a server 307 — the shell mounted first and
raced it. At the edge there is no HTML and no hydration, so there is nothing to
race. The page stays in place as the fallback for any path that bypasses the
proxy matcher.
2026-09-11 09:09:46 +02:00
Marc-André Bombeck 0bdbf009f6 fix(integrations): a provider with no history is "unknown"
The ledger's synthetic "no row" snapshot returned `state: "connected"`, so
the field's default meant the opposite of its name: every account that had
never connected a provider published `connected` on the status envelope.
Settings survived it by never reading `state`; the setup flow's connect step
did read it, and told brand-new accounts their wearable was connected.

The snapshot now reads `unknown`. `syncHealth.verdict` is unchanged and stays
the only liveness truth; the managed-record projection maps `unknown` onto
`disconnected` the way it already maps a missing connection.
2026-09-11 09:08:38 +02:00
Marc-André Bombeck 753438a329 fix(auth): the invite landing is public in the client shell too
`/invite/<token>` has been public in `proxy.ts` since v1.17.0 and was never
added to the client-side gate in `auth-shell.tsx`. Next streams the shell
before the landing page's RSC redirect resolves, so the shell classified the
route as protected, `/api/auth/me` answered 401, and `router.replace(
"/auth/login")` won the race — the operator's invite link landed on the sign-in
page it was meant to bypass.

The shell now lists `/invite/`, and lists the `/auth/` family as the prefix the
edge already admits rather than as two individual pages, so a future auth page
cannot inherit the same defect. `PUBLIC_PATHS` is exported from `proxy.ts` so a
new parameterised guard can render the shell at every page prefix the edge lets
through and fail when the two lists drift apart again.
2026-09-11 09:08:07 +02:00
Marc-André Bombeck 0d2bad69e3 feat(ai): the provider status says whether the shared provider fits
GET /api/user/ai-provider gains three additive fields: the instance-wide
health tri-state, whether this caller already holds a receipt, and the one
boolean that answers 'may the shared provider be offered in one tap'.

The offer is the conjunction of five preconditions and every one of them
can only take it away: the operator's provider is the one that would serve
the caller, the health is demonstrably healthy, the assistant master and
coach flags are on, the acting record holds its own credentials, and no
receipt is on file yet. A managed profile is excluded by the positive form
of the policy test - 'not deny' would have let a child's record through.

Nothing here probes a provider; a probe would bill the operator for every
registration on the instance. docs/api/openapi.yaml is regenerated from the
schema source.
2026-09-11 09:07:45 +02:00
Marc-André Bombeck dec5732687 fix(onboarding): checklist queries follow its own setup rule
The card's visibility rule gained a "ran the setup flow" disjunct; the
component's query gate kept restating the older half of it. A wizard-run
account past five readings therefore saw a permanent checklist whose
medication, data-source, notification and insight rows were frozen at
"not done", because every supporting query was disabled.

Both places now read one exported predicate, isStillInSetup, which also
keeps the rows live for a restarted run nobody finished.
2026-09-11 09:07:41 +02:00
Marc-André Bombeck 82b7c11b05 feat(ai): a tri-state health of the instance's shared provider, fail closed
The done screen promised working insights on the strength of a presence
read. A fresh account's own provider-health ledger is empty by
construction (the table is unique on user + provider), so the evidence has
to be an instance-wide fold. It folds across accounts and returns three
words: no counts, no timestamps, no account can be inferred from it.

Fails closed against the grain of the ledger it reads. There the fail-open
protects a generation already running; here the output is a promise made to
a person, so an empty table, a timeout or a read error is 'unknown', and
'unknown' buys nothing.
2026-09-11 09:04:50 +02:00
Marc-André Bombeck 274923a060 Merge release v1.38.18
The first run asks what you need and switches on exactly that; the five-step wizard and the two columns it wrote are gone.
2026-09-11 00:09:59 +02:00
Marc-André Bombeck 677019b53b fix(onboarding): let the confirm screen's sex select shrink at 390 px
The string-headroom sweep went red on CI for French at phone width by
two pixels the Mac never showed: the runner's fallback fonts render a
touch wider. The box was the sex select on the confirm screen — its
value is whitespace-nowrap, and a grid item's automatic minimum is its
min-content, so the track was pinned at the padded option's width and
the shell scrolled sideways. Both cells of that row and the trigger
carry min-w-0 now: the track takes the free space and the value
ellipsises, which is the select primitive's own design. Reproduced and
verified locally by narrowing the viewport to 372 px, which stands in
for the wider fonts (336 px of scroll before, none after).

The sweep now names what overflowed: the boxes past the shell's edge,
with tag, slot, classes, text prefix and edges, ride the failure
message and the outside list, so the next red run says what rather
than only that.
2026-09-10 23:50:30 +02:00
Marc-André Bombeck aba785f9f4 test(e2e): expect the module-off notice on a direct visit, not a redirect
A module page whose switch is off answers with the shared notice that
names the switch and offers the Modules settings, so a bookmark or a
report link explains itself instead of bouncing home. The vaccinations
journey pinned the old redirect and went red for the behaviour the setup
flow introduces on purpose.
2026-09-10 23:24:45 +02:00
Marc-André Bombeck 1abf528925 chore(release): v1.38.18 — the first run asks what you need and switches on exactly that
Bump the version, the service-worker fallback and the OpenAPI document,
and add the CHANGELOG entry for v1.38.18.
2026-09-10 23:09:23 +02:00
Marc-André Bombeck 8ed46eef58 Merge remote-tracking branch 'origin/main' into feat/onboarding-wizard 2026-09-10 20:53:38 +02:00
Marc-André Bombeck 85151ca24e Merge release v1.38.17
A webhook or ntfy target on your own network can be reached again with the operator's say-so, the test button says why a private target was refused, and the second of two close doses can be logged from the card again.
2026-09-10 20:52:57 +02:00
Marc-André Bombeck 550a7b87d7 fix(medications): measure a row's nearest occurrence across sibling schedules
The nearest test enumerated only the schedule under test, and production
rows carry no schedule identity. On a medication composed of sibling
schedule rows (08:00 daily plus 12:00 daily, the wizard's compose shape) a
row snapped exactly to A's 08:00 was also asked about B's 12:00, and B's
own occurrences alone never showed that A's 08:00 is nearer: next-due, the
display due and the compliance cycle all answered tomorrow's 08:00 at 09:00
local, the same swallow one level up.

The neighbour set is now the union of every schedule's occurrences within
the radius, memoised per row, since it depends on the row alone and a
predicate asks about many slots. The rolling short-circuit still looks at
the schedule under test only. The era filter in the next-due predicate
compared a field no caller ever populated, so it is gone along with the
test that pinned it; the era floor lives in the overdue search's band
range and in the forward walk's start at now, as it always did in
production.

Tests: sibling schedules in both next-due and the compliance cycle, the
exact tie between two slots, the 25-hour fall-back day (a pair across the
repeated hour, and a row anchored in the old offset), and the ad-hoc
epsilon case now stands on the ad-hoc row alone.
2026-09-10 20:34:36 +02:00
Marc-André Bombeck 95140e5aa7 fix(medications): resolve one occurrence per intake row, the nearest
A taken, skipped or auto-missed row counted as resolving every occurrence
within six hours of its anchor. The radius was sized for the twice-daily
12 h gap, so on any schedule whose neighbouring doses sit closer than that
(19:49 and 23:59, 08:00 and 12:00, every four hours) the first dose's row
resolved the second occurrence too: the next-due walk jumped to tomorrow,
the card offered tomorrow's first dose, and a skip pressed next landed
there. The second dose could not be logged from the card at all.

Reproduced with a Europe/Berlin account on 19:49 + 23:59: the 19:49 take
left the 23:59 row pending and the skip was written to tomorrow's 19:49.
The compliance-journey e2e spec exposed the same thing in every run that
started after noon, when its twin slot is 23:59.

Rule, in slot-resolution.ts and shared by the list's next-due, the card's
overdue search and the compliance current-cycle descriptor: a row resolves
exactly one occurrence, the one nearest its anchor, and only within the
drift radius. An exact match short-circuits; a drifted anchor is measured
against every occurrence the schedule emits within the radius and loses to
any nearer one (ties go to the earlier occurrence), so the effective reach
is min(radius, half the gap to the neighbour) and a sibling can never be
swallowed. Rolling cadences skip the nearest test, their occurrences are
at least a day apart. Ad-hoc rows keep the one-minute epsilon, now in the
cycle descriptor as well, so the card's due slot and its cycle state agree.

The drift tolerance itself stays: it covers a row whose anchor sits off the
canonical instant, a pre-snap row or an instant that moved under it across
a DST shift, which is what the radius was introduced for in v1.15.10.
2026-09-10 20:17:38 +02:00
Marc-André Bombeck 80171436e3 chore(release): v1.38.17 — a private notification target can be listed by the operator
Bump the version, the service-worker fallback and the OpenAPI document,
and add the CHANGELOG entry for v1.38.17.
2026-09-10 19:27:49 +02:00
Marc-André Bombeck 2380a4e7e6 docs(api): regenerate the contract for the loopback wording
The four notification routes describe private_origin_not_grantable as
link-local, metadata or unspecified only; the generated YAML follows.

Refs #947
2026-09-10 19:18:16 +02:00
Marc-André Bombeck 08e66a464b Run the child journey's two tests one after the other
Both reset and walk the one account; on two workers each undid the
other's setup mid-flow, which is the reason the two sweeps were already
serial.
2026-09-10 19:18:02 +02:00
Marc-André Bombeck 94bed12edc fix(egress): keep loopback grantable under an exact operator origin
A Nightscout self-host on host networking with
NIGHTSCOUT_PRIVATE_ORIGINS=http://localhost:1337 worked before and must
keep working unchanged; an operator who lists an exact loopback origin
with its port has made the same deliberate decision as one who lists a
LAN origin. The never-grantable floor is now the unspecified address,
link-local and the metadata endpoint only. Loopback (127/8, ::1,
localhost) is grantable when listed exactly, still resolved and pinned
at connect time with redirects forbidden, and still refused when not
listed.

::1 is answered before the embedded-IPv4 unwrap, which read it as the
IPv4-compatible spelling of 0.0.0.1 and refused it as unspecified. The
pinned Nightscout transport test runs the real floor again. Each refused
range keeps its own test; loopback moves to the grantable-when-listed
set with a test that an unlisted loopback is still refused, and a
Nightscout grant of http://localhost:1337 is asserted to parse.

Refs #947
2026-09-10 19:08:04 +02:00
Marc-André Bombeck a2e407909c Never derive answers given for somebody else onto the guardian
"Finish without the profile" completed the flow with no record id, and
the route then derived the child's answers onto the guardian's own
record. The server now decides: answers given for somebody else with no
record to apply them to complete and latch the flow without deriving or
seeding anything, whatever the client sent. The checklist carries the
profile instead and reads none of those answers as the guardian's own.

A record id the caller does not guard answers 404 like every
id-addressed managed-profile route, one answer for missing, not managed
and not theirs alike; the contract documents the field, the 404 and the
422 text. Pinned by two integration cases and a second child journey.
2026-09-10 18:58:21 +02:00
Marc-André Bombeck 9c306f04e7 fix(notifications): name the never-grantable refusal and redact the grant log
A loopback, link-local or metadata target answered
private_origin_not_approved with a message telling the user to have the
operator list it, and the parser refuses such an entry forever: a dead
end the route test even pinned. Those targets now answer
private_origin_not_grantable (catalogued, on all four routes, translated
in seven locales) with a message that says no grant can open them and
to use the relay's LAN address. Both senders carry the reason into the
outcome so the test button forwards the same code.

The malformed-entry warning printed the entry verbatim, which is where
a pasted token or userinfo sits; the parser now hands callers scheme
and host only, plus the reason in words. The Nightscout list throws a
named error with that redacted entry and reason, and the connect route
answers it as a 422 with the message instead of a bare 500, so a
self-host that listed http://localhost:1337 reads what to change.

The two settings cards translate a coded save refusal like the test
button does; the docs and the changelog name the sub-host and sibling-
port narrowing; the dispatcher floor tests assert the policy marker so
a real NXDOMAIN cannot pass for a refusal.

Refs #947
2026-09-10 18:45:57 +02:00
Marc-André Bombeck 55ff6df205 Merge remote-tracking branch 'origin/main' into feat/onboarding-wizard
# Conflicts:
#	docs/api/openapi.yaml
#	src/lib/openapi/error-codes.ts
2026-09-10 18:20:07 +02:00
Marc-André Bombeck 6adbee581e Apply the review of the setup flow: the child's answers reach the child
"Someone I look after" derived the child's answers onto the guardian's
own record. The completion now takes the managed record the profile
step just created, checks the same access rule the guardian's modules
route applies, and lands the same derivation and dashboard seed on that
record through the same record-keyed write; the guardian's own flow is
stamped complete and latched without touching its map. Three
integration cases pin it, and the child journey reads the child's map
through a real switch — it asserted the guardian's map before, which
pinned the wrong record.

Also from the review: the checklist's visit row read a meta the visits
list never publishes and now counts its body; the first-result tile
read the measurements list as an array and now shows the reading; the
demo allowlist admits the disclaimer and tour writes, with a structural
test over every onboarding route file; restart clears the old first
result, and the screen trusts the ledger before painting a result as
done; the headroom sweep's raw-key check matches the flow's own key
shapes; the demo migration script stops copying the dropped column; the
questions-to-pass rule and the shell's onboarding-path rule are pure and
pinned; the baseline form composes the shared action row; the schema
diff loses the unrelated formatting churn.
2026-09-10 18:19:34 +02:00
Marc-André Bombeck 71175290af Merge remote-tracking branch 'origin/main' into fix/private-notification-origins
# Conflicts:
#	src/app/api/settings/ntfy/route.ts
#	src/app/api/settings/webhook/route.ts
2026-09-10 18:07:55 +02:00
Marc-André Bombeck 761a5a54c1 fix(notifications): keep the egress mark from clobbering a set action
The mark named its action unconditionally, so a job that had already
named its own (the low-stock underflow branch) or a settings route
whose test then failed at the relay lost that name on the wide event.
Set the action only when the event has none, and always land the
channel and origin meta pair, through a small hasAction() on the
builder. Note the parse-time floor on the Nightscout page, which shares
the grammar.

Refs #947
2026-09-10 16:51:57 +02:00
Marc-André Bombeck 5c5a592177 Let the setup flow's action rows wrap, and measure headroom per word
At 390 px with labels a third longer the action row pushed "Confirm and
continue" past the viewport; both rows now wrap. The string-headroom
sweep lengthens every word by 30% rather than hanging the whole surplus
on the last one — that manufactured an unbreakable run no locale
produces — leaves screen-reader-only boxes alone, and accepts a select
value's ellipsis, which is the primitive's design app-wide.
2026-09-10 16:49:18 +02:00
Marc-André Bombeck 9630b59973 chore(compose): forward and document NOTIFICATION_PRIVATE_ORIGINS
Put the variable on the compose environment whitelist (without it a
value in .env never reaches the process), on both example files, and in
the env manifest so check-env reports it. The self-hosting notifications
page gains a section on notification targets on a private network: the
exact-origin grammar, what stays refused even when listed, and a table
of which target is refused where so an operator knows which lever to
pull.

Refs #947
2026-09-10 16:47:55 +02:00
Marc-André Bombeck 984a75d036 fix(api): name the private-origin refusal on webhook and ntfy routes
The save routes evaluate the same policy the senders do. A target on a
private network the operator has not listed is a 422 with
meta.errorCode = private_origin_not_approved and a message that names
NOTIFICATION_PRIVATE_ORIGINS, instead of the generic "Invalid data"; a
listed private address saves although the plain public floor would
have refused it. The settings schemas take the target predicate as a
parameter so the validator module never reads the environment; the
exported constants keep the public floor for the OpenAPI contract.

The test routes forward the sender's refusal as the same 422 and code
instead of a bare 500, so the card can say why the test failed rather
than sending the operator to the wide-event log. A delivery fault is
still a 500. Both test routes and the dispatcher reach the same sender
function, and a structural test holds them there.

The OpenAPI descriptions name the code on all four routes; the test
button's error map gains the code in every locale.

Refs #947
2026-09-10 16:46:13 +02:00
Marc-André Bombeck 5061f423a8 Merge release v1.38.16
The API says what it refused and why, on every route, and the admin page says whether last night's off-host copy landed for each account.
2026-09-10 16:39:54 +02:00
Marc-André Bombeck 6c75c4f39f feat(notifications): honour NOTIFICATION_PRIVATE_ORIGINS on send
A self-hoster's Gotify or ntfy on a private network was refused at
dial time with no operator override: both senders pinned the public
resolver, and the two grants that exist for other surfaces were never
read here. Add the third grant, NOTIFICATION_PRIVATE_ORIGINS, a comma-
separated list of exact origins read from the server environment.

A listed origin runs under the operator-approved pin: still resolved
and pinned inside the connector, redirects forbidden, loopback and
metadata answers refused. An origin not listed keeps the public pin it
always had. A malformed entry is logged once and grants nothing, and
the valid entries beside it keep working, so a typo in one relay's
origin cannot take every public webhook down with it. There is no
`=true`, CIDR, wildcard or suffix form.

One function, evaluateNotificationTarget, gives the verdict for both
senders, so the test button and the scheduled reminder cannot disagree.
A refusal now carries its own reason (`*_private_origin_refused`) and
an errorCode instead of collapsing into a network error, and a send
that used the grant marks the wide event with
`notification.egress.private_origin` and the channel plus origin.

The pin inventory keeps both senders in the conditional shape and
refuses a bare true or false in either.

Refs #947
2026-09-10 16:39:24 +02:00
Marc-André Bombeck d91a8dfebe Make the setup flow pass its own journeys and axe sweep
Run against the standalone build, the four journeys and the axe sweep
surfaced five things the unit tier could not see. The completion route
derives only once every question is settled, and Q6 stays pending for
somebody with no unit-bearing area — the confirm screen now passes the
questions the flow never showed before it completes. The dashboard seed
matched a JSON null where the unset column is a SQL NULL, so it never
landed; the retired step route carried the same filter. The auth shell's
onboarding branch matched only the front door, so every question screen
rendered inside the full app chrome with the sidebar. Inline links
relied on colour alone, the step list sat outside any landmark, and the
baseline form brought a second h1 onto the confirm screen. The two
sweeps run serially, since each drives one account through the API.

The integration file gains the seed case that would have caught the
null filter.
2026-09-10 16:38:47 +02:00
Marc-André Bombeck ea3a8deed2 fix(egress): share the origin-grant grammar and floor its ranges
Lift the Nightscout allowlist parser and verdict into
src/lib/private-origin-policy.ts so a second operator grant can reuse
one grammar instead of a second parser. The Nightscout validator keeps
its exported names and behaviour; its tests are unchanged.

Add the floor both precedents lacked: an entry whose host is a literal
address in 127/8, 0/8, 169.254/16, ::, ::1 or fe80::/10 is not a grant,
and the operator-approved pinned dispatcher drops an answer in those
ranges even when the name is listed. RFC1918, CGNAT and IPv6 unique-
local stay grantable; that is what the list is for. Loopback inside the
container is the app itself, and on host networking every admin port of
the host; link-local is the cloud-metadata endpoint. No relay lives on
either.

The pinned Nightscout transport test resolves its listed name to a
loopback server on purpose, so it stubs the grantable-address predicate
for that harness only.

Refs #947
2026-09-10 16:34:04 +02:00
Marc-André Bombeck dd3eb0396e test(e2e): keep the adherence journey's second dose on today's calendar
The journey anchors one dose at the clock and its twin twelve hours on, and
the twin wrapped past midnight for every run that started after noon. The
skip then landed on tomorrow's slot and the dashboard tile read one taken
over two expected where the skip-parity figure is a hundred; the green runs
on main were all morning runs. The twin is twelve hours on before noon and
the last minute of the day after it, so the skip lands on the day the tile
reads whenever the suite runs.
2026-09-10 16:20:44 +02:00
Marc-André Bombeck e98457151d Regenerate the OpenAPI document for the error-code catalogue
The catalogue lists the answers and restart codes and no longer the
retired step ones, and the generated document quotes that list. The
skippable-step id type nothing read goes with it.
2026-09-10 16:16:36 +02:00
Marc-André Bombeck 8c7cdcfc2b Tighten the setup flow after a review of the whole diff
The done screen moves focus to its heading like every other screen; the
confirm screen's preference list holds only dt/dd pairs and the settings
link stands beside it; Back from Q1 is not offered once the flow has
been entered, because the front door would resume past the welcome and
bounce straight back; the medication task records no target on the
ledger, as the contract says, and keeps the id on the screen; and the
two success affordances go through the outcome module rather than a
hand-rolled tick. The error-code catalogue lists the answers and restart
codes and no longer the retired step ones, and the session-surface guard
learns the one new deriving helper the onboarding pages read through.
2026-09-10 16:09:18 +02:00
Marc-André Bombeck d37993822e fix(admin): keep the off-host freshness badges readable in both themes
The destructive tone as 12px badge text on its own wash measures 4.08:1 in
the light theme and 3.99:1 in the dark one; the muted foreground on the
muted wash 3.6:1 in the dark one. The badge takes the shape the status rows
on the same console already use: the token paints a small indicator and the
wording stays in the foreground colour. The word states the condition, so
nothing hangs on the colour alone.
2026-09-10 16:00:38 +02:00
Marc-André Bombeck 2686da2803 Add the setup flow's browser journeys, axe sweep and string-headroom check
Four journeys, one account each, from the welcome screen to the
dashboard: blood pressure and weight typed in, a daily medication added
inline, a visit within a month with labs, and a child's managed profile
created on the confirm screen. Each asserts what the walk wrote — the
module map, the tile order, the checklist, the settled ledger — and the
first proves that leaving after Q3 resumes at Q4.

Two sweeps on accounts of their own drive the state through the answers
route and visit every screen by URL: axe at both widths plus one
keyboard-only answer, and every locale with every text node lengthened
by 30% before the page, the shell, every clipping box and every control
are measured. All six run in one project because each mutates the
account it walks.

The medication wizard learns to stay where it was mounted after a
create, which the first-result screen needs and the medications list
does not.
2026-09-10 15:57:41 +02:00
Marc-André Bombeck 02ca15ad6e Translate the setup flow into the other six locales
Every key the flow, the checklist rows, the Settings card and the
module-off action added to the English bundle now exists in German,
Spanish, French, Italian, Polish and Korean, with the same placeholders.
The forty-seven keys the five-step wizard left behind — its carousel,
goal picker, source grid and step counter — leave all seven bundles,
and the English-leak guard drops the one entry that named them.
2026-09-10 15:47:22 +02:00
Marc-André Bombeck fd46dcc3a1 chore: drop two exports nothing reads
The delivery-state reader in the error-reporting module had no caller: the
card reads the three columns itself. The skippable-step id type was exported
for a consumer that never appeared. The dead-code gate names both.
2026-09-10 15:43:37 +02:00
Marc-André Bombeck ec82ad3a93 Carry the setup answers into the checklist, Settings and the module pages
The getting-started checklist reads the answers: a visit named within a
month adds a "prepare the visit" row that is done once one is on the
calendar, and the data-source row names the wearable that was chosen.
Its per-browser state moves to one module so the done screen, the skip
and Settings write the same keys.

Settings → Account gains the two ways back in: "Set up again" through
the restart route, which resets the ledger, keeps the answers as
prefill and touches no module; and "Show the checklist again", which
forgets what this browser hid.

A page whose module is off now answers with the shared notice and the
one action that helps, in one place for every module page: the shell
maps the route to the module through the navigation model's own gate,
so a page and its nav entry cannot disagree about which switch they
follow. And the tour's two dead stops get their anchors on the
integrations and health-record group headings.
2026-09-10 15:41:06 +02:00
Marc-André Bombeck 29a02d6741 chore(release): v1.38.16 — the API says what it refused, and the admin page says whether last night's copy landed
Bump the version, the service-worker fallback and the OpenAPI document,
and add the CHANGELOG entry for v1.38.16.
2026-09-10 15:39:50 +02:00
Marc-André Bombeck 2676a5c02a docs(api): say in the contract that cycle insights are fenced per section
The route's description told a native client only that phase never leaves
the cycle routes. It now says what a grant scoped to the cycle alone
receives: the phase rows with no measurement or mood outcome columns and no
lagged discovery, the same as a record with nothing logged. The owner and a
whole-record grant are unchanged.

The catalogue's header read as a current count; it is history and now says
so.
2026-09-10 15:36:54 +02:00
Marc-André Bombeck 53c2e342b0 test(record-settings): hold the module write to the shared helper
The guardian's modules branch no longer invalidates the health score in the
route; the record-keyed write it shares with the setup flow does. The guard
pinned the old call site and went red for a behaviour that had not changed.
It now asserts the route goes through the shared write with the record id
and that the helper is still the place that invalidates.
2026-09-10 15:35:52 +02:00
Marc-André Bombeck a062610895 Retire the five-step wizard's route, goals and columns
The needs-based flow is the one setup flow now. POST /api/onboarding/step
and the six goal slugs go, and with them the two account columns the
wizard kept — its checkpoint and its goal list — through a migration
that drops them; onboarding_completed_at stays as the first-run
redirect's gate. The one durable effect the goals had, the dashboard
tile order, moves to the completion route: the answers now carry both
halves of Q2, which modules are on and what sits on top, and the seed
keeps the wizard's one contract of writing only while the layout column
is still unset.

The OpenAPI table loses the step path and the completion's description
says what the route does today; the demo-allowlist test names a
mutation that still exists.
2026-09-10 15:32:35 +02:00
Marc-André Bombeck b446911d7d Add the setup flow's done screen
The dashboard is one click away, already ordered, and the checklist
opens on arrival. The tour is an offer here rather than an automatic
launch: pressing it sets the referrer the shell's launcher reads, and
nothing else does. Two record-shaped exits follow the answer to Q1: an
account that said "both" is offered the profile for the person it looks
after, and one that set up a record for somebody else is offered that
record through the same switch the account menu uses, so the first
entry lands where it belongs. The step is marked done on arrival, once.
2026-09-10 15:28:16 +02:00
Marc-André Bombeck 5a805e8d17 Add the setup flow's first-result screen
Exactly one task, by the step machine's fixed priority: connect the
wearable named in Q4, add the first medication, or log one reading for
the first area. The measurement form and the medication wizard render
inline; a connection goes through the integrations page, because the
OAuth handshake cannot run inside this screen, and the screen watches
the status envelope until it comes back connected. On completion the
screen shows what the task produced — the reading on its tile, the
medication with its next dose, the connection with its first sync — and
records the result on the ledger with the server's own instant.

The offer is not recorded on arrival: somebody who leaves mid-task
resumes here rather than on the done screen.
2026-09-10 15:24:32 +02:00
Marc-André Bombeck 58bc91a0a3 Add the setup flow's confirm screen
What the answers switch on is read off the registry's derivation and
never computed here, so the list the person confirms is the list the
completion route writes. Units, language and time zone are shown once
beside it, changeable in Settings, never asked again.

The profile half keeps the baseline form and its per-field refusals:
the fields are seeded from the account so a value it holds is confirmed
rather than typed again, and a refused field still stops the flow. For
"someone I look after" the managed-profile form takes the profile's
place, because that record is created here, after the questions; an
account without a second factor can finish without it and create it
later under Settings.

Confirming posts the completion, passes the first-result step outright
when there is no task to offer, and goes where the step machine says.
2026-09-10 15:19:48 +02:00
Marc-André Bombeck 7b279aec72 Add the six question screens of the setup flow
One question per screen, Q1 to Q6, each a chip set with a real radio or
checkbox inside every chip so the browser owns grouping and keyboard
movement, and a focus ring the five-step picker's hidden inputs never
had. The selection is pre-filled from the stored answers, "Next"
persists it through the answers route and navigates from the state the
server hands back, and Q1 is the one question without a skip.

The questions are data (which step, which answers, one or many, may it
be passed) with two pure translations beside them — stored answers into
a selection, a selection into the strict body — so the wire never sees
a chip this file did not offer. Q6 asks only about the units the ticked
areas need and sends nothing for a value the account already had.

The step page guards every URL with the step machine and stays under
/onboarding/, which is what the first-run redirect lets through.
2026-09-10 15:15:24 +02:00
Marc-André Bombeck 1c2e7c29de Add the setup flow's welcome screen and shell
The front door reads the same ledger every screen reads: a record that
never entered the flow sees the welcome, one mid-way is sent to the step
it owes, a finished one is offered the questions again. The shell prints
the counter and an ordered step list off the step machine, so it shows
exactly the screens this flow has, and every screen moves focus to its
heading on arrival.

"Skip for now" is a real exit — it stamps the account past the first-run
redirect and opens the checklist on the dashboard — and the one-time
medical disclaimer now gates it as well as "Set up", because a skip that
reached the dashboard without it would be a way round the acknowledgment.

The five-step wizard's welcome carousel, goal picker and source grid go
with it; the numbered step route follows in the next commit.
2026-09-10 15:10:50 +02:00
Marc-André Bombeck 13f11ed06c Add the pure step machine for the setup screens
Which screen is next, where a returning person resumes, whether a URL
may be visited, and what the counter says are all one function of the
published ledger and answers, so the page guard, the screens and the
shell cannot disagree. Q6 is in the order only while an area needs a
unit and the account does not already answer it; the first-result task
follows the spec's fixed priority (a connection the browser can finish,
then the first medication for a daily schedule, then one reading for
the first area) and is left out for a record somebody else will run,
because the three tasks write the caller's own record.

Tested before the screens exist; the two rules a screen would most
easily get wrong were broken on purpose and the tests went red.
2026-09-10 15:02:17 +02:00
Marc-André Bombeck ceb0a84de6 Add the query-key module for the setup flow
The needs-based onboarding has no read of its own — its state rides
GET /api/auth/me — but every screen that persists an answer, the confirm
screen, the disclaimer acknowledgment and the Settings restart card are
mutations, and the queryKey-factory rule allows no bare key at a call
site. One module names them, and one read-back key for the reading the
first-result step logs, under the measurements prefix so a later write
evicts it.
2026-09-10 14:59:43 +02:00
Marc-André Bombeck 66ae214100 chore(api): list the booster's out-of-scope refusal in the catalogue 2026-09-10 12:30:44 +02:00
Marc-André Bombeck 67bb45a2b3 chore(api): keep one onboarding entry in the error-code catalogue
Two branches each added an onboarding surface to the catalogue; the object literal carried the key twice and the second entry hid the first from the guard.
2026-09-10 12:30:10 +02:00
Marc-André Bombeck 12d6aa3078 Merge the scoped-grant fences, the delegate controls that ask their own section and the published switch refusals 2026-09-10 12:29:09 +02:00
Marc-André Bombeck 26f95aa12e chore(api): list the onboarding routes' error codes in the catalogue 2026-09-10 12:28:53 +02:00
Marc-André Bombeck 83b7cd223a docs(sharing): the booster needs two sections, and the guide promised it at one level
The write-level row listed "a vaccination dose and the booster reminder it
suggests" three paragraphs under a section table that puts the vaccination
record in Health background. Read together, that tells a self-hoster a
health-background WRITE grant can plan a booster — which the route beside it
now refuses, because the reminder it mints lives under Readings. The row lists
the dose alone, and the exceptions paragraph, which is where a reader looks for
exactly this, carries the two-section case and says the dose logs either way.

With it, the small things the same pass turned up:

The cycle-insights fixture asserted a property it could not show. Its docblock
claims the cycle-native answer survives the fence, and it seeded no symptom at
all, so `symptomPatterns` was empty in every leg and a regression that emptied
it along with the foreign columns would have passed green. One catalogue
symptom on the luteal days, asserted on the owner leg and on the cycle-only
one.

The immunization rows matched on a bare `role="button"`, which passes vacuously
the day the card becomes a real button and fails for the wrong reason if
anything else in the subtree grows one. They carry the same stable marker the
visit card took.

`/api/cycle/calendar` reads the same wrist-temperature channel the crosstab
does and is deliberately not fenced, and it was the only one of the pair with
nothing saying why: no value from it reaches the response.

The encrypted export's new 403 documented the switch refusal and not the
narrow-scope one it answers first, unlike the two settings operations beside
it. Both sheets say at the top that their Save and Delete are gated at the
caller, so a third mount reads the constraint before it violates it. And one
docblock line ran past the wrap.
2026-09-10 12:23:59 +02:00
Marc-André Bombeck 3017e24bb1 Merge the needs-based onboarding's server state and the derivation that never hides data 2026-09-10 12:23:34 +02:00
Marc-André Bombeck f5df6111a1 test(onboarding): put the setup flow's cases through the finished questionnaire
Two cases in the integration file answered one or two questions and posted
the confirm, which the gate now refuses; they answer or pass all six. The
audit assertion reads the details column as the JSON string it is.
2026-09-10 12:20:50 +02:00
Marc-André Bombeck 44b6ea01c6 fix(onboarding): tidy the small edges around the setup routes
Four of them. The confirm re-stamped its completion instant on every call, so
a replay quietly moved the moment the setup finished at while the derivation
beside it was carefully latched. The two list answers were stored exactly as
sent, duplicates included, so the column could hold something the reader would
never return — the reader de-duplicates on the way out and now so does the
write. The wide-event name for saving an answer used a different noun from its
two siblings, which makes a dashboard filter awkward for one feature. And the
contract said the restart body was required while the route accepts none.
2026-09-10 12:14:32 +02:00
Marc-André Bombeck 681e69a723 fix(modules): drop the last three fail-open gates and discover the class instead of naming it
Six surfaces were named and fixed; nine carried the expression. `/labs`,
`/medications` and `/mood` still read `inSharedRecord || user?.modules?.X`, and
every precondition holds for them too: all three are presentable to their own
scoped grants, all three module keys map to a real section so the masked map
answers correctly for a delegate, and none of the three routes behind them
carries a module gate of its own — so a typed URL rendered a working page for a
record whose owner had switched the module off.

The guard is a discovered sweep now rather than a six-entry list. It walks
every component under `src/app` and `src/components` through the shared walker,
keeps the ones that read the module map, and asserts the SHAPE: no boolean `||`
joins the delegate flag to a module read. The search window cannot cross a `;`,
a `{` or a `}`, so it sees one expression at a time and a delegate check
elsewhere in the same file is none of its business. A tenth surface fails on
arrival.

Writing it turned up why the first version could not have found the three: the
comment stripper every structural guard in this directory re-spells removes
block comments first, and cannot tell a real opener from a `/*` inside a line
comment. `mood/page-client.tsx` explains its gate with "Every
`/api/mood-entries/*` route also enforces the gate", and that `/*` opened a
fake block that swallowed the next 2.2 kB of real code — the gate three lines
below it included. A guard reading that file was searching a source with a hole
in it and reporting a clean sweep. The shared walker now carries a stripper that
walks each line left to right and lets whichever opener comes first win; the
published-coverage sweep beside it moved onto the same one.
2026-09-10 12:14:14 +02:00
Marc-André Bombeck b17f18295e fix(onboarding): let the getting-started list go when its rows are done
Three things, all in the same pair. The reader that orders the list from the
answers shipped without the proof that it reads correctly: every existing case
took the early return, so `checklistOrderFromNeeds` and the two new arms were
never executed by a test. They are covered now — medication first for somebody
who takes one daily, the named connection ahead of the untouched rows, profile
always first, and no answer combination that drops or duplicates a row.

A first-result task that was offered and then passed left the setup reading as
permanently unfinished, because the check asked only whether the offered task
had produced anything. A deliberate pass is an answer. And the published state
is additive — every record carries the field — so nine pending steps and empty
answers must read as "never entered the flow" rather than as an unfinished
one, or every account that predates the flow would look half set up.

The list itself now follows the design: for a record that ran the flow it goes
when its rows are done or the person hides it, and the five-reading rule stays
only for records that never entered.
2026-09-10 12:11:17 +02:00
Marc-André Bombeck f90307fd22 fix(auth): answer the setup state for the record the payload describes
The account payload resolved the setup state for the actor while its module
map, its cycle flag and every count the checklist reads beside it answer for
the active record. A guardian looking at a child's dashboard therefore got the
child's rows ordered by their own answers, and the child's reading count
tested against their own flow state. The two halves of that component have to
agree about whose record they describe, so the field is record-scoped now,
like the module map next to it.

Under a grant narrowed to one section the answers come back empty, for the
reason the module map is masked: they name the domains the record tracks, and
a grant that opens readings does not open that. The shape of the flow still
comes through.

The three write routes stay actor-only and say why: a delegable declaration is
a reviewed entry in the sharing surface guard, and a read that is wider than
its write is the honest shape while that entry is still to come.
2026-09-10 12:06:02 +02:00
Marc-André Bombeck b10a3ef22e fix(onboarding): leave a trail for the three settings columns the flow writes
The setup flow writes a record's module map, its glucose unit and its unit
preference. All three have a dedicated settings route that records an audit
row, and the flow recorded none, so "why did my modules change" had no answer
in the activity panel. Restarting the flow did write a row, which made the gap
look like an oversight rather than a decision, because it was one.

Same event names as the dedicated routes, since it is the same column and the
panel should group them. The module row names the keys that actually moved and
the domains kept for their content.
2026-09-10 11:57:11 +02:00
Marc-André Bombeck 07f1b6ce92 refactor(modules): one record-keyed write for a record's module state
The guardian's modules route and the setup flow's confirm both decide a
record's modules, and each had its own copy of what that means: write the
preference blob, write the delegated cycle column, invalidate the health
score. Two copies of a three-step write drift, and the second one was added by
this branch. They share one function now, keyed on the record, which is the
carrier the managed-profile work needs.

Authentication stays at the routes and stays different on purpose — the
guardian route acts on a managed record, the setup routes refuse outright
under a switch until a guardian's route into a record's setup lands with the
rest of that record's configuration. So does the merge: what the answers imply
and what somebody just ticked are different questions about what may be
overwritten. The actor's own modules route keeps its own write, because that
one is guarded on a concurrency token the record-keyed callers do not carry.
2026-09-10 11:54:19 +02:00
Marc-André Bombeck efd4efa862 docs(sharing): stop the cross-section predicate's docblock from listing its callers
It named three of them and the booster mint made four the same day. A comment
that enumerates its own callers goes stale on the next one, so it states the
shape instead and keeps the note about the two verbatim copies it replaced.
2026-09-10 11:52:54 +02:00
Marc-André Bombeck 2d2350252f fix(onboarding): never switch a module off on a record that already uses it
The derivation wrote an explicit off for every module the answers did not
name, which is right for a record being set up and wrong for one with years of
rows behind it. An established self-hoster has, for most modules, no stored
preference at all — they were default-on and nobody ever touched the toggle —
so the first confirm took away the navigation entry, the dashboard widget and
the settings entry for domains full of content. The rows survived; the
surfaces did not.

A derived off now asks first, and only for the modules it would actually
retract. Ownership is not re-answered: the measurement domains come from the
same map the MCP reads and the coach snapshot gates off, and each remaining
module names the one table its content lives in, exhaustively, so a module
added later fails to compile until somebody says where its content is. A
module whose domain holds rows keeps whatever the record already had, because
absence is what "on" looks like in the stored map.
2026-09-10 11:48:27 +02:00
Marc-André Bombeck cc6e6ca221 fix(onboarding): derive the module map only from a questionnaire that was finished
The only gate on the derivation was Q1 being set, so one answer was enough to
turn the whole questionnaire into a module map. Two ways that landed wrong and
they compound. Somebody answers who the record is for, closes the tab, and
later finishes the legacy four-step wizard, which posts to this same endpoint
and knows nothing about these questions: the five unanswered ones each read as
their conservative default, eleven surfaces are written off, and the
once-only marker makes it unrepeatable. Or any client patches one answer and
posts the confirm straight back.

The gate now asks whether every question has an answer or a deliberate pass.
A half-answered flow derives nothing, is not stamped complete, and keeps its
confirm step pending, so finishing the questions later still does the work.
The legacy arm is untouched: a caller with no setup row still answers the
fixed acknowledgement it always did.
2026-09-10 11:42:38 +02:00
Marc-André Bombeck 7a1f3fe32d fix(onboarding): stop the setup flow asking for units the account already holds
The spec's sixth question is skipped when the account already carries the
preferences, and the flow had no way to know: `User.unitPreference` is
nullable with null meaning "default metric", and the account payload coerces
that away, so nothing downstream could tell a chosen metric from an unset
column. The two columns are read raw on the server now, into the same
vocabulary the wire publishes, and a record whose account holds both reads its
`units` step as done — the question answers itself and is never put again.

Read-side only: the stored ledger keeps saying pending, because the person
really has not answered it, and an answer given later still lands.

The two writes the units answer makes — the display columns and the record of
the answer — go in one transaction, so a failure between them can no longer
leave the columns changed with no record of what changed them.
2026-09-10 11:39:32 +02:00
Marc-André Bombeck 70e40e097d docs(sharing): correct the four statements the self-hosting guide gets wrong
Measured against the route declarations on this tree:

The health-background section names allergies, family history and the profile
facts, and omits visits, the practices behind them and the vaccination record —
all three of which `scope.ts` puts in that section, so a grant is narrower on
the page than it is in the product.

"Aggregate surfaces appear only on a whole-record grant" is true and
incomplete: a whole-record grant does not open them equally either. The daily
digest and the dashboard's snapshot answer at read, the health score, the
dashboard's summary and the insights need manage.

The write level lists seven creates against twelve WRITE declarations. A visit,
a practice, a vaccination dose and the booster reminder it suggests were
missing, and the guide said nothing about the creates that need manage inside a
section a write grant can otherwise add to, or about the vault taking no
delegated write at any level.

"Exports, the health-record archive" sat under what a delegate cannot reach,
while `POST /api/export/health-record` answers at manage on a whole-record
grant and its own comment says why. The row is about the full exports and the
encrypted archive; the doctor report is named as the exception it is.

The sharing-denial guard's docblock carried the same class of stale claim — 116
fenced modules, 26 never published — and that gap is closed on this tree. The
caveat becomes an assertion: a new leg recomputes the fenced modules from the
route sources and requires every one to be published, and it names no number,
because a hard-coded figure is what turned the paragraph into a false statement
about the contract. It fails when a published path is withheld from it.
2026-09-10 11:25:09 +02:00
Marc-André Bombeck 0e4619a0c0 docs(nav): say why Insights stays closed under a switch, since the old reason lapsed
The entry carried "Non-delegable in v1, server-side and here". That was true at
v1.36.0 and is not true now: twenty-seven `/api/insights/*` reads plus
`/api/dashboard/summary` and `/api/export/health-record` declare
`("manage", "record")`, and the AI-egress objection they were closed for is
answered by construction rather than by the flag — the record resolver stamps
`setDelegatedGenerationSuppressed`, so a delegate reads what the owner's own
account generated and causes no egress.

What keeps the door shut is the overview's own reads rather than the tiles':
`/api/insights/layout` and `/api/insights/generate` both resolve `requireAuth()`
and refuse any switch at any level. Opening the entry without first deciding
what those two mean for a delegate — whose saved layout, and whether the
briefing reads or regenerates — would hand a whole-record MANAGE delegate a page
whose chrome 403s while its tiles answer, which is the failure the presentation
inventory exists to prevent. That is a decision about two more routes, not a
flag on this one, so the comment now says what is actually load-bearing and the
Coach's own reason is stated separately.
2026-09-10 11:22:06 +02:00
Marc-André Bombeck 3f015effec test: prove the setup flow against a real database and a real grant
Four claims the unit suite cannot reach, because each is about what is in the
database afterwards: the answers persist and a replay writes nothing new, the
module derivation happens once and leaves a later Settings change alone, a
restart resets the steps and not the modules, and a delegate with a live
accepted grant and a switched session is refused on all three writes — with
neither record acquiring a row, which is the quiet failure a fall-back to the
caller's own record would produce.

The demo guard gains the three paths and, beside them, the case that matters
more: admitting one verb on a path must not open a sibling.
2026-09-10 11:17:00 +02:00
Marc-André Bombeck 4410a496cc docs(sharing): say that the writable-section list is existential, not per verb
`writableDomains` answers "is there at least one delegated write route in this
section this grant satisfies". Its docblock promised a per-section answer the
table cannot give: within a section the split runs by verb, and three of the
four sections marked writable carry MANAGE-only creates beside their WRITE ones
— an allergy and a family-history entry under `profile`, a water entry and a
checkup reminder under `measurements`, a snooze and a re-recorded dose under
`medications`.

No shipped control is wrong because of it: the allergy and family-history forms
already ask the manage question, and so does the water entry. But the name and
the sentence beside it invite a control to read "my section is writable,
therefore my create is", and that reading is wrong in three sections out of
four.

Documentation only, in the three places the claim is made — the published
field, the function that derives it, and the guard that holds it against the
routes, whose green run now says what it does not prove. A per-verb table would
be a second place the route declarations live, and the declarations are what
decides; the control keeps asking the hook for its own verb class.
2026-09-10 11:16:55 +02:00
Marc-André Bombeck c809971a23 docs(sharing): name the screener's score row where the section is consented
`POST /api/mental-health/assessments` is fenced on `mind` and writes one row
into `measurements`: the instrument's total, minted `COMPUTED` and keyed on the
administration it came from, so the trend reads through the chart and rollup
tier without the encrypted item answers going anywhere. A grant scoped to mood
and mind therefore adds a point to the owner's measurement series, and nothing
said so.

Left in place rather than fenced. Withholding the projection the way the
booster mint is now fenced would file a screener whose own total is missing
from the record — an inconsistency inside the section the grant does open, to
avoid a derived point in one it does not. So it is documented instead, in the
three places it is decided or agreed to: the declaration, the section's own
definition, and the consent copy in all seven locales, which is where a
widening belongs. The published operation says it too.
2026-09-10 11:15:50 +02:00
Marc-André Bombeck 1b74bf8b54 fix(vaccinations): keep the booster mint inside the sections the grant opens
`POST /api/vaccinations/{id}/booster` is declared `("write", "profile")`, and
that is right for the act — filing the Impfpass and arming the booster it
suggests are one thing to the person doing them. The row it writes is not: a
`MeasurementReminder` belongs to the measurements section, every direct route
over the model declares it there, and creating one needs MANAGE. So a WRITE
grant scoped to the health background alone produced a reminder on the owner's
checkup list that the delegate could neither read nor change through the
section that owns it.

The seam is fenced the way the visits service fences a checkup closure, with
one difference stated at the call site: this refuses rather than skips. There
the closure is one effect of a larger save and reporting it as not done keeps
the save honest; here the reminder is the whole request, and a 201 over a row
that was never written would tell the person their booster is planned while
nothing rings. The prompt that raises the call asks the same question client-
side, so a delegate outside the section is not offered it in the first place;
the dose itself still logs either way.

`vaccination-booster-scoped-delegate.test.ts` drives the owner, a delegate
holding both sections, a profile-only delegate and a whole-record one. The
scoped-refusal leg fails against the previous handler, which answered 201 and
left the row.
2026-09-10 11:11:38 +02:00
Marc-André Bombeck 0ee26625be fix(modules): let the record's own module map close its pages for a delegate too
Six page gates read `inSharedRecord || user?.modules?.X`, with a comment saying
the delegate's own module map does not govern the owner's record. That was true
when it was written and stopped being true in v1.38.14: `GET /api/auth/me` now
publishes the RECORD's map, masked to what the grant opens, so the prefix that
protected against reading the wrong map now widens the gate instead. The
navigation drops the entry correctly while a typed URL still renders the page
for a record whose owner switched the module off, and `/api/vaccinations`
carries no module gate of its own, so it renders and works.

Deleting the prefix answers both cases from the one map, which is what it is
for. A structural guard holds the six expressions: it locates each gate, proves
it is a module gate, and then asserts it does not widen on the sharing
question. It finds nothing to assert on if the expression moves, and says so,
rather than passing on an empty match. All six legs fail against the previous
gates.
2026-09-10 11:04:49 +02:00
Marc-André Bombeck 3f44b882ac feat(backup): carry the setup answers out of the account and back in
Nothing recomputes an answer. The module map they produced survives on the
account row, but the map says what is switched on, not that the person told the
flow they take medication daily and have a visit next month — so a restore
without the row opens a blank questionnaire for somebody who already answered
it, and leaves the checklist ordering itself from nothing.

Both ends live in one file, the arrangement the visits and the score already
use, because a reader who greps only the restore route gets a false negative
when the route delegates.

`modulesDerivedAt` is the field that makes this more than history and it is
asserted rather than defaulted: it is the once-only latch on the module
derivation, so a restore that let it default to null would hand the next confirm
permission to re-apply the questionnaire over every module decision taken since,
silently. The round trip seeds it non-null and reads it back.

The file's schema validates the three answer objects loosely and the restore
narrows them through the same fail-soft readers the account payload uses. Being
stricter there would refuse a whole account's restore over one retired chip.

The wipe takes the row for the reason the reset already takes the wizard's own
columns: the record the answers were about is gone, so the answers describe
nothing.
2026-09-10 11:03:56 +02:00
Marc-André Bombeck dbfad0f28e feat(api): publish the setup state on the account payload, and read it
Additive: `onboarding` carries the nine steps with their status, the answers as
given, the flow's own completion stamp and the one task it offered. Always
present — a record that never entered the flow reads as empty answers with nine
pending steps, so a client branches on the statuses rather than on whether the
field exists, and an unknown step id is skipped rather than refused.

It is resolved for the CALLER's own record rather than for the active one,
unlike the two module fields beside it. The three write routes are actor-only,
and publishing a setup state the browser cannot write would be a read it could
act on and never complete.

Both ends land here, because a field with no reader is the failure this
repository keeps rediscovering. The getting-started checklist orders its rows
from the answers — medication first for somebody who takes one daily, the
data-source row first for somebody who named a wearable — and it stays on screen
while the flow is unfinished. That is the second half: five readings were never
evidence that the setup finished, and now a pending step, an unconfirmed set of
answers or an offered task that produced nothing keeps the list where it is.

The ordering only applies once the answers are confirmed. Re-ordering the
dashboard under somebody who is still mid-question would be movement they did
not ask for.
2026-09-10 11:03:47 +02:00
Marc-André Bombeck 021ea8f1ff feat(api): let a record answer the setup questions, and act on them
Three writes, all on the caller's own record.

`PATCH /api/onboarding/answers` saves one step the moment it is answered, so
leaving the flow and coming back resumes where it stopped. It is idempotent
because the whole computation is a pure function of the row and the body,
including the first-result instant, which is kept rather than re-taken. There is
no ordering contract at all: a back button has to work.

`POST /api/onboarding/complete` keeps everything it did and gains the confirm
screen's job. For a record that answered the questions it derives the module map
once and applies it, and the once-only latch is the point: a second confirm
would re-apply a questionnaire over decisions taken in Settings since. Cycle is
switched on through its own column and never off, because the gate already
derives an unanswered cycle from recorded sex and an untick is not a request to
retract that.

`POST /api/onboarding/restart` puts the steps back and clears the latch. It
writes no module state whatever: a re-run never turns off something switched on
by hand, and the safest way to hold that is for this route to have no opinion
about modules at all. It also leaves the first-run redirect's own stamp alone,
so asking the questions again does not push anybody back through the old wizard.

All three refuse outright while the session is acting on somebody else's record,
at every grant level, so a delegate can never write another record's setup. The
route into a managed profile's flow belongs with the rest of that record's
configuration and is not smuggled in here.

The demo allowlist gains the three: the flow has to be completable there with
preset answers, and none of them creates health data.
2026-09-10 11:03:36 +02:00
Marc-André Bombeck cc98c56172 feat(onboarding): store what a record needs, and map it to modules
The setup questionnaire the design spec asks for needs somewhere to put its
answers. `OnboardingRecord` is that place: one row per RECORD rather than per
person, so a guardian running a managed profile's setup writes the child's row
and not their own, and the three JSON columns hold the answers, the nine
ordered steps with their status, and the one task the flow ends on.

Nothing here is encrypted, and the schema comment says why: the columns hold
closed enum vocabularies, not free text, which is the same class of value as
the module map and the goal slugs sitting in plaintext beside them.

The needs to modules map lives next to the module keys rather than in the flow,
because a module renamed or retired has to break the map at compile time rather
than leave a chip that quietly changes nothing. The derivation is total — every
directly-owned key gets an explicit value — and the merge beside it is
one-directional: what the answers name is switched on, what they do not name is
switched off only where the record does not already carry a deliberate on. The
two delegated keys are absent by construction: `cycle` is reported separately
because its real column is on the cycle profile, and the Coach is not offered by
this flow at all.

Readers are fail-soft. They sit on the payload that rides every app boot, and a
value written by a release that named an area this one retired must not take the
shell down with it.

Nothing is retired: the four-step wizard, its goal slugs and the one-time tile
seed keep working and keep their meaning until the new surface replaces them.
The two states are disjoint — the slugs decide tile order, these answers decide
which modules are on, and neither reads the other.
2026-09-10 11:03:24 +02:00
Marc-André Bombeck e7a1950f3a refactor(sharing): retire the coarse "may this person add" answer
`canWrite` is the grant's LEVEL and carries no scope term. Its docblock said
"May this caller ADD to that record", and the client hook republished it as
`canAdd`, so fourteen controls across measurements, medications, labs, illness
and the dashboard gated a create on a boolean that answers `true` for a WRITE
grant scoped to the document vault — a grant whose writable-section list is
empty, because the vault takes no delegated write at any level.

Nothing shipped was visibly wrong before the capture picker, because the nav
drops a section a grant does not open. That is a property of one surface, not
of the answer, and the answer is the thing many controls read.

So the coarse answer is gone from the hook, and every consumer asks
`canWriteDomain` for its own section instead: `measurements` on the two
measurement surfaces and the dashboard's empty state, `medications` on the
medication list, table, ledger, card menu and side effects, `labs` on the lab
list and biomarker detail, `illness` on the episode list. Each of those is the
section its own route declares. `canWrite` keeps its name and its wire shape —
native clients read it — and its docblock now says what it is: whether the
grant is a reading one, with the per-section lists beside it for the question a
control actually has.

The hook table gained the vault-scoped WRITE grant as its own leg: level true,
every section false. The take-all-due fixture described a grant the server
never mints — `canWrite: true` over an empty writable list — and now derives
its list from the same table the server derives it from.
2026-09-10 11:02:32 +02:00
Marc-André Bombeck b6d3f9903f docs(api): publish the switch refusal on the wipe, the deletion and the encrypted export
The three routes that act on the whole of an account — `DELETE
/api/settings/data`, `DELETE /api/settings/account`, `POST
/api/export/encrypted` — name no record. They resolve the caller and act on
whatever the caller owns, so the question a switched session puts to them is
what happens when the browser believes it is somewhere else.

They already refuse: all three resolve through `requireFreshMfaIfEnrolled` or
its erasure sibling, and both open with `requireAuth()`, which reads the acting
carrier and throws `sharing.not_permitted` for anything but `none`. What was
missing is that the contract never said so. `/api/settings/{data,account}`
published a 403 about narrow Bearer scope alone, and the encrypted export
published no 403 at all, so a client that switches records had no way to learn
which of its calls stop working short of trying one.

One sentence, spliced onto the three, byte-identical for the same reason the
delegable refusal is one string. `switched-session-destructive-refusal.test.ts`
drives each route with a live whole-record MANAGE switch and asserts both
halves: the status, the code and the wording, and that neither record moved —
a refusal raised after the transaction would satisfy the first alone. The
export leg additionally asserts no archive rode along with the 403.
2026-09-10 10:49:12 +02:00
Marc-André Bombeck 927496236a fix(capture): ask each capture surface's own section before offering it
The capture FAB rides the bottom bar on every authenticated page, and its
fallback arm was section-blind:

    return caps.canAdd && DELEGABLE_CAPTURE_KINDS.has(kind);

`canAdd` is bound straight to the grant's LEVEL — `grantAllows(grant, "write")`,
no scope term at all. So a WRITE grant scoped to `["labs"]` published
`canAdd: true` with `writableDomains: ["labs"]`, and a delegate standing on
`/labs` was offered a weight form and a dose that the server refuses at
`grantCoversDomain`. The worst case is a WRITE grant scoped to `["documents"]`:
the vault takes no delegated write at any level, the writable list is empty, and
both kinds were still offered.

`writableDomains` is already the level × scope × route-table intersection, so
one question per kind, asked of that kind's own section, answers the scoped
case, the vault case and the mood entry's MANAGE-only create together. The
closed kind list and the separate manage arm are both dead once that lands and
are gone. The dashboard quick-entry sheets and the header menu carried the same
shape — unreachable today, because the dashboard opens only for a whole-record
grant — and move with it rather than waiting to become reachable.

The picker's legs in the affordances suite now build their capabilities from
the same table the server publishes, and four scoped cases join them: labs-only
offers nothing, measurements-only offers the reading, documents-only offers
nothing at all, and a mind-scoped manage offers the mood entry alone.
2026-09-10 10:45:01 +02:00
Marc-André Bombeck 3e176db5b7 fix(encounters): stop offering the visit edit sheet to a delegate who may not save it
`VisitsSection` asked the grant about its add button and nothing else. Every row
underneath stayed tappable into the edit sheet, whose Save is `PATCH
/api/encounters/{id}` and whose Delete is `DELETE` on the same path — both
`("manage", "profile")`. So a READ delegate opened a form that could not be
saved, and a WRITE delegate, who may file a new visit, opened one that could not
be changed. Reachable wherever the checkups page is, which is every
`profile`-scoped grant.

The row now takes its open callback only when `canManageDomain("profile")`
answers, and the card renders its content as content rather than as a button
when it does not. The add button keeps asking the write question, because that
is a different question with a different answer.

Four legs in the affordances suite over the same scoped fixtures the
immunization log uses: the owner opens the sheet, a READ and a WRITE delegate
see the row and cannot open it, a WRITE delegate still gets the add button, and
a MANAGE delegate opens it only while holding the section. Two of them fail
against the previous section.
2026-09-10 10:39:46 +02:00
Marc-André Bombeck e8a2cbe82e Merge the per-account off-host backup freshness and the honest error-report badge 2026-09-10 10:37:00 +02:00
Marc-André Bombeck 7c7e621fd9 fix(vaccinations): ask the grant before offering to add, edit or delete a dose
The immunization log carried no capability check at all: not one reference to
the record hook anywhere under `src/components/vaccinations`. The page is
presentable to every `profile`-scoped grant and to every whole-record one, so a
READ delegate was shown the add button, a clickable row that opens the edit
sheet, and the delete inside it — three controls the server refuses with a 403
each. A WRITE delegate was shown two of them.

`POST /api/vaccinations` answers at WRITE; the edit, the delete and the restore
behind it are `("manage", "profile")`. The two add buttons now ask
`canWriteDomain("profile")` and the row's edit affordance asks
`canManageDomain("profile")`, which is the split the address book next door
already gets right. The list already renders a non-interactive card when it is
handed no edit callback, and the sheet is only reachable through one of the two
gated entries, so nothing needs a second check that could drift from the first.

`delegated-write-affordances.test.tsx` gained a scoped-grant fixture — every
fixture in it was `sections: null`, which is why nothing noticed — and six legs
over the log: the owner, a READ, a WRITE and a MANAGE delegate holding
`profile`, a MANAGE delegate holding another section, and the empty state's own
add. Four of them fail against the previous view.
2026-09-10 10:36:52 +02:00
Marc-André Bombeck e645921852 fix(cycle): fence the phase crosstab's outcome columns to the sections they belong to
`GET /api/cycle/insights` is declared `("read", "cycle")`, which is right for
the phase labels and wrong for what it compares them against. The crosstab rows
carry `lutealAvg`, `follicularAvg` and `delta` in display units for resting
heart rate, HRV, sleep duration, steps, weight, body/wrist/skin temperature and
blood glucose, plus the mood score read straight off `MoodEntry` — measurement
and mind data, published in full to a grant scoped to the cycle alone, with the
lagged discovery's narrated interpretation on top.

The visits service already had the right shape for this: a predicate over the
grant's sections, asked before the foreign rows are read. Both sections are now
fenced at the query rather than in the response, so a caller outside them never
loads the values in the first place and the rows read exactly as they do for a
record with nothing logged. The wrist-temperature read that sharpens the
prediction stays: it never reaches the response.

The predicate had two verbatim copies, one in the visits service and one in the
vaccination service, with a comment on the second saying a second spelling would
be a second thing to keep in step. It is one module now, `sharing/acting-domains`,
and the third consumer imports it rather than a feature service.

`cycle-insights-scoped-delegate.test.ts` drives four grants against a fixture
whose separation is large enough that the FDR gate cannot be the reason a row is
missing: the owner and an entire-record delegate get both figures, a cycle-only
delegate gets neither and no lagged row, and a cycle+mind delegate gets the mood
column and not the weight. Both scoped legs fail against the previous handler.
2026-09-10 10:36:35 +02:00
Marc-André Bombeck a7faae8ded refactor(admin): read the off-host card from evidence, sort the worst row first
Four smaller things around the same card.

The configured flag came from the environment of whichever process serves the
request. A hand-rolled split that gives BACKUP_S3_* to the worker and not to
the web process would have shown an operator "nothing leaves this host" over a
ledger full of fresh rows. The ledger is queried either way now, and a row in
it outranks an environment read: a row is proof an upload happened.

Rows sorted by username put the one account that needs attention wherever the
alphabet leaves it, which on a hundred-account cohort is the crowd problem the
card exists to end, moved from a count into a list. Worst verdict first,
alphabetical within a verdict, decided server-side so the tests and the
accessibility fixture see the order the operator does.

The card's docblock claimed the worker holds PutObject and GetObject. The
runbook is right and the multipart path needs AbortMultipartUpload too, so the
prose no longer documents a grant that would break the uploader.

And the byte formatter moved to lib. The off-host card was importing it out of
a thousand-line client component, which costs nothing while both cards render
on one route and becomes a cost the moment either moves.
2026-09-10 10:32:33 +02:00
Marc-André Bombeck 9d18b8fd25 fix(admin): let the error-reporting badge follow reports, not a parseable URL
The badge read the enabled flag plus a DSN that parses. Neither says anything
about the target accepting a report: a wrong public key, a wrong project id and
a host that stopped answering all parse, and every one of them showed green
with a line naming the host. That is the false reassurance an operator finds
out about when they go looking for a crash that was never reported.

Nothing in the tree recorded an outcome, so there was nothing to read. The
sender now stamps one next to the DSN it used — instant on a success, a short
classification on a failure. Never the response body: that is text from a
remote host and has no business in this database or on this page.

The badge is green only while a report has left inside the last fortnight,
amber while a target is set and nothing has come back, and it names the reason
underneath. The clock lives with the ledger, so the verdict is resolved in the
route and the card paints what it is handed. A failure that a later success
superseded is not shown at all. Pressing Test records like any other send, so
the button proves the target on demand.
2026-09-10 10:28:57 +02:00
Marc-André Bombeck 25f0310596 feat(backups): tell an empty ledger apart from an empty bucket
On the release that adds the ledger the table is empty, so on a host that has
been uploading nightly for months every account read Never, under a sentence
saying no copy had ever reached the bucket. That sentence is untrue on exactly
the morning an operator opens the new card for the first time, and it is a
claim the host cannot make: what is empty is the record, not the bucket.

The run now records every account it walks, not only the ones an object came
of. A walk that produced nothing moves the attempt instant and leaves the
success columns alone, so the two cases separate: no row at all is no record
yet, a row without a success is never. Never now means what the word says —
a run looked at this account and has never put anything there.

The card names the last check on the never row, so the state is a fact with a
timestamp rather than an assertion. Runbook and all seven bundles carry the
same two sentences. The integration file proves both arms against real
Postgres, including that a failed run leaves the previous good copy on the
row.
2026-09-10 10:15:31 +02:00
Marc-André Bombeck cfc19a211c fix(backups): give the off-host verdicts slack for a Berlin night that is 25 hours long
The threshold was the schedule period with no budget on top of it. Two things
spend that budget on a host where nothing is wrong. The cron runs 02:30
Europe/Berlin, so on the DST fall-back Sunday the gap between two runs is 25
hours and every account on every host would cross one period on the same
morning. And the ledger instant is when that account's object landed, by
design, so on a cohort walked one account at a time an account reached an hour
later tonight than last night drifts past 24 with two clean runs behind it.

The schedule period and the verdict threshold are now separate numbers. The
period is still what the card quotes; the threshold is the period plus six
hours, applied to both steps, so due still means one run produced nothing and
stale still means two. The fall-back night is pinned in the unit file by its
real dates rather than by an arithmetic 25, and a genuinely missed night at 31
hours still reads due. The runbook says why the slack is there.
2026-09-10 10:09:59 +02:00
Marc-André Bombeck e64435f6a5 fix(backups): size the off-host ledger column for the object the uploader allows
The column was INTEGER. A single object may occupy 8 MiB across 10 000
multipart parts, which is the 80 GB the uploader explicitly permits, and
Postgres INTEGER stops at 2.1 GB. An account between the two uploads fine and
then cannot be recorded, so the biggest account on the host is the one the
console would have to report on and could not.

BIGINT in the table, BigInt in the model, Number() where the route builds the
wire row so the payload type stays a plain number. The migration is edited in
place rather than followed by a second one: the table has not shipped, and a
column widened before its first release is one column, not a history.

The comparison with the in-database backup does not carry over, for the
record: that size is octet_length over a bytea Postgres caps at 1 GB, while
this object never touches the database at all.
2026-09-10 10:07:28 +02:00
Marc-André Bombeck 86823db34e fix(backups): a landed object stays a success when the ledger write does not
The per-account ledger row shared the upload's try. A pool timeout or a
connection reset on that upsert landed in the same catch as a refused upload:
the account was counted as failed, its reason pushed into the run's failure
list, and the console would go on to read never or stale for an account whose
encrypted copy was sitting in the bucket the whole time. That is the same
inversion the ledger was added to remove, on the write side.

The upload's boundary now ends where the object is durable. uploadEncryptedBackup
resolves only after the multipart completes, so the count and the largest-object
figure are taken there, and the row is written afterwards under its own boundary.
A write that fails warns with the account it belongs to and adds a run-level
count, which is a different fact from a failed upload and reads as one.

Two arms that were correct by construction and unasserted now have tests: a
failed upload writes no success row, so the previous timestamp stands, and a
run whose ledger write rejects after the object landed still reports it
uploaded.
2026-09-10 10:04:06 +02:00
Marc-André Bombeck 34d647a884 test(backups): prove the off-host ledger end to end and the card's empty state
The unit tests either side of this mock Prisma, so neither proves the
migration applies or that the writer and the reader agree on a shape. The
integration file runs the real nightly job against real Postgres with an
in-memory bucket, then reads the row back and asks the console's own
classifier what it says: fresh after a run, one row across two runs, stale
once it ages past two nightly periods, gone when the account is.

The component test pins the case an operator most needs stated: a host with
no bucket configured says so, rather than painting an empty list that reads
as "no problems". The accessibility scan's admin-backups response gains one
row in each state, because a card that paints only its header proves nothing
about the rows anybody reads.

Two small corrections ride along, both from writing the tests. The freshness
badge composes its classes through `cn` like every other surface, and the
error-reporting line waits for the settings to arrive instead of asserting
"nothing is sent" while the answer is still loading.
2026-09-10 09:34:33 +02:00
Marc-André Bombeck 532483e782 fix(admin): say where error reports go, and stop calling a silent target configured
There is no default error-reporting DSN in this tree and there should not be:
a self-hoster's crash reports must not leave their host because nobody told
them not to. That part was already right, so nothing here adds a default.

What was wrong is what the console said about it. The GlitchTip card showed a
green "Configured" badge as soon as a DSN existed, whether or not the switch
that actually sends anything was on, and it never said where reports go. An
operator reading that badge has been told their errors are being collected
somewhere, which may be true of neither half.

The badge now tracks reports actually leaving, and one line under the switch
states the case: the host they go to, or that they stay here, or that tracking
is on with no target. The host only — the public key in the DSN answers a
different question. The deploy runbook says the same thing for a
maintainer-operated instance.
2026-09-10 09:28:12 +02:00
Marc-André Bombeck 1c10bbbde8 feat(admin): say per account how fresh the off-host copy is
The nightly off-host job reports counts — uploaded, failed, total — and a
count cannot name the account it is failing for. A cohort where one object
has been refused every night for a month reads as "99 uploaded, 1 failed"
each time, which looks like weather rather than like an account with no
disaster-recovery copy at all.

The worker now writes a ledger row when an object lands (account, instant,
size), and Admin → Backups gains a second card that rates every account
against the nightly schedule: fresh inside one run, due when one run
produced nothing, stale when two did not, never when no object has ever
landed. On a host without BACKUP_S3_* the card says off-host backup is not
configured and stops there.

The verdicts are computed from the ledger, never from a bucket listing: the
worker's grant is deliberately PutObject + GetObject, and an admin page must
not put the operator's credentials on its render path to state a number the
database already holds.
2026-09-10 09:27:58 +02:00
Marc-André Bombeck 036720bcfb docs(changelog): name the modules route's method and the profile refusal as they are
The 1.38.15 entry said PUT where the record-settings route answers PATCH, and promised a rejectedFields field on the managed-profile edit that only the two profile routes carry; the edit refuses with a 422 and the issue list.
2026-09-10 09:09:26 +02:00
Marc-André Bombeck 0c14cbd489 Merge the issue list on every shape refusal, the shared limiter on single-record writes and the error-code catalogue 2026-09-10 08:55:26 +02:00
Marc-André Bombeck 3ffdfe15a1 fix(api): give the shared write ceiling a code a client can branch on
The eleven single-record writes answered their shared 429 with prose and
nothing else, while the envelope's own description tells a client to
branch on `meta.errorCode`. On `POST /api/medications/[id]/intake` and
`POST /api/cycle/day-logs` a second, narrower bucket can answer 429 as
well, so the presence of the rate-limit headers was the only thing
telling the two refusals apart.

All eleven now carry `record_write.rate_limited`, the catalogue lists
it, the published 429 names it, and the contract test fails if a site
stops emitting it or the sentence stops publishing it.

The same description now states what a client could not predict from
"300 requests per 60 seconds": refused requests count too, because the
check runs before the body is read.
2026-09-10 08:39:09 +02:00
Marc-André Bombeck 68964b4bac docs(api): correct two comments that describe behaviour the code does not have
The single-record write ceiling justified itself with "every one of these
routes is already wrapped in `withIdempotency`". Ten of the eleven are.
`POST /api/medications/intake` is not, and it is the one of the eleven a
native client actually loops — it is replay-tolerant for its own reason,
being an update of a named `intakeId` rather than a create. The comment
now says which is which, and adds the clause it was missing: the check
runs before the body is read, so a refused request spends the allowance
too.

The custom-symptom wrapper said a replay "answered the 409 that
uniqueness raises". There is no such 409. The row's key is minted fresh
per request and the label lives in an AES-GCM column with a per-write
IV, which can carry no unique index, so an un-keyed replay wrote a
second row with the same label — a silent duplicate in the person's own
vocabulary, up to the fifty-row cap. The wrapper is worth more than the
old sentence claimed, not less.
2026-09-10 08:38:16 +02:00
Marc-André Bombeck b2c8fe8567 fix(api): answer the unknown-leaf refusal with a sentence and a code
`PUT /api/auth/me/report-selection` threw a bare 422 whose whole `error`
string was `report-selection.leaves.unknown` — a machine token in the
field a client shows a person, with nothing beside it to branch on and
no way to learn which leaves were refused. It now answers a sentence,
with the token in `meta.errorCode` and the refused ids in
`meta.unknownLeaves`, and the operation's description says so.

The site was invisible to the refusal guard because the refusal is
decided by `if (!minted.ok)` rather than by a parse result, so the guard
now reads the refused string as well as the deciding block: every 422
under `src/app/api` whose `error` is a dotted token is inventoried with
the reason it still is one. Eleven remain, each with its reason, and the
inventory may only shrink. Removing the fix above turns it red naming
that route.

The four sibling shape refusals keep their token in `error` on purpose,
and the comment now says why that is not the same decision as the seven
`invalid_json` sites: those moved their string because their status
moved to 400 anyway, while a shape refusal that keeps its 422 would be
changing the wire for nothing. Both halves publish `meta.errorCode`.

Two loose ends in the same guard: a block calling `returnAllZodIssues`
or `apiValidationError` without spelling `422` is now judged (their
default status is 422, so a future `refuse422(err)` helper cannot slip
past), and the site floor moves from 40 to 200 against the 248 the tree
carries — the old floor would have survived losing five matches in six.
2026-09-10 08:35:35 +02:00
Marc-André Bombeck f9561395c7 fix(api): read every module a route reaches when listing the error codes
The catalogue guard read the route tree plus a hand-kept list of library
modules. The dose-history import builds its file-level codes in a module
that list never named, so `empty_file`, `missing_required_columns`,
`unreadable_json`, `json_not_an_array` and `json_carries_no_intake_time`
shipped on `POST /api/medications/intake/dose-history-import` while the
envelope's own description promised every code was enumerated below, and
the guard was green because it had not read the file.

The sweep now walks the import graph from every route under `src/app`:
1423 modules, resolved through the same `@/…` alias the app uses, with
the generated client never opened. A code is read where it is written,
however many hops from the route that answers with it, and nothing is
hand-listed any more. Seeding from the whole app tree rather than
`src/app/api` also reached the clinician share-link document route,
whose three codes were missing for the same reason.

A tuple of codes is read as a family, like the object form already was,
which is what makes the import's union visible; the constant holding it
is renamed to the `*_ERROR_CODES` spelling the sweep reads, since a list
named for anything else is as likely to be nutrients as error codes. The
two sync-ledger writers are cut out of the text first — `errorCode` on
`IntegrationStatus` is a different field with the same name.

Proven by breaking it both ways: dropping `empty_file` from the
catalogue turns the guard red, and a code planted in
`src/lib/analytics/compliance.ts`, a module no list ever named, turns it
red naming that file.
2026-09-10 08:31:44 +02:00
Marc-André Bombeck 348d9e0739 Merge pull request #946 from MBombeck/release/v1.38.15
Release v1.38.15
2026-09-10 08:21:29 +02:00
Marc-André Bombeck 56b6ec7010 test(e2e): read the tile's rate after the skip parity, one figure on both surfaces
The adherence journey pinned the tile at the figure its engine produced before a skip left the denominator; with both engines held to one number the tile reads what the card reads.
2026-09-10 08:06:11 +02:00
Marc-André Bombeck 868efc1c13 docs(api): publish the error codes the server actually emits
`meta.errorCode` is the mechanism this API chose for machine-readable
errors, and the envelope's own description tells a client to branch on
it rather than on the prose. Of the two hundred and forty-two codes in
the tree, sixteen appeared anywhere in the contract. A client had to
discover each one by triggering the error in testing, and had no way at
all to learn that a new one had appeared.

They are enumerated now, grouped by the surface that emits them, in the
description of the field they belong to. The list is generated from the
code and committed as a literal so it reads in a diff, and the sentence
in the document is rendered from it rather than written beside it.

Nothing is renamed. Four naming conventions coexist — dot.case, bare
snake_case, a camelCase segment and a hyphen — and a code is a wire
value a shipped client branches on, so they stay. New codes are
dot.case, and the guard is what stops a fifth convention arriving
unnoticed.

Three families stay outside the list and say why: the assistant refusal
builds its last segment from a template, the integration probes are
enumerated per operation where the per-provider differences can be
stated, and a route checking a credential of its own may answer 401
with no code.

The guard re-derives the set from the tree and fails both ways — a code
emitted and not listed, and a code listed and no longer emitted, which
is the worse of the two because a client can write a branch for it and
wait forever.
2026-09-10 07:47:10 +02:00
Marc-André Bombeck 8d418bc6f8 chore(release): v1.38.15 — the rest of #939, one adherence figure, and an API that says when to come back
Version anchors, the OpenAPI document and the changelog entry. Refs #939.
2026-09-10 07:45:55 +02:00
Marc-André Bombeck ab6c1cd917 fix(api): put a ceiling under the single-record writes
The batch endpoints have been capped at 60 calls a minute since they
were written. The per-record siblings a naive or older client loops
over — the measurement create, the mood entry, both medication-intake
writes, a lab result, a custom-metric entry, a cycle day-log, a
vaccination, an allergy, a biomarker and an encounter — had no ceiling
at all. That is backwards from the risk: the batch endpoint is the one
a well-behaved client uses, and the unlimited path is the one a broken
loop finds.

All eleven share one generous per-account bucket, `record-write`, at
300 requests a minute. Five writes a second sustained for a full minute
is beyond any hand-driven session and any sync burst, and every one of
these routes is already wrapped in `withIdempotency`, so an honest
retry storm is deduplicated before it is counted — the bucket exists to
cut off the pathological loop, not to shape traffic. It keys on the
ACTING account, the precedent the delegable medication routes set, so a
delegate burns their own allowance rather than locking the record's
owner out of their own log.

The eleven operations publish the bucket name and the cap instead of
the generic refusal, on the shared 429 that already declares
`Retry-After` and the rate-limit triple. A test pulls the key and the
window out of the query the limiter runs and holds the published
sentence to them, so the paragraph cannot drift away from the bucket it
describes.
2026-09-10 07:42:07 +02:00
Marc-André Bombeck 17671d9dc1 Merge the AA-contrast status rows on the admin page 2026-09-10 07:41:22 +02:00
Marc-André Bombeck 040b430e73 fix(api): accept an Idempotency-Key on the titration step and the custom symptom
Two more creates the client replays out of its offline outbox ran the
handler again on the replay. A titration step carries no natural key at
all, so a lost success response left the medication with two dose
changes on the same day and the runway estimate reading off the wrong
one. A custom cycle symptom is unique on its label, so the replay did
not duplicate — it answered the 409 that uniqueness raises, reporting a
conflict the client cannot act on for a row it has no record of
creating.

Both wrap in `withIdempotency`, the composition their siblings already
ship, and both operations publish the header and the in-flight 409 so a
client generated against the contract can tell a retry is safe.

The integration file that drives the medication creates twice against
real Postgres gains the titration case: one dose-change row after the
replay, and a replayed 201 carrying `X-Idempotent-Replay: true`.

`POST /api/mcp/tokens` is deliberately not on this list. Its response
carries a freshly minted `hlk_` credential, and the wrapper refuses to
persist a secret-shaped body — publishing the header there would
promise a replay the mechanism will never perform.
2026-09-10 07:40:05 +02:00
Marc-André Bombeck 3e44d68518 fix(api): answer an unparseable body with 400 everywhere
`safeJson` refuses a body that will not parse with 400, and so does
`apiHandler`'s own SyntaxError branch — about two hundred and twenty
routes inherit that. Seven `/api/auth/me/*` writes hand-rolled the
parse in a try/catch and threw 422 for the identical condition, so a
client's "my serializer produced garbage" branch had to accept two
statuses on a subset of routes it had no way to predict.

All seven answer 400 now, with the sentence `safeJson` already sends
and the dotted token each one carried moved to `meta.errorCode`. The
400 is published on those seven operations through a shared response;
it is deliberately not folded into the standard set, which is spread
onto reads as well and a GET has no body to refuse.

`/api/auth/me/health-score-config` keeps its 422: the operation's own
description names that status and its exact message, so moving it is a
contract decision rather than a cleanup. The guard carries it as an
allowlist entry with that reason rather than quietly skipping it.

Three route tests pinned the old status; they assert the new one and
say why. The guard reads the hand-rolled parses out of the tree and
asserts it still finds them, so it cannot pass on a matcher that
stopped matching.
2026-09-10 07:26:32 +02:00
Marc-André Bombeck 9ce0bd5027 fix(api): name the refused fields on every shape rejection
Fifty-nine 422s raised off a Zod `safeParse` answered with one opaque
sentence and nothing a client could map onto a field, while the other
166 sent `details.issues` — the multi-issue envelope that exists so a
caller with three bad fields fixes all three in one round-trip. Twelve
of the fifty-nine put a dotted machine token in `error` where the
sentence belongs, so `error` was sometimes text to show a person and
sometimes a token that must not be shown, with nothing in the payload
to tell them apart.

Every one of them now answers through `apiValidationError`, which keeps
the existing `error` string and the existing `meta` byte for byte and
adds the issue list beside them. The dotted tokens keep their place in
`error` for the clients that already match on them and are published in
`meta.errorCode` as well, which is the field a machine code belongs in
and the one a new client should read.

A guard reads the route tree per refusal site rather than per file —
per file is what let this grow, since a route that used the helper once
looked compliant to a `grep -l` sweep — and asserts it still finds the
sites it judges, so a matcher that stops matching fails instead of
reporting a clean zero.
2026-09-10 07:19:55 +02:00
Marc-André Bombeck 9e1f64e733 fix(admin): keep the worker-status row readable with no worker present
The admin snapshot paints its worker row in `--destructive` whenever the
process serving the page is not the worker: a split deployment running
`HEALTHLOG_PROCESS_TYPE=web`, or a worker that stopped answering. The token
is AA on a card (4.85:1 in the light theme) but the stat tile lays a
`bg-muted/50` wash over that card, and axe measured the tinted wording at
3.97:1 there, under the 4.5:1 AA floor. `e2e/a11y.spec.ts` went red in
exactly that state and green in every other one, which is why the console
could ship it.

The status grids now name a tone instead of spelling a class at every call
site. Success and warning keep their tint, both clear AA on the tile.
Destructive takes the shape the other status rows already use, the
medication detail row and the invite chips: the token paints a small
indicator and the wording stays in `text-foreground`. The word itself
("Stopped", "Error") states the condition, so nothing hangs on the colour
alone. The database, Umami and GlitchTip rows sit on the same surface with
the same tint and move with it.

The success-affordance guard's two pinned entries for the status grids went
stale in the process: the tint they carried now lives once in the tone
table, so the pins follow it there.

Checked against a standalone build on a throwaway database: the whole a11y
spec green in both themes and both viewports with `HEALTHLOG_PROCESS_TYPE`
at `web` (the failing state) and at `all`. jsdom cannot measure a contrast
ratio, so the new unit test pins the token choice for both arms instead.
2026-09-10 06:56:50 +02:00
Marc-André Bombeck c64708cc37 test(ci): pin the third end-to-end server the notification journey drives
The determinism guard counted two Playwright servers and would have refused a third by deletion; the notification journey's mail-configured, scheduler-free process is the third. Pin it by its two distinguishing variables and assert the shared servers carry no mail configuration.
2026-09-10 06:49:14 +02:00
Marc-André Bombeck 8b1ca7ee5a Merge the notification dispatch end-to-end journey, the account-scoped reminder sweep and the published notification preferences 2026-09-10 06:37:56 +02:00
Marc-André Bombeck 74dbb1a2e4 test(e2e): give the notification journey a server and a scope of its own
The journey's isolation went one way only. `test.describe.configure` orders
the tests inside the file; the suite is fullyParallel with two workers, so
everything else runs beside it — and its own trigger, the admin reminder
sweep, walked the whole instance and dispatched for every account that had
an overdue dose. With the mail env pointed at the local responder, that
would have started sending real messages for accounts this file has never
heard of, and the exact-equality assertion on the accepted recipients would
have been reading them. The sweep now names the account it then counts, and
the comments that defended the opposite direction say what the exposure
actually is.

Its own server, too, and for two reasons. The `SMTP_*` vars decide whether
the Email card renders at all, so on the shared server they put a card the
axe scan and the card-anatomy sweep had never measured onto
`/settings/integrations` for every spec that opens the route. And unset,
`HEALTHLOG_PROCESS_TYPE` starts the pg-boss reminder scheduler inside the
process serving requests, whose every-fifteen-minutes tick either mints the
missed-dose row that makes the sweep skip its own dispatch or dispatches
beside it. A third server carries both: mail configured, `web`, and only
this spec talks to it.

The shared server keeps `all` on measured grounds rather than taste. Worker
status is per-process and in-memory, so a `web` process reports the worker
stopped, `/admin` renders that row destructive-red, and axe fails it at
3.97:1 against the muted tile — a real contrast defect any operator running
the documented web/worker split already sees, and not this branch's to fix.
That limit is written where the server is defined.

Also here: the stub draws its port per run instead of pinning one, and says
so by name when the port is taken; teardown ends its sockets and survives a
setup that never got as far as starting it; the ledger reset stops deleting
rows whose subject is this account but whose recipient is somebody else,
and clears intake events explicitly rather than through a cascade; the
attempt poll refuses a window larger than the twenty rows the diagnostic
returns; and the header names the precondition the file cannot enforce and
the internal reasons it pins on purpose.

Verified against a production build and a throwaway Postgres: the journey
three times over at one worker, then the a11y and settings geometry specs
at two. Both assertions broken once to see them fail.
2026-09-10 06:35:40 +02:00
Marc-André Bombeck ee73e840e0 Merge the backup and restore end-to-end journey, the restore that leaves instance settings alone and the 422 for an unreadable copy 2026-09-10 06:09:23 +02:00
Marc-André Bombeck fd6fa18913 feat(api): publish the resolved notification preferences on the account payload
The medication detail's notification section decides between the
server-side reminder switch and the client-managed chip on
`notificationPrefs.medication.clientManaged`, read off `GET /api/auth/me`.
That payload never carried the field — the preferences live on their own
endpoint, which is not on the app-boot path — so the flag was `undefined`
for every account: the chip never rendered, and a person whose phone owns
the reminders was shown a switch that no longer decides anything. The
write path and the dispatch gate were correct the whole time; only the
web reflection was missing its end.

The payload now carries the fully-resolved block from the same resolver
the dedicated endpoint uses, so the two cannot disagree, and an account
that never opted in reads `false` rather than absent. No extra query: the
session already loads the row the column sits on.

The pair guard over this payload gained the direction that could not see
it. It asked that every published field has a reader; a reader with no
field was invisible. It now also reads the response types clients declare
for this endpoint and holds them against what the route publishes. A
typed guard was tried first and does not work here — each consumer
declares its own local interface, so the compiler checks every file
against its own private claim and agrees with all of them.
2026-09-10 06:04:39 +02:00
Marc-André Bombeck f3321b8031 feat(api): let the admin reminder sweep name one account
`POST /api/admin/notifications/reminder-check` walked every active
medication on the instance and dispatched a reminder for each overdue
slot it found. That is the operator button's intended behaviour and it
stays the default, but it left any other caller — a browser journey, a
smoke check — writing into every account's delivery ledger at once with
no way to say otherwise.

The body now accepts an optional `userId` that narrows the sweep. It can
only narrow: the route is `requireAdmin()`, cookie-only by construction,
so a Bearer caller never reaches it however wide its scope, and the
selector feeds the Prisma `where` rather than the authorisation. A
bodyless POST — what the admin panel sends — is unchanged. An unknown key
is a 422 instead of a silently instance-wide run.

Published in the contract alongside the notification diagnostic, so the
scope is readable rather than folded into the console-only exemption.
2026-09-10 06:00:27 +02:00
Marc-André Bombeck 343d6397a0 test(e2e): say what the backup journey really touches, and pin it to promises
The file claimed it stayed inside its own account. "Backup now" enqueues the
pass for every account on the instance, so the header says that now, and says
what is confined instead: the restore's transaction, and the instance-wide
settings the dialog's opt-in leaves alone — which the journey asserts is clear
before it confirms, because a default that flipped would hand this file the
power to rewrite the document size cap for every spec sharing the server.

The run's own answer is asserted where it happens. Without it a missing worker
cost two minutes of polling and then blamed the backup pass for a 503 about
something else; the failure now names the endpoint in two seconds.

The rest are the assertions that pinned incidentals rather than promises: the
Argon2 cost comes from the constant the writer exports, so a legitimate cost
bump is not a red spec; the document is found by id rather than by position;
the poll compares the row against the row it saw before the click rather than
against the runner's clock; the non-admin bounce is pinned by pathname; the
empty-state CTA has its own test id, so nothing has to pick between two
buttons that share one; the deliberately corrupted copy is deleted when the
control is done with it instead of sitting in the console's list; and the
fixture orders by id after the timestamp so a tie cannot present as a change.
2026-09-10 05:48:18 +02:00
Marc-André Bombeck 8be51d9beb test(e2e): cover notification preferences through to the dispatch decision
One browser journey for the web arm of notification delivery: an account
configures its channels on the settings surface, a due medication reminder
runs through the product's own sweep, and the dispatch decision is read back
off that account's `push_attempts` ledger via the admin diagnostic.

What it pins:
  - the enabled channel delivers (`result: ok`) and the message really leaves
    the process, asserted against a local SMTP responder rather than against
    the ledger row alone;
  - a channel that is configured and switched OFF is never attempted, and its
    own test control is inert on the surface;
  - the APNs arm is attempted and skipped, and the ledger's reason
    distinguishes the transport refusing (`apns_not_configured`) from the
    client-managed opt-in refusing (`client_managed`) — with email still
    delivering under the opt-in, which is the published "APNs leg only"
    contract;
  - an ntfy relay URL inside a private range is refused with 422, leaves the
    stored config untouched, and writes no attempt.

Email is the channel exercised for real because it is the only one that can
be: every account-supplied delivery target crosses the SSRF floor
(`isPublicUrl` plus `safeFetch({ requirePublicHost: true })` with a
connect-time address pin), so ntfy, the generic webhook and Web Push refuse a
local stub by design, and Telegram and APNs address hard-coded third parties.
Email's transport is operator configuration, so `e2e/setup/smtp-stub.ts` can
stand in for it end to end. The config points the e2e server at that stub.

The journey carries one skipped test at full strength: the medication detail
surface decides between the reminder switch and the client-managed chip on
`notificationPrefs.medication.clientManaged` read out of `/api/auth/me`, and
that payload does not carry the field. The flag therefore reads as false for
every account and the chip never renders, so a person whose phone owns the
reminders is still shown a server-side switch that no longer decides anything.
The write path and the dispatch decision are both correct; only the web
reflection is missing its end.

The account and its jar are seeded in global setup, and its channels, devices,
ledger and preferences are reset before every test so the counts are about the
run in front of them.
2026-09-10 05:41:17 +02:00
Marc-André Bombeck 6e4f3fb4c4 docs(ops): what a restore replaces, and the console path
Two gaps in `backup-restore.md`. It said the restore "replaces the account's
data tables" only in a paragraph about grants, so nothing stated the
consequence for the account's own record: the rows it gained after the snapshot
was taken are deleted with the rest of their class. And the console restore was
named once in passing — `## Restore` documents only the off-host script — so an
operator restoring from the browser had no procedure to read.

Both are written down now, including which button does what, that the restore
targets the snapshot's owner rather than the admin running it, that
instance-wide settings ride along only when the dialog's opt-in is ticked, and
what a copy this instance can no longer decrypt answers.
2026-09-10 05:26:56 +02:00
Marc-André Bombeck fd176f621d fix(backup): say what the backups console actually does
Two places claimed a stored payload cannot leave the page: the card's own
description ("payloads are not downloadable from this page") and the listing
route's comment ("admins can trigger a re-snapshot but not download another
user's payload from the UI"). Both have been false since the download button
shipped — every row carries one, and the route hands back the decrypted JSON.

The description now says what happens instead: sizes are the encrypted blob,
Download decrypts the snapshot for the admin who asks, the ciphertext stays in
the database. Seven catalogues, and the route comment points at the route that
owns the payload.
2026-09-10 05:26:31 +02:00
Marc-André Bombeck d3f087475c fix(backup): refuse a stored copy that will not open with 422
A `DataBackup` row that fails to decrypt answered 500 on the restore, the
download and the preview. It is not a server fault: either the key that wrote
the copy is no longer in `ENCRYPTION_KEYS` — a rotation that dropped the legacy
entry before the script reported zero rows, the case the rotation runbook warns
about — or the stored bytes are not the ones that were written. Every other
bad-input arm on those routes already answers 4xx, and the 500 also paged the
error reporter as if the process had broken.

All three now answer 422 with `meta.errorCode = backup.payload.undecryptable`
and one shared sentence, so the three routes cannot drift into three wordings
for one condition. The download's second 500 stays: a payload this instance
wrote and cannot parse really is a fault here.

The two routes that open a stored copy move from the unpublished list into the
contract, because the refusal is now a promise an operator can look up rather
than whatever the handler happened to answer. The restore publishes its
`Idempotency-Key` header with them.
2026-09-10 05:25:30 +02:00
Marc-André Bombeck 6b366b4f27 fix(backup): make the console restore leave instance settings alone
A disaster-recovery snapshot carries the singleton `app_settings` row —
registration, the MFA requirement, the default locale and timezone, module
availability, the notification and AI configuration, the document size cap and
quota — and the restore wrote it back as a side effect of restoring one
account. An operator putting a single record back on Wednesday reconfigured the
whole host from Monday's file, silently, with nothing on screen saying so.

Rebuilding a host from a snapshot is a real case, so the write stays: it is now
`restoreInstanceSettings: true` on the request and a checkbox beside the typed
gate, off unless the operator ticks it. Restoring an account and reconfiguring
the installation are two decisions, so they are two answers.

The 422 confirmation sentence and the dialog copy drop the instance-wide claim;
the opt-in carries it instead, in all seven catalogues. Integration coverage
runs both arms: without the flag the settings row keeps its own values, with it
the file's values land.
2026-09-10 05:16:59 +02:00
Marc-André Bombeck 6a2282fef8 Merge Retry-After on every refused request, stable list pagination and the corrected error contract 2026-09-10 05:10:05 +02:00
Marc-André Bombeck 6f718121c7 test(api): use the real caps in the limiter mocks, and drop a stale pointer
Three consent-surface tests mocked the shared AI-consent bucket at 60 where it
is 20, and the analytics-read and MCP mocks named 60 against real caps of 120.
Nothing asserts the number today, so nothing was wrong on the wire — but the
mocked verdict now carries `limit` all the way to `X-RateLimit-Limit`, and the
first test that reads that header off a mock would pin the fiction.

The response-shape file's header pointed at a document that is not in the
repo; it says what it means directly instead. It also now records the one
thing the gate cannot see: `meta` is a loose object on purpose, so undeclared
keys inside it survive the parse and the strip comparison does not reach them.
2026-09-10 05:07:15 +02:00
Marc-André Bombeck cf9e8b8790 docs(api): declare the 429 headers instead of only describing them
The shared 429 named `Retry-After` and the `X-RateLimit` triple in prose, so a
generated client got no typed accessor for the field the same sentence tells
it to back off on. They are a `headers` block now: `Retry-After` and the cap
and remainder as integers, the reset instant as a date-time. The text also
says what a 429 from a ceiling that is not one of these buckets carries —
nothing, because there is no bucket to describe.

Two route descriptions still listed the pre-change header set: the ingest 429
named only `X-RateLimit-Remaining` / `X-RateLimit-Reset`, and the document
suggest 429 named only the reset instant beside `meta.retryAt`. Both are short
of the wire in exactly the direction this work exists to close.
2026-09-10 05:07:08 +02:00
Marc-André Bombeck 42100d94a7 fix(api): finish the pagination tiebreaker, and state the tie premise correctly
The comment on the measurements list justified the tiebreaker with an Apple
Health import stamping long runs with one instant, and said the unique index
forbids two live measurements of the same type at that instant. The index is
`(userId, type, measuredAt, source, sleepStage)`, so the named example is the
one case it does block — while ties survive across `type` (the `stats:` daily
rollups), across `source` (two writers landing together) and across
`sleepStage`. Same conclusion, honest premise.

The per-day drill-down on the same route still sorted on `measuredAt` alone.
It slices in memory rather than with `skip`, so nothing drifts between pages,
but two identical requests were free to render a tied block in different
orders, and a list that reshuffles on refresh reads as data changing.

Three of the tiebreakered routes had nothing pinning the order: custom-metric
entries, the per-medication intake history (both sort arms, so the NULLS LAST
pin cannot be lost to the tiebreaker) and the mental-health assessment
history. Each now asserts the `orderBy` the way the illness day-log test does.
2026-09-10 05:07:02 +02:00
Marc-André Bombeck 2c63b0c4a7 fix(api): give the remaining 401 throws a code, and say what the code covers
Three refusals still answered 401 with prose alone: the Bearer re-read on
`/api/auth/me/sessions`, and the wrong-second-factor arm on both MFA step-up
routes. The shared 401 description told clients the code is the field to
branch on, so a client that took that advice landed in its default arm on all
three — and on the MFA pair that is the difference between re-prompting for a
digit and signing the user out over a typo.

The sessions re-read is the same missing-credential fact the gate already
names, so it reuses `auth.missing`. The MFA pair gets a code of its own,
`auth.mfa.code_invalid`: none of the existing ones fit, because every other
401 code asks the client to discard something, and this one asks it to keep
the session and try another code.

The description narrows to match what is actually true. The generic gates
name a reason; a route that checks a credential of its own — sign-in, the MFA
challenge exchange, a password confirmation — still answers 401 with prose,
and the text now says so instead of promising a field those responses do not
carry.
2026-09-10 04:59:40 +02:00
Marc-André Bombeck dd8a724039 fix(api): floor Retry-After at one second on a refusal
`resetAt` is written by Postgres as `NOW() + interval` and subtracted from the
app process's clock, so a row that still refuses can read as already expired
here. The old floor let that render as `Retry-After: 0`, which tells a client
to retry immediately into the ceiling that just turned it away — a contradiction
of the status it rides on, and a hot loop for anything that honours the header.

One second is the honest minimum on a 429. The rounding-up rule and the reason
for it are unchanged; only the floor moves.
2026-09-10 04:55:47 +02:00
Marc-André Bombeck dd3844a7a2 fix(api): dress only the 429s a limiter actually refused
The request-scoped capture kept the last verdict of any kind and fell back
to it when nothing had refused. That fallback fires in exactly one state —
no limiter refused this request — which is the definition of "this 429 came
from somewhere else". So a daily AI budget that is spent until midnight, an
hourly generation quota, and a provider-side 429 relayed onward all went out
carrying our own bucket's numbers: a remainder that says there is room left
and a Retry-After measured against an unrelated window. On the AI paths the
captured window can also expire while the provider call runs, so the dressed
delay could land at zero and tell the client to retry immediately into the
ceiling that had just refused it.

The cell now keeps refusals only. A request every bucket let through reports
nothing, and a 429 from another cause leaves undressed, which is correct:
there is no bucket to describe. The two-limiter rule is unchanged — the last
refusal wins, and a refusal still outranks a pass.

The unit case that pinned the fallback is turned round, and both directions
now run through the real wrapper: a limiter refusal gets the headers, a 429
raised without one gets none. The integration file gains the two shapes it
was missing — a route that consults two buckets must report the one that
refused, and a route whose 429 comes from the daily budget must carry no
rate-limit headers at all.
2026-09-10 04:55:19 +02:00
Marc-André Bombeck 8865e1b225 Merge the second-factor end-to-end journey and the confirmation dialog fix 2026-09-10 04:53:50 +02:00
Marc-André Bombeck 5cb5c7df44 test(e2e): drive backup and restore end to end through the settings surfaces
One journey across the whole path: an account writes readings in three
domains and files a PDF, downloads its own record as the passphrase-sealed
archive, an admin snapshots it from the backups console, and the snapshot is
restored over an account that has since lost a reading and a dose and gained
one the snapshot never saw.

The assertions address what the documentation promises rather than what the
implementation happens to do. The archive is checked byte by byte against the
HLX1 header in src/lib/export/passphrase-archive.ts — magic, version, KDF id
and the Argon2 cost the file carries — because "a file arrived" is equally
true of plaintext JSON under a new extension. The restored reading and dose
are checked by their ORIGINAL ids, because a restore that re-created them
under fresh ones would have written a different record that reads the same.
The reading created after the snapshot is asserted GONE: the runbook says the
restore replaces the account's data tables, and replacing is not merging.

Two refusing controls. A stored copy with one flipped ciphertext byte is
refused with the route's decrypt failure and leaves the record untouched — the
envelope is AES-256-GCM and its tag covers every byte, so the flip is caught
before the transaction opens. A delegate holding whole-record READ inside the
account gets the not-covered panel instead of the export card, never reaches
the console, and is refused 403 by the list, the manual run and the restore,
the last of them naming the real snapshot so the refusal cannot be mistaken
for a missing row.

Waiting is on the job's own evidence: the console's endpoint is polled until
this account's stored copy is newer than the click, so nothing in the file
guesses at a queue. The journey has its own account, its own delegate and its
own cookie jars; only the reset between repetitions and the deliberate
corruption reach Postgres directly, because a browser cannot express either.

The backups console gains data-testid hooks and a data-backup-id on each row
so the spec addresses controls rather than translated labels.
2026-09-10 04:53:03 +02:00
Marc-André Bombeck 01fe007f35 test(e2e): take the TOTP parameters and the field hooks from the source
The spec re-declared the server's algorithm, digit count and period as
literals, so a change to any of them would leave the spec generating codes the
server no longer verifies and blaming the product. It imports the three
exported constants instead; the recovery-batch size stays a literal, because
its module pulls in the database client and would drag the generated client
into the Playwright process.

The two credential fields on the login form are addressed by test id now, like
the submit button beside them, and the recovery toggle at the challenge is
renamed to the house's noun-verb order.
2026-09-10 04:52:53 +02:00
Marc-André Bombeck 78789e090e test(e2e): measure the login cap the journey keeps clearing
The journey emptied every `auth:%` bucket before each sign-in, which is wider
than it needs and takes the register, passkey and reset buckets with it — a
future spec measuring one of those throttles would find its evidence deleted by
an unrelated sign-in. The clear now names the two surfaces this file spends.

It also left the throttle as the one auth control the journey rides on and
never sees: no spec in the suite asserted a 429, and this is the only one that
posts a real login at runtime. A closing stage spends the cap from an empty
bucket and asserts the answer that goes over — 429, with the bucket's own
remaining and reset headers. It costs nothing: the account is dropped
immediately after and nothing else signs in from there.

The bucket is keyed per IP and every spec on the machine is that IP, the
sibling browser project included, so the measurement is taken in one project
and a round disturbed by the sibling is retried rather than asserted. Two
probes emptying and filling one bucket beside each other were seen to measure
their own interference instead of the limiter.
2026-09-10 04:52:33 +02:00
Marc-André Bombeck b428fcf74f test(e2e): read the replay verdict instead of inferring it from a 401
The replay control submitted the enrolment code at the login challenge and
asserted a 401. That 401 is the same answer the route gives a code that has
simply drifted out of its ±1-step window, and by the time the journey reached
the challenge — a rotation, a refused rotation, a sign-out, a page load and an
Argon2id verify later — the enrolment code usually had. Out of window, the
refusal happens before the monotonic floor is ever consulted, so the control
could pass with the floor deleted.

Both TOTP refusals now assert the verdict the route records itself,
auth.mfa.failed with details.replay, written and awaited before it answers:
false for a code that never matched the secret, true for the replay. Flipping
that verdict while leaving the refusal in place turns the positive half red,
which is what the old assertion could not do.

The replayed code is the one the previous sign-in just spent, so the window is
a property of the journey rather than of the wall clock: the accept is taken at
a step boundary when the current step has too little left, which bounds the
wait by one period and leaves the pair at least two.

The rotation stages no longer press Escape to get the confirmation out of the
way. They assert the card closes it, by test id.
2026-09-10 04:52:11 +02:00
Marc-André Bombeck 36410831ed fix(settings): close a confirmation when its request settles
The confirming click on both alert dialogs in the TOTP card calls
preventDefault(), which is what keeps the dialog up and its button disabled
while the request is in flight. Nothing took the dialog down again, so a
refused rotation left the confirmation open over the card, and the card is the
only place the refusal explains itself: the step-up message painted behind the
overlay, inside the aria-hidden region the modal creates, with the confirm
button live again. A success hid it, because the fresh-codes panel replaces the
branch the dialog lives in and it unmounted anyway.

Both dialogs are controlled now, and each mutation closes its own when the
request settles, whichever way it went. The disable arm carried the same shape
and a mistyped six-digit code there is routine, so it is fixed with it.

The card test pins the sentence a step-up refusal shows and the wiring that
takes the dialog down; what a person sees is asserted against a real browser in
e2e/mfa-step-up-journey.spec.ts.
2026-09-10 04:49:11 +02:00
Marc-André Bombeck 7c9740c657 Merge the per-module access reason on the account payload 2026-09-10 04:41:57 +02:00
Marc-André Bombeck 47a5079cfa feat(api): say why a module's surfaces are not there, not only that they are not
`GET /api/auth/me` publishes a boolean per module, and three different
situations collapse into the same `false`: the record has the module switched
off, the active grant's sections do not open it, or the operator switched it
off for the whole instance. A client holding the boolean has to guess between
them, so the empty state either says nothing or says something that may be
untrue -- offering a delegate a switch that is not theirs to reach, or telling
an account holder to turn on a module the operator removed.

`moduleAccess` carries the reason beside the booleans, which keep their exact
meaning: `enabled`, `disabled`, `not_granted`, `unavailable`, resolved
outside-in so the reason published is the one nothing further in can change.
`modules[key]` stays exactly `moduleAccess[key] === "enabled"` for every key,
and the two halves are built independently -- the boolean still runs through
`maskModulesToSections` -- so the test of that pairing is an assertion rather
than a restatement of a derivation. It is checked on the pure builder across a
matrix of grants, records and operator blobs, and again on the real route for a
scoped delegate, an unscoped one, and an operator-disabled module.

Both ends in one change, because a payload field with no reader is the failure
this repository keeps rediscovering. The reader is `ModuleDisabledNotice`, the
shared module-off empty state the empty-states audit asks for: it names the
reason in the reader's own language and offers the enable control only when the
record's own switch is what is off, since neither of the other two is fixable
from that page. The nutrients page adopts it and drops its bespoke block, which
had been handing every delegate a button that would refuse them.

Registered in the OpenAPI registry as `ModuleAccessMap` and carried on the
account payload; the native contract gains a field and loses nothing, since a
Bearer request carries no switch and never reads `not_granted`.
2026-09-10 04:41:38 +02:00
Marc-André Bombeck 21dd7c7e48 fix(api): give the generic auth refusals a stable errorCode
`requireAuth`, `requireAdmin`, `requireCookieAuth`, `requireFreshMfa` and
`requireBearerAuth` all refused with a bare prose string and no `meta`.
So the single most important branch a native client makes — refresh the
token and retry, drop the session and show the login screen, or stop
retrying because this credential will never work — could only be made by
string-matching the English sentence "Token expired". Any rewording of
that string, or a localisation pass, silently turns a recoverable
refresh into a forced logout for every already-shipped build.

The mechanism was already here and these gates were the ones skipped:
the assistant, consent, step-up, module and sharing refusals all carry
`meta.errorCode`, and `/api/auth/refresh` emits `auth.refresh.*`. So
`HttpError` takes an optional code and the wrapper puts it in the same
field. Five values, dot.case like the majority: `auth.missing`,
`auth.token.expired`, `auth.token.invalid`, `auth.scope.insufficient`,
`auth.admin.required`. A revoked token reads invalid, not expired —
refreshing a revoked token loops forever.

Additive: an HttpError thrown without a code serialises byte-identically
to before, which is most of them. The published 401 description now
enumerates the codes and says what a client should do with each.
2026-09-10 04:24:34 +02:00
Marc-André Bombeck 18302c64f8 Merge the skip parity between the two compliance engines 2026-09-10 04:23:01 +02:00
Marc-André Bombeck a792ac09b1 Merge the doctor-report end-to-end journeys 2026-09-10 04:22:47 +02:00
Marc-André Bombeck 89ec49cd42 Merge the medication adherence end-to-end journey 2026-09-10 04:20:01 +02:00
Marc-André Bombeck 06d2104808 Merge managed-profile editing, sex at creation and module switches per record 2026-09-10 04:19:35 +02:00
Marc-André Bombeck a7bdf14a4e test(api): pin the pagination tiebreaker in the two route tests
Both asserted the single-column `orderBy` the offset lists used to build,
so they held the defect in place: a test that pins the shape a fix has to
change is not evidence, it is a lock. Turned round to assert the total
order, with the reason at the call site.
2026-09-10 04:17:45 +02:00
Marc-André Bombeck 4993352cc9 test(api): parse real responses against the schemas that publish them
Response drift was structurally undetectable. `openapi:check` proves the
YAML matches the registry and the route-coverage guard proves the verb is
listed; both pass when the registered schema disagrees with what
`apiSuccess()` sends, and the coverage guard says so in its own doc
comment. That is how `/api/sync/changes` shipped five domains against a
three-domain contract and how the error envelope went years without
declaring the field the multi-issue 422 was built for.

Two bodies, the two that were broken: a full `/api/sync/changes` page
with live and soft-deleted rows in all five domains, its `cursorExpired`
short-circuit (a second shape under the same schema), and a 422 carrying
more than one issue.

`safeParse` alone would not have caught either finding, because Zod
strips undeclared keys instead of refusing them — a schema short of the
wire parses cleanly. So the parsed value is compared back to the raw
body; a strip means the contract is missing something the server sends.
Removing `cycleDays` / `cycles` from the sync schema, or `details` from
the envelope, fails all three cases.
2026-09-10 04:08:52 +02:00
Marc-André Bombeck 0cd996e7de docs(api): declare the two sync domains that were already on the wire
`GET /api/sync/changes` returns five domains — measurements, mood,
intakes, cycleDays, cycles — and has since the cycle module landed. The
registered schema declared three, closed the object and required only
those three, so `cycleDays` and `cycles` did not exist in the contract:
full day-log and cycle payloads, both upserts and tombstones, computed
and serialised on every single pull, invisible to any client generated
from the spec. The body was also invalid against its own schema, since
the object was closed against the two keys it always sends.

The day-log and cycle DTOs were already published for the cycle routes,
so the two upsert arrays reuse them and only the tombstone shapes are
new. The module's own description and the operation summary were stale
in the same direction and now name all five.

This is the two-ended change the contributor notes describe: the writer
shipped, the contract half did not, and no gate noticed because every
gate proves the other end.

No wire change.
2026-09-10 04:05:04 +02:00
Marc-André Bombeck fd8fc0ec0e docs(api): publish details.issues and open meta on the error envelope
Every documented 422, 401, 403, 409, 410 and 429 points at one
`ErrorEnvelope`, and that schema declared `data`, `error` and a `meta`
closed to `requestId` + `errorCode`. Two things were wrong with it.

`returnAllZodIssues` has sent a third top-level key since v1.4.42 —
`details.issues`, one entry per rejected field — from 166 route files.
It exists so a client can fix three bad fields in one round-trip instead
of three, and the doc comment says so, yet no component schema anywhere
declared it. A client generated from the contract had no field to read
it from, so the feature was invisible to exactly the consumer it was
built for. It is now a schema, with the `unrecognized_keys` list and the
promise that no rejected value is echoed back.

And `meta` was closed while real refusals put more in it: `removedIn` /
`replacedBy` on a 410, `module` beside `module.disabled`, the
per-integration context on a failed connection test. Closed plus those
keys means the response was invalid against its own published schema and
a strict decoder is entitled to reject it. It is open now.

No wire change; both halves describe what the server already sends.
2026-09-10 04:03:02 +02:00
Marc-André Bombeck 3e063f48ae fix(medications): a skipped dose leaves the dashboard tile's denominator
The two compliance engines disagreed about a deliberate skip. The dose-history
ledger (`tallyComplianceFromLedger`, behind the medication card, the dose
history, the doctor report and the Health Score pillar) has excluded a skipped
dose from the denominator since v1.15.9 — a skip is a pause, not a miss. The
schedule-anchored engine behind the dashboard tile and the adherence storyline
built its denominator from the raw expected-slot count with no skip term, so it
counted the same slot as expected-and-missed. A twice-daily day with one dose
taken and one skipped read 100 % on the card and 50 % on the tile.

The skip term now lands in the engine, not at the call sites: the day's
expected count drops the doses the user skipped, capped at the minted slots,
and a day whose every expected dose was skipped falls out of the buckets the
same way it falls out of the ledger denominator. The schedule anchoring, the
per-day buckets and the duplicate-log cap are untouched — only the skip
treatment moved. `skipped` outranks `autoMissed`, mirroring
`reconstructDoseHistory`, so a dose the auto-miss cron marked forgotten still
counts against the rate.

A new parity test feeds one fixture (twice daily, one taken, one skipped, one
missed) to both engines and pins them to the same figure, so the class cannot
come back through either side; both new cases were confirmed to fail against
the previous behaviour. The tile-engine suite gains the corrected figure.
2026-09-10 04:01:32 +02:00
Marc-André Bombeck 1d2744a109 fix(api): give every offset-paged list a unique tiebreaker
`/api/measurements` and `/api/labs` sort on one non-unique column and
page with `skip`/`take`. When the sort key ties, Postgres does not
promise the same order for the query that fetches page N and the one
that fetches page N+1, so a client paging its own history can receive a
row twice and never receive another — silently, on both sides.

Ties are not hypothetical here. The partial unique index forbids two
live measurements of the same type at one instant, but the tie that
occurs in production is the cross-type one: a daily `stats:` rollup
posts steps, distance, flights and active energy at the identical
timestamp, and an unfiltered history list pages straight through the
block. A lab panel drawn in one sitting shares `takenAt` across every
analyte in it.

Appending `{ id: <same direction> }` to the `orderBy` makes the order
total. Same fix on the five siblings that page the same way — medication
intake history, illness day-logs, custom-metric entries, reminder
history, mental-health assessments — because the defect is the shape,
not the two routes it was found on. No wire change; `/api/sync/changes`
already ordered this way.

The fixtures seed ids in an order unrelated to insertion order, so the
assertion on order inside the tied block can only hold if the secondary
key is doing the work: with the tiebreaker removed the new file fails on
all three cases.
2026-09-10 04:01:14 +02:00
Marc-André Bombeck 08100b6207 fix(api): put Retry-After and the rate-limit triple on every 429
A refused client had nothing to back off against. `rateLimitHeaders()`
emitted `X-RateLimit-Remaining` and an ISO `X-RateLimit-Reset`, no
`Retry-After` and no cap, and only about 70 of the 199 route files that
consult a limiter attached even those two. The rest answered with a bare
prose envelope, including every endpoint an offline replay queue hits:
the four batch ingests, `/api/sync/changes` and `/api/auth/refresh`. A
first-run Apple Health import trips the 60-per-minute batch ceiling
reliably, and the only strategy left to the client was a blind backoff.

Threading headers through 129 handlers is 129 edits the next new route
forgets, so the verdict is carried instead: `checkRateLimit` records it
in a request-scoped cell and `apiHandler` dresses any 429 that leaves
without headers. A route that already built its own is left alone —
`Retry-After` is the presence test, and it comes from the same builder.

`Retry-After` is whole seconds rounding UP (RFC 9110 §10.2.3), floored
at zero. `X-RateLimit-Limit` is new and needs the cap, so the limiter
result carries it. `X-RateLimit-Reset` keeps its ISO form: it is the
wrong convention for the name, but it is on the wire today and changing
it is a decision of its own.

The cell lives in its own leaf module because 177 test files replace
`@/lib/rate-limit` wholesale with a mock factory, and `apiHandler` must
not depend on anything those factories stand in for.
2026-09-10 03:55:46 +02:00
Marc-André Bombeck 50a65b6f80 test(e2e): cover the second-factor journey end to end
Enrol TOTP from the settings surface, sign out, sign back in through the
challenge, and step up for a recovery-code rotation — in a browser, against
a real server, on a throwaway account the journey seeds and drops itself.

Four refusals ride alongside the four positives: a wrong code at the
challenge (401, no session cookie, and the ticket's attempt counter moved),
the enrolment code replayed (401, refused by the monotonic totpLastStep
floor), the rotation once the session's mfaVerifiedAt has aged past the
five-minute window (401 with meta.errorCode auth.stepup.required), and a
recovery code presented a second time (401). Each was proved to fail by
removing the control it stands on and watching that one assertion break.

Codes are computed from the enrolment secret with the otpauth dependency the
server verifies against, at explicit timestamps, so nothing waits on a step
boundary: the sign-in code is generated one step ahead of now, inside the
±1 drift window and necessarily above the replay floor.

The fixture reaches Postgres for the two things that have no endpoint by
design — ageing the step-up stamp, and emptying the per-IP auth buckets
this journey would otherwise exhaust. The account carries the Playwright
project name so the two browser projects never drive one factor state.

Adds data-testid hooks on the TOTP card, the login step, and the password
form so the spec asserts on stable attributes instead of rendered text.
2026-09-10 03:53:11 +02:00
Marc-André Bombeck 923b832891 test(e2e): correct three claims the report journey's comments make
The mobile exclusion carried an inherited second reason — that mobile
emulation emits no download event for the panel's anchor click. The
precedent it came from contradicts itself: the JSON example-download
test in `settings-export.spec.ts` asserts a real download event in the
mobile project, and that spec also measures this very panel's tap
targets there. The honest statement is that the panel's mobile layout is
covered elsewhere and this journey is about the artefact.

The bytes are read off the download because the saved file is what the
person ends up with, not because a consumed body reads back empty —
Playwright buffers the response independently of the page.

And the filename assertion covers the name the client anchor invents,
not the route's `Content-Disposition`; the two differ by a word, so it
is not contract coverage of the header.
2026-09-10 03:49:32 +02:00
Marc-André Bombeck 094eb13b5f test(e2e): read the report's period line in the account's date order
The period assertion hardcoded a slash-separated month-first rendering.
The field order comes from the account's date-format preference, so a
DMY account prints dots and fails with a message claiming the report
carries no period at all, while an en-GB rendering matches, swaps the
two fields and computes a nonsense span in silence.

The order is now read off the account and the separator is captured once
and back-referenced, so all three renderings parse and none can be read
as another. `AUTO` is refused rather than guessed at: the fixture pins
an explicit order, and an account that lost it should say so.

The empty-window control also asserts the span it got. It had two silent
fallbacks under it — the panel sends a day count when a date field is
empty, and the route falls back to its 90-day default on a bound it
cannot parse, neither a 422 — and both landed on a window that holds the
seeded readings, so the missing-section assertion below was passing on
the fixture's luck.
2026-09-10 03:49:21 +02:00
Marc-André Bombeck 19bee96ad2 test(e2e): prove the report card is closed by the destination, not the level
The delegate spec asserted the absence of the export card inside a
READ-level record and presented that as the UI half of the MANAGE
boundary. It is not. `/settings/gesundheitsakte` is a personal
destination, and the shell answers it with the "not part of shared
access" panel at every adult grant level — read, write and manage
alike — so the same two absences would pass unchanged inside the record
the delegate manages. The assertion could not fail for the reason it
named.

Both arms now open the page. Inside the managed record, where the route
answers 200 for the same request, the card is still absent: that is what
makes the destination the cause. The level-sensitive statement stays
where it belongs, on the route's 403, and the file header now says which
half proves what.
2026-09-10 03:48:47 +02:00
Marc-André Bombeck 33f5bed802 test(e2e): give the doctor-report journey its own account
Generating a report writes: the route remembers the scope and the
practice name on the account row, and the export panel a later visit
opens is therefore the collapsed "repeat run" state. The journey was
generating on the shared fixture account, which is the account
`settings-export.spec.ts` asserts the first-run state against in nine
places — an expanded picker, an empty summary, a disabled button. The
two files run in an unconstrained order under two workers, so the first
symptom was an order-dependent red in CI; against a persistent local
database the flip never cleared and the red was permanent.

The journey now seeds, generates and reads back on `e2e-report-owner`,
with its own cookie jar. The shared account and the whole-record
fixtures also get `report_selection_json` and `last_report_practice_name`
cleared on every seed, which repairs a database an earlier run already
dirtied and keeps a delegate's scope choice from being left on a record
owner's row.

The account's date order is pinned rather than left to the locale, and
its export bucket is purged beside the share-link and login buckets: the
10-per-hour ceiling is shared by every export route, keys on the actor
and outlives a run by an hour, so repeated local runs would otherwise
meet a 429 the spec reports as a missing artefact.
2026-09-10 03:48:37 +02:00
Marc-André Bombeck db8ac95342 test: cover the tile's rate attribute in the unit gate, and correct two notes
`data-latest-rate` is a production attribute whose only reader was the browser
suite, so a change to the rate's shape would have surfaced three minutes and a
whole server away from the gate that should own it. One unit test now renders
the chart over a loaded window and asserts the root carries the last day's
rate.

Two comments were wrong. The card's take / skip buttons do not collapse to
icons at narrow widths — both render their label unconditionally beside the
icon — so only the true half of the reason for addressing them by `data-slot`
survives: the labels are translated copy.

And the Enter press in the wizard's times-of-day helper is not decoration.
The field's overlay input holds what is being typed and hands it to the form
only on Enter or on blur (`src/components/ui/time-field.tsx:175-184`), while
the add button is disabled on an empty draft — so a fill followed straight by
a click waits out the actionability timeout on a button that never enables.
Proven by removing it: the flow died at exactly that click. The line stays,
with the reason written beside it.
2026-09-10 03:45:32 +02:00
Marc-André Bombeck c39bf0d0ed test(e2e): name the tile's disagreement about a skip, and assert both refusals
The dashboard assertion called itself "the assertion that they cannot drift
apart silently" and then pinned 50. They have already drifted. The tile's
denominator is the day's expected slots, which a deliberate skip does not
leave, and its numerator counts only rows carrying a `takenAt`
(`src/lib/analytics/schedule-anchored-compliance.ts:141-164`). The card's
engine — `src/lib/analytics/compliance.ts`, the documented single source of
the percentage — drops a skip from the denominator outright
(`src/lib/analytics/compliance/ledger.ts:43-47`), which the counts nine lines
earlier already assert. One afternoon, two answers. The note now says that,
names which engine is authoritative, and the number stays pinned as what the
server's daily buckets really produce rather than as agreement.

The refusal flow was named for a schedule that does not exist and proved
something else: the 404 comes from the ownership guard, before the body is
read and before any schedule code runs. `expect(refused.data).toBeNull()`
proved nothing either — the error envelope always carries a null `data`. So
the test is renamed for what it does prove, the empty assertion is dropped,
and the case the old title promised is added: a pin onto an instant that is
not one of the medication's slots, refused with the documented 422.
2026-09-10 03:45:20 +02:00
Marc-André Bombeck f544cae9a9 test(e2e): read the card's rate once, and keep the journey inside one day
Two separate ways the flows could not deliver what they promised.

The card read polled for up to seventy seconds and escaped a missing figure by
reloading the page — which re-mounts the list and issues the very batched
compliance call it was waiting out, so each poll spent one more of the
allowance it was short of. Meanwhile the budget is thirty seconds tripled by
`test.slow()`, so one ride-out consumed the whole test and the run died on a
Playwright timeout rather than on the "the card never painted an adherence
figure" message the note promised. The inner poll was also wrapped in a second
one with a thirty-second budget, and `expect.poll` does not abort an in-flight
callback, so a seventy-second call ran to completion inside it.

With the journey on its own account there is nothing to ride out: the read now
waits twenty seconds for the attribute and fails with the diagnosis attached.
The nesting is gone too — the step that waits for the card to re-read its
schedule polls the attribute directly.

The other one is the day boundary. A clock-anchored slot is inside its own
on-time window by construction, so the TAKE is always today's; the dashboard
assertion is not, because it reads the latest day and a day's expected count
carries no now-cap. Cross midnight between the take and the final read and the
latest day is a fresh one with two doses scheduled and none taken, which
answers 0 where 50 is asserted. The flow is a couple of minutes long, so it
declines to start in the last ten minutes of the day and says why.
2026-09-10 03:45:09 +02:00
Marc-André Bombeck d529d5976c test(e2e): move the adherence journey onto its own account
The batched compliance read allows thirty calls a minute per ACTOR, and the
journey spends that allowance twice over: it writes doses and then reads the
resulting rates back off the same cabinet. On the shared account two siblings
spend it as well — `refetch-nav.spec.ts` mounts `/medications` unstubbed and
drives a client-side round trip back to it, and `delegated-writes.spec.ts`
opens `/medications?new=1` on a SECOND session row of the same account, which
is a different session but the same actor and therefore the same bucket. Add a
serial group's retries and thirty reads inside one minute is reachable rather
than theoretical.

The cabinet has the same shape of problem in the other direction: the clear
before each test deletes every medication row of the account it runs on, and
that is today the account every other authenticated spec holds.

So the journey gets its own account and its own jar. The rate-limit bucket,
the medication cabinet and the dashboard tile's denominator become private at
once.

Two fixture repairs ride along, because they are the same helper:

- The clear now goes out as the app's own DELETE per row instead of one raw
  `DELETE FROM medications`. Three fifteen-minute per-user cells hold
  medication state and a raw statement evicts none of them; the file survived
  only because every test happened to write through the API afterwards, which
  is an accident of ordering rather than a property. The rows are still
  enumerated in SQL, because the list route serves a memoised shape and a row
  it has not caught up with would hide from it.

- `ageMedication` takes both stamps from its caller instead of deriving them
  from `CURRENT_DATE`. That resolves in the database session's zone — UTC in
  CI — while the plan dates the spec sends are computed in the browser's
  pinned Europe/Berlin, so between midnight and 02:00 the row silently started
  a day earlier than the caller asked for. The docstring now says `starts_on`
  is overwritten, not adjusted.
2026-09-10 03:44:48 +02:00
Marc-André Bombeck 297395372b Merge pull request #945 from MBombeck/release/v1.38.14
v1.38.14 — the reported bugs at their class, and a gate that stops crying wolf
2026-09-10 03:43:31 +02:00
Marc-André Bombeck 7b06a235e1 test(e2e): cover doctor-report generation end to end
The doctor report had unit coverage for the renderer and route coverage for
the envelope, and nothing that pressed the button. Two browser journeys close
that.

`doctor-report.spec.ts` seeds a few weeks of blood pressure and weight, one
allergy and one medication through the page's own `fetch`, picks a window in
the export panel and generates. The saved download is asserted as a real
artefact — `%PDF` magic, a `Content-Length` that agrees with the bytes, a
length no empty document reaches — and then parsed back to text, so the
period line, the blood-pressure section and the drug list are read out of the
document rather than inferred from a 200. The period is checked as a span, so
the assertion survives the account's timezone. Its refusing control is a
window with no readings: still a valid, readable report that names the period
and carries no blood-pressure section, with the reference data that is not
window-scoped as the control against a blank page passing.

`doctor-report-delegate.spec.ts` covers the access boundary the route draws at
MANAGE. A delegate inside a record it may only read is not offered the export
card at all, and the route refuses the request that card would have sent with
`sharing.access.denied`. The positive control is the same delegate, the same
payload and the same switched-record path against a record it manages, so the
one variable between pass and refusal is the access level. Both requests carry
the record-context headers the shipped client sends: without them the fence
refuses with the same status and the same error code, which would make the
refusal pass for the wrong reason.

Seeding is idempotent — a re-posted reading collides on its natural key and
answers 409 — so a second local run and a repeated run both stay green. The
delegate journey takes its own cookie jar because it moves the session's
record selector, and both specs run in one project.
2026-09-10 03:27:02 +02:00
Marc-André Bombeck fd337a4e7a fix(import): match the molar-mass annotation by the shape Apple writes
The catch-all angle-bracket pattern read as an HTML sanitiser to static analysis. The annotation Apple writes is a number, so the pattern now matches exactly that, and a unit with anything else between the brackets stays unknown instead of being silently trimmed into a lookup.
2026-09-10 03:25:16 +02:00
Marc-André Bombeck 0c46df1413 fix(api): put a ceiling on editing a managed record's identity
`PATCH /api/managed-profiles/{id}` had none, while creating a record and
inviting a Guardian have both been capped at ten an hour since they shipped —
one family answering the same abuse three ways. It matters more here than the
count suggests: `updateManagedProfile` opens a transaction and takes an
advisory lock on the id it was HANDED before it decides the caller is not a
Guardian of it, so an unthrottled caller can name any id and make the database
hold a lock about it.

The refusal now lands before the id is read, on the same bucket convention and
with the same ceiling as creation. The GET beside it stays unlimited, matching
the guardian roster read next to it: both are cheap identity reads a Guardian
may already make. The 429 is documented on the contract and the edit form's
message mapping grew the arm creation already had.
2026-09-10 03:24:50 +02:00
Marc-André Bombeck 3d163d3602 chore(release): v1.38.14 — the reported bugs at their class, and a gate that stops crying wolf
Version anchors, the OpenAPI document and the changelog entry. Refs #943, #944.
2026-09-10 03:05:20 +02:00
Marc-André Bombeck 25ba09e714 Merge the precise off-host deletion note 2026-09-10 02:19:00 +02:00
Marc-André Bombeck 242be8100a Merge the truthful batch unit description and the dry-run count fix 2026-09-10 02:19:00 +02:00
Marc-André Bombeck 92e43ebf67 Merge the synthetic journey's host allowlist and cleanup 2026-09-10 02:18:59 +02:00
Marc-André Bombeck c673255355 fix(settings): stop a timezone edit writing the actor's language into a record
A managed record with no recorded language opens the edit form's language
control on the actor's, which is the same starting point the creation form
uses. The diff then compared that control against the record's NULL column, so
every save of such a record carried `locale` — a guardian correcting only the
timezone silently recorded their own language as the record's, and the audit
row said the language changed.

The comparison is against the value the control opened on, frozen at mount.
Nothing is sent unless somebody moves it.
2026-09-10 01:59:08 +02:00
Marc-André Bombeck 038fc72be2 fix(settings): keep a managed record's edit form across a refetch
The fields component was keyed on the query's `dataUpdatedAt` under a comment
saying the key stopped a refetch landing mid-edit from replacing what somebody
is typing. It did the reverse: the timestamp moves every time the query
resolves, so invalidating the `managed-profiles` prefix from anywhere — the
guardian list on another row is enough — remounted the fields and threw the
half-typed name away.

Keyed on the record's id instead, which is stable for as long as the form is
about the same record.
2026-09-10 01:57:42 +02:00
Marc-André Bombeck 0bae48180a docs(api): say which account payload fields describe the record
The `AccountPayload` description still claimed that under an active switch the
payload describes the caller "their preferences, their modules, their
identity", which stopped being true when the module map and the cycle flag
started answering for the active record — `ModuleMap` on the same spec said
the opposite. The iOS client reads this file.

Both descriptions now say the same thing: identity and preferences are the
caller's, `modules` and `cycleTrackingEnabled` are the active record's, and
both are masked to the sections the active grant opens. Spec regenerated.
2026-09-10 01:57:12 +02:00
Marc-André Bombeck 8ff1b865fc fix(settings): send a managed record's cycle flag only when it moved
The Modules save posted `cycleTrackingEnabled` on every submit, and the route
writes it whenever it is present. An explicit boolean beats the sex-derived
default in the cycle gate, so a guardian turning Labs off for a record created
without a recorded sex wrote cycle OFF as a deliberate answer; setting the
record's sex to FEMALE afterwards then left cycle off with nothing on screen
saying why. It also listed `cycleTrackingEnabled` as changed in the record's
audit trail on every save of any module.

The flag now rides only when it differs from the value the form opened on,
which is what the edit form's `managedProfileEditPatch` already does. The
decision moved into a pure `managedModulesPatch` so a test can see it — what a
form does NOT send is invisible in its markup.
2026-09-10 01:56:17 +02:00
Marc-André Bombeck 0cccb4de99 fix(sharing): keep a scoped grant out of the record's module configuration
Publishing the active record's module map and cycle flag on the account
payload was right for a whole-record grant and too generous for a narrowed
one. `accountAccess.active` is set for any live grant, level and scope
included, so a delegate scoped to `measurements` read whether the owner
tracks their cycle, their screeners, their illness episodes and their
supplement intake, and the cycle flag derives from the owner's recorded sex.

Both fields are now masked to the sections the active grant names: a closed
section answers `false`, which is the answer a module that is off already
gives and the answer the browser's route inventory has always acted on. An
unscoped grant names the whole record and is unaffected, so the own-record
and whole-record payloads are byte-identical to what they were.

The masking table lives beside the sharing vocabulary rather than inside it,
and runs one way only: no value in it can turn a module on, admit a read or
widen a grant.
2026-09-10 01:54:29 +02:00
Marc-André Bombeck 617beb40dc test(e2e): cover the medication-adherence journey end to end
The percentage on a medication card is the number this product is for, and
nothing in the browser suite walked the path that produces it: the wizard
specs stub `/api/medications` and stop at the POST body, and the compliance
engine's own tests are unit tests over pure functions. The join was the part
nobody checked.

Three flows against the seeded account, serial and in one project because
they read counts back off a cabinet they own:

  - a twice-daily medication created through the real wizard, one dose taken
    and one skipped from the card, and the figure read back on the card, in
    the intake history and on the dashboard tile;
  - a dose recorded against a schedule that does not exist, refused, with the
    rate exactly what it was before;
  - a plan due on two weekdays whose other five days stay out of the
    denominator, with a daily twin given the identical doses as the control —
    without it, "100 %" would also be what an engine that counted no days at
    all would say.

The dose times are derived from the clock rather than picked from the
wizard's suggestions: the card offers one dose, so with fixed times there is
always an hour at which that dose belongs to yesterday or tomorrow, and the
day the write lands on decides what the tile reads. Each medication is aged a
few days as well — compliance is reconstructed from the creation stamp
forward, so a medication created a second ago reads the empty-set 100 % and
no take can move it.

Four surfaces gain data attributes so the journey addresses controls and
figures rather than translated copy: the card's take / skip buttons, the
card's two adherence rates, the intake-history row status, and the dashboard
tile's most recent day, which existed only as bar geometry. Presentation is
unchanged; the compliance block's fixed-geometry guard normalises the two new
rate attributes alongside the ones it already did.
2026-09-10 01:46:13 +02:00
Marc-André Bombeck 7f54f339b2 refactor(backup): drop the retention value nothing could ever read
E2. `loadOffhostConfig` parsed BACKUP_RETENTION_DAYS, clamped it to a
minimum of one day and put it on the config object, where no caller read
it. Neither annotation fits: it is not deliberately internal, because
there is no internal use, and no consumer is pending. The design forbids
one outright — the worker's grant excludes DeleteObject on purpose, so
nothing here can act on a retention window without giving a compromised
worker the ability to wipe the history. A clamp that guards nothing only
read as an enforcer the worker is not.

So the field and the clamp go, and the reason sits where the parse was.
The variable keeps its place in the two example files and on the compose
whitelist: it is the number the operator sets the bucket's own lifecycle
rule to. The docs table said "defaults to 30", which implied the app had
an opinion; it now says the app does not read it.
2026-09-10 01:38:40 +02:00
Marc-André Bombeck a4909d3e00 docs(env): say exactly which object the off-host worker deletes
E1. Two halves of one correction. `.env.example` still said backup objects
older than BACKUP_RETENTION_DAYS are pruned, which no code does, so a
self-hoster reading that file alone still expected the worker to keep the
bucket tidy. It now carries the same sentence as the production example.

And that sentence overreached in the other direction: "the worker never
deletes an object" is not true of `_healthcheck/<ts>.bin`, the 1-byte key
the Test-connection button writes and then deletes. The delete swallows
its own failure, so an operator who granted exactly the three documented
actions leaves one orphan per press and is never told. Both files now say
"a BACKUP object", and name the one key and what happens without
DeleteObject on that prefix.
2026-09-10 01:31:17 +02:00
Marc-André Bombeck c3b5585fd6 fix(ops): stop the distance dry run promising work it will refuse
Low, review 2. An account with one out-of-range candidate is refused
whole, rows and audit row included, but the dry run counted its rows into
"N row(s) would be repaired" — so the number an operator read before
--apply was larger than the number --apply could ever produce. The refused
accounts are now counted and reported separately, and the per-account line
says its rows are not in the total.

The refusal itself told the operator to check the Health app "before
forcing anything". There is no --force and never was. It now names the
only route that exists: re-run with the matching --unit if the archive
really was in another one.
2026-09-10 01:30:26 +02:00
Marc-André Bombeck e4333f8f71 docs(api): say which unit the batch route reads a sample in
U1. The new `unit` description on the batch entry said `value` is read in
the unit HealthLog stores the identifier in. Sixteen mappings disagree:
`convertToDbUnit` runs on every entry, and a waist circumference arrives
in metres to be stored in centimetres, an oxygen saturation and a body fat
arrive as a fraction to be stored as a percent. A client generated against
that sentence sends 98 and stores 9800.

The description now says what happens: `value` is read in Apple's own
HKUnit for the identifier, HealthLog applies its storage scaling
afterwards, and `unit` is recorded for audit rather than validated
against. Two worked examples, because the percent-shaped ones are the pair
that bites. YAML regenerated.
2026-09-10 01:29:08 +02:00
Marc-André Bombeck 79cb08efc7 test(ops): prove the journey's redactor on a key-shaped body
Low, review 2. The self-test walked every leg but never once asked whether
the redactor actually holds. The excerpt path is the only thing between a
token in a failure body and the run log, so it gets its own case: a body
carrying this project's own key prefix must come back with the token
replaced.
2026-09-10 01:26:40 +02:00
Marc-André Bombeck 3ba2fe3b82 fix(ops): prove the journey's reading is gone, not just accepted
Low, review 2. The delete leg asserted HTTP 200 and printed "account left
clean". An instance that answers 200 and keeps the row would have printed
the same line, which is the failure mode the journey exists to catch.

The leg now reads the id back and requires a 404. The self-test carries a
mock that answers 200 without deleting; with the read-back removed that
case goes green, which is the proof the check can fail.
2026-09-10 01:26:24 +02:00
Marc-André Bombeck 25cb79ecfc fix(ops): let no failed journey leg leave a reading behind
S2. The legs ran in one loop that returned on the first red one, so a
failed read back never reached the delete and the probe account kept the
row. Worse, the id was assigned only after the write's await returned: a
POST that timed out once the server had already committed left a row the
script could not even name.

Legs 3 to 5 now sit in a try/finally. The finally sweeps whatever the
delete leg did not, and when there is no id it asks the instance for the
row by a marker the write puts in `notes`, unique per run and known before
the request goes out. The sweep never throws — the red leg is the verdict,
and it says out loud what it could not remove.

--self-test asserts the mock holds no rows after every case that got as
far as the write, so a red read that skipped the delete is caught.
2026-09-10 01:26:04 +02:00
Marc-André Bombeck 742eeaad3c fix(ops): refuse a synthetic-journey target that is not ours
S1. The journey signs in with a real account and POSTs that account's
password to whatever BASE_URL names, and the workflow took BASE_URL as
free text. Anyone with repo write, or a leaked token, could dispatch the
run at a collector of their own and keep a working credential; secret
masking guards the log, never the egress.

The host now has to be on a short const allowlist in the script, checked
before anything is sent, with exit 2 and a named refusal otherwise. The
workflow input is a choice between the two hosted instances, so the form
cannot offer a third; the script's own check still stands behind it for a
dispatch that goes round the form.

--self-test covers the refusal, the prefix lookalike a startsWith check
would have waved through included.
2026-09-10 01:25:01 +02:00
Marc-André Bombeck ccca056f64 feat: let the record's module map filter its own navigation
The other half of the switched-payload change, found by the integration
test that asserted the door was gone and got the door. `isNavDestinationVisible`
short-circuited on `sharedRecord`, so a switched session skipped the module
filter entirely and every destination the grant's scope allowed was offered.

That was right while the map was the actor's: a delegate's own preferences
must not hide a domain the record granted. The map is the record's now, so
the objection is gone and the line is what makes a guardian's toggle visible
inside the profile it was set for. Scope decides which doors the grant opens;
the map decides which of them the record uses at all.

The read-only profile summary needs its marker checked against `!sharedRecord`
rather than reached through the removed short-circuit, and the case that
pinned the old reading is turned round with the reason written out.

Refs #939
2026-09-10 01:09:50 +02:00
Marc-André Bombeck bed2ab568e fix(test): read the audit details as the string the writer stores
`auditLog` serialises `details` with `JSON.stringify` into a text column,
so the assertion was reading a field off a string and finding nothing.

Refs #939
2026-09-10 01:09:50 +02:00
Marc-André Bombeck 1ab2e1b524 chore: regenerate the OpenAPI document and list the page-side seed after integration 2026-09-10 01:09:39 +02:00
Marc-André Bombeck 1dc4f70fed Merge the Apple Health import end-to-end journey 2026-09-10 01:09:27 +02:00
Marc-André Bombeck 80bcf75786 Merge the glucose end-to-end journey 2026-09-10 01:07:00 +02:00
Marc-André Bombeck 05e5e0d6c4 Merge the synthetic post-deploy journey 2026-09-10 01:07:00 +02:00
Marc-André Bombeck 7d9532b53c Merge the off-host backup variable documentation 2026-09-10 01:07:00 +02:00
Marc-André Bombeck e06c42d261 Merge the Nightscout connect registration 2026-09-10 01:07:00 +02:00
Marc-André Bombeck 122d57c376 Merge idempotency on the three medication create routes 2026-09-10 01:06:59 +02:00
Marc-André Bombeck 6338da8cf6 Merge the per-field profile rejection surfaces 2026-09-10 01:06:59 +02:00
Marc-André Bombeck f3209f0a93 Merge the release-gate noise removal 2026-09-10 01:06:59 +02:00
Marc-André Bombeck 7036b2d225 Merge the de-flaked end-to-end specs 2026-09-10 01:06:58 +02:00
Marc-André Bombeck 3bd0664edf Merge the untagged glucose bucket across every consumer (#943) 2026-09-10 01:06:58 +02:00
Marc-André Bombeck 071b110e8b Merge the Apple Health record-unit fix and the distance repair (#944) 2026-09-10 01:06:58 +02:00
Marc-André Bombeck 8702d85c9d test(notifications): pin aps.mutable-content on the medication reminder
The client's notification service extension replaces the medication name
on the lock screen, and iOS routes a payload through an extension only
when the alert carries `mutable-content`. The dispatcher has set the flag
on every alert it builds since the category work for the v0.5.4 client,
but the only assertion on it sat inside a category test, where dropping
it would have failed nothing and the name would have quietly reappeared
on the lock screen of a device that asked for it to be hidden.

Two cases now say it out loud: the medication reminder carries the flag,
and so does another event type, because that is the shipped behaviour and
narrowing it would take a capability away from the client rather than
tidy something up.
2026-09-10 01:05:03 +02:00
Marc-André Bombeck 6fe1897941 fix(medications): accept an Idempotency-Key on the three replayed creates
The native client replays its offline outbox with the same
Idempotency-Key on every attempt, and `POST /api/medications`, the
side-effect log and the inventory register ran the handler again on the
replay: after a lost success response the account was left with a
duplicate medication, a duplicate symptom entry or a second pen in the
supply count. The dedupe on `(externalSource, externalId)` only ever
covered a MIRRORED create; a manually entered medication carries
neither field and had nothing to collapse a retry onto.

All three wrap in `withIdempotency`, the composition the batch ingest
already ships, and the three operations publish the header so a client
generated against the contract can tell that a retry is safe. Zod
parsing and `requireRecordAuth` are untouched.

An integration test drives each route twice against real Postgres and
asserts what a status check cannot: one row in the table, and a replayed
201 carrying `X-Idempotent-Replay: true`.
2026-09-10 01:04:57 +02:00
Marc-André Bombeck 8995bef61c feat(ops): synthetic post-deploy journey
Post-publish verify proves the published image boots. Nothing proved that
on a running instance a person can sign in, write a reading and read it
back — which is exactly the shape of the defects this line keeps
rediscovering: a value written and never read.

`scripts/synthetic-journey.mjs` walks that journey in plain Node 22 with no
dependencies, so it runs from a workstation, a runner or the deploy host.
It warms `/`, `/api/health`, `/api/version` and the measurements list first
and discards those timings (the first hit on each route after a deploy is a
cold start), then asserts five legs in order: the served version equals the
expected one, the password flow signs in through a cookie jar, a weight
reading is written with an Idempotency-Key, the same row reads back with
its value, unit and source, and the reversible delete leaves the account
clean. One line per leg with the elapsed time; the first failure ends the
run non-zero with the status and a body excerpt that has every token shape
redacted out of it.

The workflow is `workflow_dispatch` only, with `base_url` and
`expected_version` as inputs and the credentials read from repository
secrets. It is deliberately not wired into the deploy path: the target
instance and the secrets are the maintainer's call.

Mutation proof, against a production build served from
`.next/standalone/server.js` on a throwaway Postgres.

Green:

    warm      35 ms  (discarded)
    ok        version         2 ms  serves 1.38.13
    ok        sign in        78 ms  session cookie held
    ok        write          64 ms  wrote cmtup9lwu0007zhovn0mxajdz
    ok        read back       8 ms  77.7 kg (MANUAL)
    ok        delete         27 ms  account left clean

    synthetic journey green

Read leg broken deliberately — the same server behind a throwaway forwarder
that empties the `GET /api/measurements` list and changes nothing else:

    ok        version         4 ms  serves 1.38.13
    ok        sign in        38 ms  session cookie held
    ok        write          40 ms  wrote cmtupa4ck000gzhovwnij64fz
    FAILED    read back       8 ms  read back: the list came back without the reading
              status 200
              body   {"data":{"measurements":[],"meta":{"total":0}},"error":null}

    synthetic journey RED on "read back"

Version leg broken the same way, by asking the instance for the previous
tag:

    FAILED    version         3 ms  version: instance serves "1.38.13", expected "v1.38.12"

    synthetic journey RED on "version"

`--self-test` carries that proof in the repository: it runs the journey
against an in-process instance nine times, once with nothing broken and
once per broken leg, and fails if a broken leg still comes back green. The
workflow runs it before it touches the real instance.

Gates: typecheck, `node --check`, lint (the three known warnings, no
errors), prettier, the workflow and CI-determinism guards.
2026-09-10 01:04:30 +02:00
Marc-André Bombeck 1de3681c81 test(e2e): cover the blood-glucose journey across a unit switch
The glucose display unit had thirty-odd readers and, until recently, no
control to set it. Nothing in the browser suite walks the path a person
actually takes: capture a reading in mg/dL, switch the account to mmol/L,
capture a second one, and read both back — each converted, none of them
reinterpreted — in the list and on the dashboard strip.

The journey covers that end to end, plus the boundary: a value past the
plausible ceiling is refused by the server, the capture keeps what was typed,
and the list is exactly what it was.

One reading arrives with no meal-time context, the way a meter export or a
device sync delivers one. It reads back correctly in the list; the tile it
should paint does not exist yet (#943), so the tile assertion is skipped by
issue number rather than softened into something that passes.

Three supporting changes:

- The list rows carry what they hold — type and resolved display unit on the
  row, a slot on the value cell — so the journey pins "this reading now reads
  in mmol/L" structurally instead of matching translated copy that also paints
  through a different subtree on the card list. The meal-time options carry
  their enum for the same reason.
- The sharing-marker weight rows were seeded by handing a Date to a
  `timestamp without time zone` column, which stamps them in the host's zone.
  On a machine east of UTC that put them hours in the future, where every fold
  whose window ends "now" skips them, and the type stayed uncovered — which
  keeps the snapshot's thick phase cold and the whole tile strip short. Seed
  the instant as UTC, the shape the app's own writes use.
- The file mutates one shared account and reads global verdicts off it, so it
  runs in a single project alongside the visits and immunization journeys.
2026-09-10 01:01:11 +02:00
Marc-André Bombeck 2c740f04ac test(e2e): cover the Apple Health export import end to end
Upload a synthetic export.zip on the import card, wait out the queued
job through the card's own status poll, and read the imported readings
back off the measurements list with the units the parser resolved.
Weight, the blood-pressure pair and the step count are asserted; the
walking-distance case is written and skipped, naming issue #944 — a
record written in km lands as metres today, and the assertion is kept
at full strength so the fix has something to turn green.

The refusing control uploads a valid ZIP with no export.xml: the card
surfaces the extractor's own refusal and the account's Apple Health row
count does not move.

Measurement rows now carry data-measurement-type / -value / -unit
beside the rendered cell, on both the desktop table and the mobile
list, so an assertion binds to the reading rather than to whatever the
locale formatter made of it. The import card's error line gets a test
id for the same reason.
2026-09-10 00:58:12 +02:00
Marc-André Bombeck 8ad5b90f88 docs(ops): the off-host worker never prunes; the bucket lifecycle does
The runbook said the worker prunes objects older than BACKUP_RETENTION_DAYS. It never calls DeleteObject; its grant is PutObject, GetObject and AbortMultipartUpload, on purpose, so a compromised worker cannot wipe the history. The sentence now says what expires objects and what the variable is for.
2026-09-10 00:48:31 +02:00
Marc-André Bombeck 91ae90836b docs(env): document the two optional off-host backup variables
BACKUP_S3_REGION and BACKUP_RETENTION_DAYS are both on the compose whitelist and
both read by the backup job, but the example file listed neither — so an
operator following it had no way to learn that the region defaults to auto, or
that the retention number is what the bucket's own lifecycle rule has to be set
to, since the worker never deletes an object itself.
2026-09-10 00:47:16 +02:00
Marc-André Bombeck eea0f2a532 Clear a refused profile field as it is edited
The settings profile form painted the server's refusal under the input
and left it there until the next save, so a value the person had already
corrected still read as refused. The onboarding baseline step drops that
sentence while they type; the account card now does the same.

Only the edited field's slot goes: the other fields the same save
refused were not touched, so their sentences still stand. The guard
derives both sets from the form itself, so a new rejection slot without
a clear fails.

Review finding L3.
2026-09-10 00:42:45 +02:00
Marc-André Bombeck 779cd3a0c8 test: ban a length rescale, not every literal thousand
The guard read `* 1000` anywhere in the two mapping files as a
re-implemented kilometre factor. Both files also turn seconds into
milliseconds, so an unrelated conversion would have failed it for the
wrong reason and the next person would have deleted the rule.

A rescale now counts only in a length context: a distance identifier on
the same line or within the five above it, which covers the body of a
distance-named helper. The offending line is named in the failure. The
matcher's limit is written next to it — a length conversion in a helper
named nothing like a distance, more than five lines below its signature,
still slips through.

Checked both ways against the real file: a millisecond conversion passes,
a `km * 1000` helper fails.

Review finding L4.
2026-09-10 00:37:22 +02:00
Marc-André Bombeck 610083aa4d fix(ops): stop the distance repair losing its rollup tail in silence
The rollups and the cached status insights are recomputed after the
transaction, so a throw there left the rows repaired and every chart on
the pre-repair numbers — and no later run would notice, because the
audit row makes the account skip from then on.

The tail is wrapped now. The audit row is written with
`rollupsRefreshed: false` and only flipped once the recompute returned,
so a re-run can tell "repaired, rollups pending" from "done" and says so.
A run that could not finish the tail names the account, prints the
backfill to re-run — `scripts/backfill-rollups.ts --user <userId>` — and
exits non-zero.

Review finding M2.
2026-09-10 00:37:15 +02:00
Marc-André Bombeck cd9b6450d5 docs(api): publish POST /api/nightscout/connect
The route was exempt from the published contract as a browser handoff. It
is not one: Nightscout has no OAuth step and no authorise page, and the
route is an authenticated JSON POST that Zod-parses a URL and an optional
token, probes the instance and encrypts the pair onto the row. It was the
only POST among eight `connect` exemptions, and its three siblings —
status, test, disconnect — have been published all along, so a client
could read every part of the Nightscout flow except the one that starts
it.

Register it from `nightscoutConnectSchema` so the request shape stays
single-source, document the 400 / 413 / 422 / 429 arms the handler
actually answers with, and drop the exemption. Removing the registration
now fails the coverage guard by name.
2026-09-10 00:36:31 +02:00
Marc-André Bombeck 69e4ba7b8a docs(ops): name the backup precondition on the distance repair
An in-place multiplier with no reverse operation was documented with only
a dry run in front of it. Point at the backup runbook where the write
happens.

Review finding M1.
2026-09-10 00:27:54 +02:00
Marc-André Bombeck 361e577864 fix(ops): refuse an account whose rows are not the thousandfold class
The provenance criterion proves where a row came from, not which build
imported it. An account re-imported on the fixed build carries the same
`EXPORT_XML_SOURCE_MAX` stamp and the same `stats:` external id with the
right numbers and no audit row, so it is selected exactly like a broken
one — and its rest days, under 200 m because the phone stayed at home,
survive the plausibility check after another thousandfold multiply.

So one candidate row that would leave the range now refuses the whole
account: nothing written, no audit row, the offending rows and a printed
reason instead. The idempotency guard only ever held against the
script's own prior run; this holds against the case it could not see.

The runbook says the same in words — a re-imported account must not be
repaired, the re-import already did it — and says what the dry run is
for: it is where the decision is made, not a formality in front of one
already taken.

Integration coverage for the re-imported account: correct rows, an
`--apply` run, nothing changes and no audit row is left behind.

Review finding H1.
2026-09-10 00:27:43 +02:00
Marc-André Bombeck 65e9ecbde6 fix(ingest): keep the batch sample's unit captured, not authoritative
The record-unit conversion is now opt-in per caller and only the
`export.xml` archive path opts in. There the attribute is authoritative:
Apple stamps every quantity `<Record>` with the account's own display
unit, so `km` means kilometres and the reading is meaningless without it.

`POST /api/measurements/batch` keeps its documented contract — `unit` is
captured for audit and never read. Nothing in the tree pins the native
client's unit strings for the seventeen convertible identifiers, and a
client that reads a sample in metres while stamping the person's display
unit into the field would have had every walking distance multiplied by a
thousand on ingest. Reading the field there is a wire change and needs
the client's strings pinned first.

The mapping-table audit and the shared conversion module stay. The batch
path's identity behaviour is written down where it is decided and pinned
twice: every convertible identifier round-trips a sibling unit unchanged
by default, and a walking-distance entry sent as `km` is stored as it
arrived. The OpenAPI description says what the server actually does.

Review finding H2.
2026-09-10 00:24:59 +02:00
Marc-André Bombeck de7c89a462 ci: keep the dependency audit visible on pull requests without blocking them
The audit had moved off the pull_request trigger entirely, which left a window in which a tag could be cut from a merge the audit had not seen. It runs on pull requests again as an advisory job (continue-on-error), stays blocking on the push run for main and on the daily schedule, and a tag is only ever cut from a green push run.
2026-09-10 00:20:30 +02:00
Marc-André Bombeck 90ca2cd899 chore(api): regenerate the OpenAPI contract
Picks up the managed-profile read and edit endpoints, the sex field on the
create body, the record-scoped module map on the account payload, and the
delegated cycle field on the record's module settings.

Refs #939
2026-09-10 00:02:15 +02:00
Marc-André Bombeck fb1cb4e3ed feat: gate a switched browser on the record's modules, not the actor's
Turning a module off for a profile you look after wrote a column nothing
on screen was reading. GET /api/auth/me published the ACTOR's module map
while switched, and the navigation, the dashboard tiles and the insights
sections all gate on it — so a guardian who turned Cycle off for the child
kept seeing a Cycle destination inside the child's record, and a guardian
who tracks it saw one there whether or not the child did (#939).

The map and the resolved cycle flag now answer for the record the session
is inside. They are not display preferences: every surface they gate shows
the record's data, so the record is what decides. Locale, theme and layout
stay the actor's. The record is taken from the grant-validated active
entry rather than the session's own selector, so a revoked switch cannot
publish somebody's configuration, and with no switch the payload is what
it was.

Cycle also gets a row on the guardian's Modules surface, which it never
had. It is a delegated module, so its state is the record's own cycle
profile and modulePreferences.cycle is refused — which left a guardian no
way to turn it off for a record whose sex says it should be on. The family
names the real column instead of a blob entry the gate ignores.

Refs #939
2026-09-10 00:02:03 +02:00
Marc-André Bombeck f521b03c35 feat: let a guardian edit a managed record, and record its sex
A managed profile could be created and deleted and never changed. A name
typed as a placeholder was permanent, a household that moved kept the
timezone the record was created in, and there was no way to correct a date
of birth somebody finally had (#939).

PATCH /api/managed-profiles/{id} takes the fields creation takes, every
one optional and at least one required — an empty body is a refusal rather
than a save that audits a change nobody made. It carries the gate the rest
of the family carries: a cookie session with a fresh second factor, an
active Guardian grant on the record, and the same byte-identical 404 for
"no such record" and "not yours". A GET beside it answers the record as it
stands, because the account payload names a managed record and nothing
else, and a form filled from that would have had blank fields to send.

The new field is gender. Leaving it out of v1.37.0 meant every managed
record started with the column NULL, which is what the cycle module
derives its default from: a guardian creating a record for a child could
neither record the answer nor turn the module off from there. It reuses
the column and the three values every other surface writes, so there is
one word for one column rather than two.

Refs #939
2026-09-10 00:01:50 +02:00
Marc-André Bombeck 4c858e7600 Read the height-surface guard across a split form
The onboarding step keeps the preference and the adapter where the
save happens and renders the control from its inputs file, so the
three conditions belong to the surface, not to one file. The control
check is word-bounded now: a wrapper named after it passed a substring
check while rendering something else.
2026-09-09 23:29:00 +02:00
Marc-André Bombeck a0f80eac8c Freeze the set of profile submitters that must read the answer
A partial save is a whole-class trap: any 200 read as a clean save
throws the person's correction away. The guard enumerates every
surface writing to either profile route and requires each to call the
per-field describer, or to prove its body carries a single field, for
which the partial arm is unreachable.
2026-09-09 23:23:22 +02:00
Marc-André Bombeck e74987e819 Give the settings profile form the same per-field rejection slots
It shares the route and had the same gap: the banner named the first
refused field and nothing marked the input that held the value. Each
of the seven submitted fields now carries the reason in its own slot,
through the same component the onboarding step uses.
2026-09-09 23:22:14 +02:00
Marc-André Bombeck 36cbf48286 Show a refused profile field under the input it belongs to
The onboarding baseline step flashed a toast naming one refused field
and walked on to the done screen, stamping the account as set up over
a value the server never stored. The value the person typed was gone
with the step.

A refused field now writes its reason into that field's own error
slot, marks the control invalid, and holds the step until the person
corrects it. Every refused field is named, not only the first, and the
reason comes from the validator code rather than the validator's own
prose, in all seven shipped languages.
2026-09-09 23:21:21 +02:00
Marc-André Bombeck ae20ee3d9d Split the onboarding baseline inputs into their own component
The step's profile fieldset moves to `baseline-fields.tsx` unchanged.
The markup can now be rendered against a server answer on its own,
which is where the next commit puts a test.
2026-09-09 23:16:50 +02:00
Marc-André Bombeck ad62ab6f27 test: guard tile eligibility against a missing null arm
The defect was invisible from the outside because every behavioural test in
the suite seeded a tagged reading. Two checks close that:

A structural guard that reads the dashboard surfaces and fails when a tile
derives presence from a list of enum buckets with no null / unknown arm and
no written reason, following one hop through a named constant. It carries
its own positive and negative controls, so a refactor that silently stops
matching anything fails here rather than going quiet.

An integration test that seeds twenty readings with a genuinely NULL context
against a real Postgres and reads the tile back through the same resolver
the page renders with: eligible, latest value intact, and a tagged reading
still filed under its own context.

Refs #943
2026-09-09 23:03:38 +02:00
Marc-André Bombeck 126383b352 fix(doctor-report): keep untagged glucose readings in the panel
Both report paths dropped them: the raw path iterated the named contexts,
and the dense path skipped any row without a context outright, so a report
built for a meter that records no meal time carried an empty glucose panel
while the readings sat in the database. The FHIR export dropped them for
the third time, at the LOINC lookup — its own comment already said an
unspecified reading codes as 2339-0, but the table had no entry to hit.

The insights context breakdown names the bucket, and the Coach's glucose
block now resolves through the shared helper rather than its own copy.

Refs #943
2026-09-09 23:03:32 +02:00
Marc-André Bombeck 971c922a14 fix(targets): give untagged glucose readings a target card
`buildGlucoseTargets` had the same gap as the dashboard tile: it iterated
the four named contexts, so an account whose readings carry no meal time
got no glucose target at all. Route the loop through the shared grouper.

The untagged card is judged against the RANDOM band and is not editable —
one threshold, one editor row — so the cog renders disabled the way it does
for a derived card. The insights reference panel lists the new target type,
otherwise such an account sees no band on the blood-glucose sub-page.

Refs #943
2026-09-09 23:03:32 +02:00
Marc-André Bombeck 5ab7a2ca81 fix(dashboard): paint the blood-glucose tile for untagged readings
Tile eligibility filtered the four named contexts against the per-context
summaries and asked whether any of them held readings. An account whose
source records no meal time matched none of them, so the tile was omitted
with the module on, the layout toggle on, and a reading from today. Nothing
warned; the strip was simply short one card.

Move the gate out of the page into `resolveGlucoseTiles`, which walks the
shared bucket list — untagged included — and hand the caller the label key
with the summary. Both summary producers group through the shared resolver,
so `UNSPECIFIED` reaches the wire with its own count, latest value and
trend, and a tagged account still gets its per-context breakdown.

Refs #943
2026-09-09 23:03:21 +02:00
Marc-André Bombeck 9a2b1f0955 feat(glucose): name the bucket for readings with no meal-time context
`glucose_context` is nullable, but every surface that fanned out over the
four enum members treated the named list as exhaustive. A meter synced
through Apple Health writes no HealthKit meal-time metadata at all, so an
account can hold nothing but rows the list cannot match.

Add one shared notion of the untagged bucket — the name the Coach's glucose
block already used — with a resolver that files NULL, blank and unrecognised
values under it, and a grouper that walks the named contexts first and the
untagged bucket last. The untagged bucket borrows the RANDOM threshold: an
untagged reading is a spot reading, and a fifth threshold would give the user
a second editor row judging the same readings by a different number.

Labels in all seven locales.

Refs #943
2026-09-09 23:03:13 +02:00
Marc-André Bombeck 2b3c01738e test(fence): switch the record over the page's own connection
FENCE-AC-07 drove its external switch through the browser context's API
request context, which shares one process-wide keep-alive agent with every
other API context in the runner. A POST there can be handed a connection the
server has already closed on its five-second idle timeout, and a POST is never
replayed on a fresh one — twice this line ended the spec with
`read ECONNRESET`, on all three attempts.

The switch is sent with the page's own `fetch`. It stays external in the sense
the case needs: the switch UI is what runs the cache wipe and a bare `fetch` is
not it, and the service worker returns without touching any non-GET, so the
request reaches the network unaltered. The positive control below still proves
the cached entry survived.
2026-09-09 23:03:05 +02:00
Marc-André Bombeck 0bf54b48eb test(vaccinations): seed the a11y dose over the page's own connection
The scan's fixture was written with a Playwright API context. Every API context
in a runner shares one process-wide keep-alive agent, so a request can be handed
a socket the server has already closed on its five-second idle timeout, and a
POST — unlike a GET — is never replayed on a fresh one. That is what ended this
spec twice, on this line, on all three attempts each time: `socket hang up` and
`read ECONNRESET`.

The dose is written from the page instead. The browser opens its own connection,
the service worker is blocked in this project, and the row still goes through the
real route, so nothing about the fixture changes except which socket carries it.
2026-09-09 23:02:59 +02:00
Marc-André Bombeck 99991cd4f3 test(documents): wait for the vault to book the Coach hand-off
The maximize case clicked the drawer's maximize control as soon as the drawer
was on screen. Those are not the same event: the vault records `?doc=` as the
way back only once the detail sheet has actually closed with the drawer owning
the same document, and maximizing before that sends the close down the other
branch, which calls `history.back()` and races the push to `/coach`. The URL
then stays on `/documents` and nothing is raised. The sheet's own close control
leaves the tree with the sheet, so its absence is that hand-off, observed.

The delete case is addressed to the toast's attributes rather than its copy.
The literal there has already been wrong once — a trailing full stop moved and
the assertion spent its whole timeout hunting a sentence that no longer
existed, on every attempt, on both projects.
2026-09-09 23:02:53 +02:00
Marc-André Bombeck cee6c70638 test(a11y): gate the metric scans on the chart's own slot
The two metric sub-page cases waited for `.recharts-wrapper`, a class the
charting library writes and every chart on the page carries, so the gate was
satisfied by whichever chart rendered first rather than by the one the route
exists to show. On `/insights/mood` that is exactly what happened: the mock
carried a single mood entry on a fixed date, the chart withholds its line below
three distinct days, and the sparse placeholder painted while some other chart
answered the gate. The mood line was never waited for and may never have been
scanned.

Both charts now carry `data-slot="chart-plot"` on the wrapper their data branch
renders — an empty window still paints the empty state and the scan still waits
— and the mood fixture is anchored on now with ten daily scores, the same way
the measurement rows above it are.
2026-09-09 23:02:46 +02:00
Marc-André Bombeck 7ca69ec671 test(integration): stop the rate-limit reset test racing its own window
The window-reset test burned its budget in a 50 ms window: four sequential
round-trips to a containerised Postgres had to finish inside a twentieth of a
second or the window closed under them, the counter reset, and the fourth call
came back allowed. Three failures in thirty days, two of them on `main` — run
33614804032 shows `expected true to be false` at rate-limit.test.ts:56 in a file
that took 1278 ms to run.

The short window bought nothing: the expiry this test is about is forced by hand
a few lines further down, by writing `reset_at` into the past. The burn now runs
in a 60 s window, so no round-trip can outlast it, and the test asserts the row's
count is 4 after the denial — a window that closed mid-burn would also have
produced three allowed calls, and the old assertion could not tell the two
apart.

Gates:

  pnpm exec vitest run --config vitest.integration.config.mts \
    tests/integration/rate-limit.test.ts

  three consecutive runs, 2 passed / 2 passed / 2 passed.

  Mutation: with the burn window back at 1 ms the run fails exactly as CI did —
  "AssertionError: expected true to be false" on the denial assertion.
2026-09-09 22:55:53 +02:00
Marc-André Bombeck 69aac232b4 build: budget the routes on measured drift, not on a ceiling they touch
Three of the four watched routes sat within a kilobyte of their ceiling —
444 of 445, 459 of 460, 459 of 460 — because the numbers had been re-stated
for four releases and never re-based. A budget a route is already touching
does not measure the route; it measures whichever dependency bump landed that
week. e2e run 34043772954 failed on `/insights/page: 445 KB gz exceeds the
445 KB budget` with nothing in the diff that touched the bundle, and it was one
of at least four e2e failures that were the budget gate rather than a test.

The file states the measured value per route now, plus one drift allowance over
it, and a route fails on the delta. Measured on a local build at d48bbff01:
/ 447, /insights 434, /measurements 433, /insights/mood 447, allowance 20 KB, so
the effective ceilings are 467 / 454 / 453 / 467 — a raise for all four. The
allowance covers the runner delta and ordinary week-to-week drift; the step
change the gate exists for, a statically imported catalog or a duplicated chart
library, is several times larger and still fails. Every run prints the delta, so
a route that has crept most of the way through its allowance is legible in the
log long before it is red. The reason and the re-base instructions are written
into the file's running note, as with every raise before it.

A budget file with no baselines used to gate nothing quietly, since the loop
had nothing to walk; it now refuses.

Gates, against the current build:

  real baselines                 passed; /page +0.3, /insights +0.3,
                                 /measurements +0.2, /insights/mood +0.3 KB
  /page baseline 425 (cap 445),  FAILED: "/page: 447 KB gz is 21.6 KB over the
  /insights 413 (cap 433)        425 KB baseline, past the 20 KB drift
                                 allowance (cap 445 KB)" and the same for
                                 /insights/page, exit 1
  routeBaselineKbGz removed      exit 2, "states no routeBaselineKbGz entries,
                                 so no route is gated"
2026-09-09 22:48:16 +02:00
Marc-André Bombeck 626a95ff33 ci: give every job that runs the unit suite a browser
The hero-geometry check stopped skipping under CI in v1.38 and started failing
instead, which was the point: it had caught its own launch failure and passed
for months, measuring nothing. The install step went into the quality job of
`security.yml` and nowhere else, and a second job runs the same suite — the
auto-merge job for dependency bumps. Every Dependabot pull request has failed
since on `browserType.launch: Executable doesn't exist`, four of them on
2026-09-06 alone (run 34043840314), on an error that says nothing about the
bump. One workflow was fixed; the class was not.

That job installs the same headless shell now, off the same cache key. The
error the check throws names both jobs rather than sending a reader to the
workflow that was already correct, and a guard sweeps the workflow directory so
a third job cannot run the suite with no browser anywhere in it. Its limit is
written down: the sweep is file-scoped, so a workflow with two jobs where only
one installs still satisfies it.

Gates:

  CI=1, browser path hidden      exit=1, "This check is the gate in CI and it
                                 has no browser to measure with"
  CI=1, browser present          exit=0, 4 tests passed (it measures)
  install step deleted from the  guard fails: ["dependabot-auto-merge.yml"]
  auto-merge workflow
2026-09-09 22:47:31 +02:00
Marc-André Bombeck e031e2211c fix(import): honour the energy unit an archived workout carries
`totalEnergyBurned` rides the same account-display-unit contract as the
distance beside it: a Health app set to kilojoules writes `kJ`, and the
column is kilocalories. Convert it through the shared table.

Refs #944
2026-09-09 22:47:05 +02:00
Marc-André Bombeck bdfff04975 docs(api): say what the batch ingest does with a sample's unit
The field carried no description while the server ignored it. It no
longer ignores it, so the contract has to say so.

Refs #944
2026-09-09 22:45:17 +02:00
Marc-André Bombeck bc7eff8322 feat(ops): repair walking distances stored a thousand times too small
The unit fix only helps the next import. An account that imported an
archive before it carries a decade of days understated 1000x, and the
authoritative repair — re-importing the archive on the fixed build —
needs an archive the account may no longer have.

`scripts/repair-apple-health-distance.ts` is dry-run by default and
selects rows only by the stamp the archive fold itself writes: the
EXPORT_XML_SOURCE_MAX provenance plus the `stats:` external id minted
for that fold. Never by "the value looks small", so a row a native sync
has since overwritten is left alone. `--apply` multiplies one account
per transaction and writes the audit row in the same transaction, which
is what makes a second run a no-op. The archive's own unit is named by
the operator (`--unit=mi`) because the discarded attribute is the defect
itself, and a row whose repaired value would leave the plausible range
is reported rather than written.

Refs #944
2026-09-09 22:45:13 +02:00
Marc-André Bombeck d48bbff01d ci: take the dependency audit off pull requests
`pnpm audit --prod` answers a question about the published advisory database,
not about the diff. The same lockfile passes on Monday and fails on Tuesday
because someone else published, and the branch that turns red changed nothing:
seventeen of the forty-one Security & Quality failures in the last thirty days
were advisory publications on branches that touched no dependency
(GHSA-jqff-g426-hqxp, GHSA-fph4-wmhf-6fwf, GHSA-f65p-4m7j-42xc and
GHSA-5jgf-p345-68v8 in one run alone). A gate that fails for a reason the author
cannot act on is a gate people re-run instead of read.

It keeps running on every push to `main` and once a day on a new schedule
trigger, which is the cadence the question actually has. The other three jobs
sit out the scheduled run. Nothing about what ships is loosened: the container
scan still builds and scans the image on every push to `main`, and the daily
Trivy workflow still scans the lockfile with dev dependencies included and the
published image.

Gate — the trigger set, read back from the parsed workflow:

  triggers: push, pull_request, schedule
  quality          | if: github.event_name != 'schedule'
  dependency-audit | if: github.event_name != 'pull_request'
  secret-scan      | if: github.event_name != 'schedule'
  docker-security  | if: github.event_name == 'push' && github.ref == 'refs/heads/main'
2026-09-09 22:42:54 +02:00
Marc-André Bombeck 59108e09fa fix(test): stop the score suites from talking to a real database
The three score engines' unit tests hand `persist*Score` a fake Prisma, but
`upsertScoreRow` routes the written row through `afterMeasurementMutation`,
which reads the `@/lib/db` singleton instead of the injected client. Both legs
of that tail therefore opened a socket to a Postgres the unit job does not run:
on CI the attempt failed with ECONNREFUSED a few hundred milliseconds later and
logged on the way out, after the test that started it had ended. A console write
that lands while the worker is closing its RPC channel fails the whole run with
`EnvironmentTeardownError: Closing rpc while "onUserConsoleLog" was pending` —
four of nine unit-suite failures in thirty days, every one of them with all
tests green, blamed on whichever score file the worker happened to be tearing
down. Run 31961548185 carries the full stack: recomputeBucketsForMeasurement <-
afterMeasurementMutation <- upsertScoreRow <- persistStressScore <-
stress-score.test.ts:105.

It stayed invisible on a maintainer's machine because a local Postgres answers
on 5432: the same call succeeded quietly, and the suite was writing rollup rows
for its fixture users into a real database.

The four files that drive `upsertScoreRow` stub the tail. That removes the
doomed I/O rather than the log line, and the call they were making by accident
is now asserted in score-row.test.ts instead: the v1.37.19 wiring is pinned by
an expectation rather than by a stack trace. Verified by mutation — dropping the
`afterMeasurementMutation` call from score-row.ts fails the new assertion.

The settle guard's sweep is widened while here. Its eight-line handler window
and five-line registration preamble were both measured against the sites that
existed when it was written and both cut through real code: the console write in
mood-rollups.ts sits nine lines into its handler, so the one genuinely
unregistered detached promise in the tree was never seen, and the registration in
fire-and-forget.ts sits below its handler, so a correct site read as a violation.
Registration is now looked for wherever it wraps the statement, by paren depth
rather than by line count, and mood-rollups.ts registers its WEEK/MONTH/YEAR
enqueue. Verified by mutation: unwrapping that call fails the guard.

Gate: the four files, twenty consecutive runs, 20/20 green (53 tests each).
Test time across the three engine files falls from 708 ms to 20 ms — the
round-trips that are no longer made.
2026-09-09 22:39:39 +02:00
Marc-André Bombeck 5c7c7afd59 fix(import): honour the unit an Apple Health record carries
Apple stamps every quantity `<Record>` of an export archive with the
account's own display unit, not the unit the mapping table assumes: a
metric archive reports walking distance in km, an imperial one in mi,
body mass in lb, energy in kJ, temperature in degF. The mapper accepted
`input.unit` and never read it, so a 2.484 km day was folded into the
day's total as 2.484 m and a decade of imported history read as a couple
of metres walked.

`hk-units.ts` is now the one place a HealthKit unit is converted, shared
by the record path and the workout path (which carried its own km/mi
branch — the duplicate is what let the record path stay wrong). It
converts only inside a family and only for units Apple can emit, and
returns the reading untouched for anything it cannot place, so an
archive that already speaks the table's unit is unchanged.

Every mapping-table entry whose unit cannot be converted — a
dimensionless count, a pinned event, a logarithmic dB level, a compound
rate, the percent units whose value rides as a 0..1 fraction — now
carries a written reason, and a structural guard fails on an entry that
offers neither a convertible unit nor a reason.

Refs #944
2026-09-09 22:31:31 +02:00
Marc-André Bombeck 704ef11eab test: pin the km-scale walking distance the export import stores as metres
The Apple export writes DistanceWalkingRunning in the account's own
length unit; the record mapping assumes metres and never reads the
attribute, so a 2.484 km day lands as 2.484 m.

Refs #944
2026-09-09 22:21:05 +02:00
Marc-André Bombeck 1d372df3a0 Merge pull request #942 from MBombeck/fix/managed-record-capabilities
v1.38.13 — a guardian sees the controls the routes accept
2026-09-09 22:03:41 +02:00
Marc-André Bombeck 8a3499d0f9 chore(release): add the v1.38.13 changelog entry
The release commit carried the version anchors and the OpenAPI document but not the changelog entry; it is added here.
2026-09-09 21:38:42 +02:00
Marc-André Bombeck 40b9427259 chore(deps): let the newer hono and js-yaml bounds win
pnpm-workspace.yaml carried two overrides for the same packages: an older floor (hono < 4.12.25, js-yaml >= 4.0.0 < 4.3.1) and the newer one added for the scanner findings. The older selector won the resolution, so the lockfile kept hono 4.13.3 and js-yaml 4.3.1 and four of the seventeen findings stayed open after v1.38.12. The stale bounds are gone; the lockfile now resolves hono 4.13.7 and js-yaml 4.3.2.
2026-09-09 21:38:16 +02:00
Marc-André Bombeck d464a3efe4 Merge remote-tracking branch 'origin/main' into fix/managed-record-capabilities
# Conflicts:
#	public/sw.js
2026-09-09 21:38:11 +02:00
Marc-André Bombeck 3f67a78952 Merge pull request #941 from MBombeck/ci/trivy-install
Install Trivy from its release, not through apt
2026-09-09 20:58:38 +02:00
Marc-André Bombeck 915bd63a4a chore(release): v1.38.13 — a guardian sees the controls the routes accept
Version anchors, the OpenAPI document and the changelog entry. Reported in #939.
2026-09-09 20:55:06 +02:00
Marc-André Bombeck 386e92e6f9 test(sharing): carry the two domain lists through the account-access contract
The account-access integration contract compares whole entries, so the
two lists the payload now publishes belong in its expected shapes. The
managed-record leg posts the mood entry with the logged-at instant the
create schema requires.
2026-09-09 20:06:48 +02:00
Marc-André Bombeck 77eaf22c0c ci: install Trivy from its release, not through apt
The scanner job installed Trivy through apt, which runs `apt-get update`
across every repository on the runner image. On the v1.38.12 merge
commit the runner's preinstalled Chrome repository answered with a
corrupt index ("Hash Sum mismatch") twice in a row, and the release gate
went red on a step that has nothing to do with the image under test.

The step now fetches the pinned release binary through Trivy's own
installer, which downloads the tarball for that exact version and checks
it against the published checksums. No apt, so no unrelated repository
can fail the job.
2026-09-09 20:04:13 +02:00
Marc-André Bombeck 4b3e71570c test(sharing): drive the managed-record capabilities over the routes and the browser
The integration leg reads GET /api/auth/me as a guardian acting on a
managed profile and asserts both lists, lands a mood entry and an
allergy on the profile's record, is refused a vault write, and shows a
WRITE delegate writable sections without manageable ones together with
the refused mood entry the list withheld.

The browser leg opens the managed profile, adds a mood entry through
the control that used to be hidden and asserts the POST's status, and
finds the owner-only sentence and no upload control on the documents
page. The spec gets its own session jar and runs in the desktop
project only, like every other spec that moves the record selector.
2026-09-09 19:42:27 +02:00
Marc-André Bombeck e95612e3d3 fix(sharing): show a guardian the controls the routes accept (#939)
useRecordCapabilities answers per section now. canWriteDomain and
canManageDomain read the two lists the account payload publishes; in
one's own record they are always true, and under a refused, pending or
unproven context always false. canManage becomes the coarse switch,
true when any section is manageable, and is what the banner and the
navigation read.

Every add, edit and delete control names its own section: labs, mind,
profile, illness, cycle, medications, measurements, documents. Creates
that a WRITE route answers (visits, practitioners) ask canWriteDomain.
The generic delete button, the selection bar, the capture picker, the
dashboard quick entry and the bottom nav take the section from their
callers. Controls whose routes resolve the caller rather than the
record (settings shortcuts, chart overlay preferences, custom metrics,
the Today rail, OCR, efficacy targets, credential tabs) ask for the
caller's own record instead, and the customise-shortcut guard now
requires that shape.

The vault has no delegated write route, so its controls stay withheld
under every grant, and the documents page says so in one sentence
where the upload control would be, in all seven locales.
2026-09-09 19:42:27 +02:00
Marc-André Bombeck b5c392636f feat(sharing): publish writable and manageable domains on the account payload
Every accountAccess entry on GET /api/auth/me carries writableDomains
and manageableDomains: the sections the grant opens, intersected with
the sections whose routes accept a delegated write at that level. A
READ grant gets two empty lists, a WRITE grant gets writable sections
only, a MANAGE grant gets both, and the vault appears in neither.

The client parser checks the structural invariants (no repeats, within
the grant's sections, manageable within writable, nothing below the
level) and requires the two published views of the active record to
agree on the lists. Regenerate the OpenAPI document and extend the
payload consumer guard with the active-record readers.
2026-09-09 19:42:26 +02:00
Marc-André Bombeck 54f0030ead feat(sharing): freeze which sections accept delegated writes
Add the one table of which record sections have a route declaring
requireRecordAuth("write") or ("manage"), derived from the route files,
and a structural guard that re-derives it from src/app/api on every run
and fails on a disagreement in either direction. The matcher tolerates
the line break a formatter puts after the opening parenthesis and
asserts a non-zero match count.

delegatedDomains() turns a grant's level and scope into the sections it
can add to and the sections it can change, keeping write within manage.
2026-09-09 19:42:26 +02:00
Marc-André Bombeck 925cc59ea5 Merge pull request #940 from MBombeck/chore/trivy-findings
v1.38.12 — the scanner findings are cleared
2026-09-09 19:38:19 +02:00
Marc-André Bombeck b8a3890ef4 chore(release): v1.38.12 — the scanner findings are cleared
Version anchors, the OpenAPI document and the changelog entry for the dependency release.
2026-09-09 19:19:50 +02:00
Marc-André Bombeck 312da96d9a build: type-check the application program, not the test tree, in next build
next 16.3 type-checks the whole tsconfig program during the build. That
reaches the unit tests under src/**/__tests__, their fixtures under
tests/, the Playwright config and the e2e tree, none of which is in the
image build context — .dockerignore leaves tests/ and e2e/ out on
purpose — so the image build stopped at "Cannot find module
'../../tests/fixtures/...'" on both architectures.

The build now reads tsconfig.build.json, which extends the main tsconfig
and excludes the test tree and the test-runner configs. `pnpm typecheck`
keeps using tsconfig.json and still covers the full program; the change
narrows only what `next build` compiles, which was already the case on
16.2 by omission. Verified by building with tests/ and e2e/ moved away.
2026-09-09 19:03:38 +02:00
Marc-André Bombeck 47953f5b8a chore(deps): clear the seventeen scanner findings
Trivy flags twelve distinct advisories on the lockfile and the image, none
in this code: next 16.2.11 (two critical, fixed in 16.3.3), sharp 0.35.3
pulled by next (high), nodemailer 9.0.3 (one high, three medium), js-yaml
4.3.1 (high), hono 4.13.3 under the MCP SDK's node server (three medium),
and the vitest mocker and baseline-browser-mapping (medium). Dependabot
lists none of them, which is why they sat.

next moves to 16.3.4 and nodemailer to 9.1.1 as direct pins; vitest to
4.1.11. js-yaml, hono, baseline-browser-mapping and sharp are transitive
and move through pnpm overrides bounded to the vulnerable ranges, so the
copies the scanner names change and nothing else does. Typecheck, lint,
the unit suite and the production build pass locally; the release gate
runs the integration and end-to-end suites on the minor Next bump.
2026-09-09 18:38:29 +02:00
Marc-André Bombeck 75d3fad04e Merge pull request #935 from MBombeck/dependabot/npm_and_yarn/types/pg-8.23.1
chore(deps-dev): bump @types/pg from 8.20.0 to 8.23.1
2026-09-08 21:46:24 +02:00
Marc-André Bombeck 5080624925 Merge pull request #934 from MBombeck/dependabot/npm_and_yarn/axe-core/playwright-4.13.0
chore(deps-dev): bump @axe-core/playwright from 4.12.1 to 4.13.0
2026-09-08 21:44:50 +02:00
Marc-André Bombeck 13a9c6576b Merge pull request #932 from MBombeck/dependabot/npm_and_yarn/lefthook-2.1.12
chore(deps-dev): bump lefthook from 2.1.10 to 2.1.12
2026-09-08 21:43:15 +02:00
Marc-André Bombeck 7a54aae1ca Merge pull request #931 from MBombeck/dependabot/npm_and_yarn/jose-6.2.10
chore(deps): bump jose from 6.2.3 to 6.2.10
2026-09-08 21:41:41 +02:00
Marc-André Bombeck c2bd573c99 Merge pull request #937 from MBombeck/release/v1.38.11
v1.38.11 — sign out everywhere means everywhere
2026-09-08 21:06:06 +02:00
Marc-André Bombeck e0cf6c2403 chore(release): v1.38.11 — sign out everywhere means everywhere
Version anchors, the OpenAPI document, the changelog entry, and the
README sentence that still declared immunization records out of scope
while the vaccination record has shipped since v1.37.3.
2026-09-08 20:23:30 +02:00
Marc-André Bombeck 076c2f9c5d fix(auth): sign out the other devices, lose a refresh to a revocation, key the replay cache by authority
"Sign out everywhere" revoked every other refresh token and nothing else.
A native login is two rows, and the Bearer check consults only the
paired access token, so the other phones kept working until that token
expired, up to a day on the default policy. The route also handed
destroyOtherSessions a session-kind credential for a Bearer caller, whose
session.id is the ApiToken row id; the exception matched nothing and the
calling phone revoked its own refresh token. destroyOtherSessions now
finds the paired access tokens through the refresh rows and revokes them
inside the same transaction, reporting the count, and the route names a
Bearer caller by its access-token hash. Programmatic tokens are untouched.

rotateRefreshToken marked the consumed row under usedAt: null alone, so a
revocation landing between the read and the write was overtaken and a
pair minted after the family ended stayed live. The guard now includes
revokedAt: null; on a lost race the minted pair is retired and the reason
distinguishes a revoked family from a double consume.

withIdempotency consulted the grant only at replay time, and only for its
existence; a narrow-scoped token was checked only on the delegated arm.
Both move into the cell key: a delegated cell carries the grant's id,
level and scope fingerprint, a narrow token's cells carry the token, and
a request with no live grant neither reads nor claims a cell. Cookie and
wildcard own-record cells are keyed byte-for-byte as before.

Tests: integration for the paired access tokens (cookie and Bearer
caller), a deterministic revoke-mid-rotation race against Postgres, unit
coverage for the new cell keys, and the structural guard moved to the
new invariant.
2026-09-08 20:23:30 +02:00
dependabot[bot] 776e36a37f chore(deps-dev): bump @types/pg from 8.20.0 to 8.23.1
Bumps [@types/pg](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/pg) from 8.20.0 to 8.23.1.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/pg)

---
updated-dependencies:
- dependency-name: "@types/pg"
  dependency-version: 8.23.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-06 15:55:49 +00:00
dependabot[bot] 4feccf3a07 chore(deps-dev): bump @axe-core/playwright from 4.12.1 to 4.13.0
Bumps [@axe-core/playwright](https://github.com/dequelabs/axe-core-npm) from 4.12.1 to 4.13.0.
- [Release notes](https://github.com/dequelabs/axe-core-npm/releases)
- [Changelog](https://github.com/dequelabs/axe-core-npm/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/dequelabs/axe-core-npm/commits/v4.13.0)

---
updated-dependencies:
- dependency-name: "@axe-core/playwright"
  dependency-version: 4.13.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-06 15:55:18 +00:00
dependabot[bot] 846e735b58 chore(deps-dev): bump lefthook from 2.1.10 to 2.1.12
Bumps [lefthook](https://github.com/evilmartians/lefthook) from 2.1.10 to 2.1.12.
- [Release notes](https://github.com/evilmartians/lefthook/releases)
- [Changelog](https://github.com/evilmartians/lefthook/blob/master/CHANGELOG.md)
- [Commits](https://github.com/evilmartians/lefthook/compare/v2.1.10...v2.1.12)

---
updated-dependencies:
- dependency-name: lefthook
  dependency-version: 2.1.12
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-06 15:53:56 +00:00
dependabot[bot] 0e51a17ab4 chore(deps): bump jose from 6.2.3 to 6.2.10
Bumps [jose](https://github.com/panva/jose) from 6.2.3 to 6.2.10.
- [Release notes](https://github.com/panva/jose/releases)
- [Changelog](https://github.com/panva/jose/blob/main/CHANGELOG.md)
- [Commits](https://github.com/panva/jose/compare/v6.2.3...v6.2.10)

---
updated-dependencies:
- dependency-name: jose
  dependency-version: 6.2.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-06 15:53:22 +00:00
Marc-André Bombeck a262cf7bb1 Merge pull request #930 from MBombeck/release/v1.38.10
v1.38.10 — the off-host backup streams, the rotated token sunsets
2026-09-06 16:28:46 +02:00
Marc-André Bombeck 69fc8bf2e3 chore(release): v1.38.10 — the off-host backup streams, the rotated token sunsets 2026-09-06 16:02:50 +02:00
Marc-André Bombeck fe71c9bf6b Merge pull request #929 from MBombeck/fix/rotation-sunset
fix(auth): give the rotated access token a fifteen-second sunset
2026-09-06 16:01:17 +02:00
Marc-André Bombeck dfb5d7483f fix(auth): sunset the rotated-away access token instead of revoking it
Rotation revoked the access token paired with the consumed refresh token
the instant the rotation committed. A native client with requests already
on the wire got 401 revoked on those, read that as "re-authenticate",
rotated again with the refresh token it had just spent, and tripped reuse
detection: the device's whole token family died because the client was
busy at the boundary.

Pull the paired token's expiry in to fifteen seconds instead. It is long
enough for an in-flight request on a slow mobile link to finish, including
a retry, and short enough that the token gains nothing meaningful over the
validity it already had. bearer.ts answers a passed expiry with reason
expired, which a client treats as "refresh", not as "sign in again".

LEAST(expires_at, $1) takes the minimum inside the single UPDATE, so the
write can only ever shorten: a token already inside its last seconds keeps
its own expiry, and there is no read-then-write window. The bound value is
an ISO-8601 UTC string cast in SQL so the comparison does not shift with
the host's timezone.

Reuse detection is untouched. A replayed refresh token, or one presented
under a spoofed device id, still revokes the family and its access tokens
on the spot, and so does the logout path.
2026-09-06 15:36:35 +02:00
Marc-André Bombeck 48fa96d4b6 Merge pull request #927 from MBombeck/fix/offhost-backup-streaming
fix(backup): stream the off-host copy so it fits a small container
2026-09-06 14:25:19 +02:00
Marc-André Bombeck 040cc6b767 Merge pull request #928 from MBombeck/docs/credit-1389-reporters
docs(changelog): credit the two reporters behind v1.38.9
2026-09-05 20:24:58 +02:00
Marc-André Bombeck 3ee3461f92 chore(backup): drop the whole-string builder the streaming path replaced
Nothing calls it any more: the weekly pass and the off-host job both
walk the payload through the streaming writer. Keeping an exported
function that builds the entire record as one string invites the next
caller to reintroduce the memory profile this branch removes.
2026-09-05 20:23:08 +02:00
Marc-André Bombeck 9d1246b525 docs(changelog): credit the two reporters behind v1.38.9 2026-09-05 20:09:20 +02:00
Marc-André Bombeck 13a9aacf20 fix(backup): stream the nightly off-host upload instead of building it
The off-host job was said to benefit from the streaming work the weekly
in-database backup got, and it did not. Only the payload builder was
shared: `runOffhostBackup` called `buildFullBackupJson` for the whole
document, `gzipSync` over that whole string, a whole-buffer
`createCipheriv` pass over the result, and handed the finished buffer to
a single `PutObject`. Four full copies of the record alive at once, on
the same arithmetic the weekly pass had already been fixed for.

Configuring an S3 target on a long-lived record therefore restarted the
container. On an account of 445 000 measurements the JSON alone is
242 MB, and against a 1 GB container's 524 MB heap the run died of heap
exhaustion seventeen seconds in — taking every signed-in session with
it, because the job shares the app process.

The write path is a stream end to end now: `streamFullBackupJson`
produces the document a page at a time, gzip and an incremental
AES-256-GCM writer consume it as it arrives, and `@aws-sdk/lib-storage`
puts it up in two 8 MB parts. What the process holds is fixed by the
pipeline's shape rather than by the record. Measured on that same
445 000-measurement account under `--max-old-space-size=450`, with the
heap pre-loaded to what a warm server holds: the old path dies with
`Ineffective mark-compacts near heap limit`, the new one finishes with a
peak 79 MB above its baseline and writes a 9.1 MB object.

The stored envelope gains version 3, which moves the GCM tag from in
front of the ciphertext to the end. That is the only change the stream
required — the tag exists only once the last block is in, so a leading
one means the whole object must exist before its first byte can be sent.
Nothing about the authentication moves: the tag still covers every
ciphertext byte and is verified before a byte of plaintext comes back.
Versions 1 and 2 still read, so every object already in a bucket
restores through the same reader with no flag to tell them apart.

The incremental writer is the crypto module's, split into its byte-level
half so the base64 form the in-database blob uses and the raw form an
object needs are one implementation under two framings. The off-host key
handling is unchanged: a separate `BACKUP_ENCRYPTION_KEY`, 64 hex or
32-byte base64, passed in rather than looked up.

A run that uploaded nothing for anybody is a failed job now, not
`ok: true` with an empty bucket behind it. Wrong credentials, a missing
bucket and an unreachable endpoint all fail every account rather than
one, and the target's own sentence rides out as the cause. A run where
some account got a copy still succeeds; retrying the whole cohort over
one object would re-upload everybody's.

The one ceiling left is structural rather than a memory bound, and it is
counted rather than discovered: a multipart upload carries 10 000 parts,
so an object past 80 GB is refused for that account with a clear message
instead of failing halfway through with an SDK error about part numbers.

`tests/integration/offhost-backup-streaming-memory.test.ts` pins the
budget from both sides — what the streaming uploader holds, and that the
materialising path does not fit the same budget on the same fixture in
the same process, so the number cannot pass by measuring nothing.
2026-09-05 19:13:11 +02:00
Marc-André Bombeck 1cd398897e Merge pull request #926 from MBombeck/release/v1.38.9
v1.38.9 — date order everywhere, plain-HTTP writes, gateway errors named
2026-09-05 18:56:12 +02:00
Marc-André Bombeck e9358170bc chore(release): v1.38.9 — date order everywhere, plain-HTTP writes, gateway errors named 2026-09-05 18:21:20 +02:00
Marc-André Bombeck 5694e25e68 Merge pull request #924 from MBombeck/fix/gateway-error-surfacing
fix(ai): say what the gateway actually answered instead of "empty content"
2026-09-05 18:17:42 +02:00
Marc-André Bombeck d4ee3480f1 Merge pull request #925 from MBombeck/fix/date-format-everywhere
fix(format): carry the date-order preference to every numeric date
2026-09-05 18:16:24 +02:00
Marc-André Bombeck 703ca2744e Surface what an OpenAI-compatible gateway actually refused
A gateway can answer a failed generation with HTTP 200 and put the reason
in the body: a top-level `error` object and no `choices`, or
`choices[0].error` beside `finish_reason: "error"` when a generation dies
mid-flight. Both fell through to the empty-content throw, so a dead credit
balance, a data-policy block, a rate limit and a model that is down all
recorded the same hop: status 0, reason "returned empty content", no
excerpt. Nothing on the provider health card told them apart.

Raise the shape a non-2xx reply raises instead, with the gateway's own
message leading and its `error.code` as the status when that code is an
HTTP error status. The chain classifier, the health ledger and the card
then see 402 / 403 / 429 / 503 and treat each of them the way they treat
the same status on the wire. Message and excerpt are bounded and
key-redacted by the same helper the non-2xx path uses, so remote text is
no more trusted here than it is there.

Gated on the gateway tag: api.openai.com signals every failure with a
status, so the pinned tags parse exactly as before, and a genuine empty
reply stays the empty-content throw it was. The local-endpoint provider
had the same hole on its buffered path, its buffered-reply fallback and
its stream, and gets the same treatment. The body classifier learned the
two account-side refusals a gateway words in its own vocabulary rather
than the vendor's.
2026-09-05 17:56:47 +02:00
Marc-André Bombeck 031600d69d fix(format): carry the date-order preference to every numeric date
The per-user date order reached the entry form and nothing else. A
reporter switched away from MM/DD/YYYY, the date picker followed, and
the dashboard chart axes and the measurements list kept the old order.

`makeFormatters` took `timeFormat` and `dateFormat` as optional
parameters defaulting to "AUTO", so six of the seven constructions in
the tree silently rendered the locale default and nothing anywhere
said the setting had been dropped. Drop both defaults. The compiler
then names every caller: the chart bucket labels, the legacy
`@/lib/format` helpers the measurements list renders through, the
medication compliance and efficacy charts, the doctor-report PDF and
the clinician share view.

Thread the preference:

- `makeBucketLabelFormatters` takes the order; the health and mood
  charts read `useDateFormatPreference()`. The UTC pin decides which
  day the label names, the preference decides how it is spelled, and
  the two are separate questions.
- `format.ts` reads `readStoredDateFormat()` beside the timezone and
  hour-cycle mirrors it already read.
- The PDF takes `dateFormat` as a required render option, alongside
  `timeFormat`, which was optional for the same reason.
- The clinician share view spells the OWNER's dates the owner's way.
  It also picked up the owner's hour cycle, which it had been ignoring
  while the PDF route beside it already honoured it. Both resolve
  through the new `resolveUserFormatPreferences`, the counterpart to
  `resolveUserTimezone`.

Textual months stay on the UI locale. The preference pins numeric
field order by rendering through de-DE / en-US / en-CA, and a textual
month through those would change the month name's language.

Add `date-order-explicit-formatter-guard`: a raw numeric date renderer
must take its locale from the preference or carry a written reason,
and a formatter construction may not hard-code "AUTO" for the order.
Its allowlist holds thirteen calendar-day key builders, each with the
reason it has no order to get wrong. The sibling timezone guard passes
every one of them, because naming a calendar says nothing about
spelling a date.

Refs #922
2026-09-05 17:06:34 +02:00
Marc-André Bombeck 0913e8f2b7 Merge pull request #923 from MBombeck/fix/upload-https-hint
fix: writes and uploads work again on a plain-HTTP self-host
2026-09-05 16:48:04 +02:00
Marc-André Bombeck 5556478691 Make uploads and every other write work over plain HTTP
crypto.randomUUID() is [SecureContext] in the Web Cryptography IDL, so a
page served over plain HTTP never gets it. Measured in Chromium against
http://<lan-ip>: isSecureContext false, randomUUID and subtle undefined,
getRandomValues still a function.

The document vault minted its queue id and Idempotency-Key that way, inside
the file-input change handler. On a LAN self-host the call threw before a
queue row existed, so picking a file produced no upload, no error and no
trace — the picker simply looked inert, and the only way through was to
reach the app over HTTPS. The client transport has minted a default
Idempotency-Key the same way since v1.37.18, which put every apiPost and
apiPatch on the same footing: on such a host nothing wrote at all.

Add randomId(), which prefers the platform call and otherwise assembles a
v4 UUID from getRandomValues — the same CSPRNG, the same 122 bits, no
secure context required — and route every browser-side call site through
it. Nothing in an upload needs one: the bytes travel over multipart XHR and
every cryptographic operation happens on the server. Passkeys, web push and
home-screen install still need HTTPS; browsers withhold those outright.

A structural guard fails a direct crypto.randomUUID() anywhere outside the
two server-side files that may keep it, so the class cannot return one call
site at a time.

Also point the CSV and JSON import cards straight at the import guide. They
resolved through a redirect under the integrations tree, which is the wrong
place for a guide that is not an integration runbook. The suite that
covered those links pinned the old spelling rather than the guarantee; it
now asserts an absolute docs-site URL, no internal path, and new-tab
hygiene.
2026-09-05 16:22:39 +02:00
Marc-André Bombeck 295d70988d Merge pull request #921 from MBombeck/release/v1.38.8
v1.38.8 — the HRV tile for ring and strap accounts, and a token ceiling
2026-09-03 21:28:44 +02:00
Marc-André Bombeck 315341cbb8 chore(release): v1.38.8 — the HRV tile for ring and strap accounts, and a token ceiling 2026-09-03 21:02:49 +02:00
Marc-André Bombeck c0cbe10033 Merge pull request #899 from Antiheld86/fix/dashboard-hrv-rmssd-fallback
Fix/dashboard hrv rmssd fallback
2026-09-03 21:01:25 +02:00
Marc-André Bombeck fde8f9c80c test: pin both HRV label keys across every locale
The tile now calls t() with a key looked up from HRV_LABEL_KEY rather
than a literal, and the call-site coverage guard only reads literal
arguments. So the label left the guard's field of view exactly when it
became per-series: dropping either key from a bundle would ship a raw
key into the dashboard of whichever locale lost it, with nothing in the
gate to say so.

The keys are read from the map, so a third HRV series is covered by
construction rather than by remembering. The count is anchored, because
an empty map would satisfy the loop by matching nothing. A second case
asserts the RMSSD label actually names the measure in every locale,
which is the whole reason the second key exists.

Verified by deleting the key from one bundle: three cases fail and name
the locale and the key.
2026-09-03 20:38:13 +02:00
Marc-André Bombeck e961be81a2 Merge remote-tracking branch 'origin/main' into pr899
# Conflicts:
#	CHANGELOG.md
2026-09-03 20:37:47 +02:00
Marc-André Bombeck d6d463ff72 Merge pull request #893 from Antiheld86/feat/measurement-token-ceiling
Cap how many live measurement tokens an account may hold
2026-09-03 20:35:38 +02:00
Antiheld86 2adc0d08b2 docs: note the live-token ceiling in the Home Assistant guide
The mint endpoint's 409 ceiling wasn't mentioned anywhere a self-hoster
would see it before hitting it.
2026-09-03 11:28:22 +02:00
Antiheld86 6d86b71a3c Address review: move the query-shape case, document the mint race
Two notes from review, neither a behaviour change.

`counts only live tokens carrying this scope` mints successfully and then
inspects the `where` handed to the count — it was sitting in the refusal
block and belongs beside the other what-was-the-helper-given cases. Moved
verbatim.

`still mints on the last free slot` stays where it is, next to the 409 it
is the other half of: the pair is what pins `>=` against `>`, and reading
either alone tells you less than reading both together.

The ceiling is count-then-create and so not atomic — two mints racing at
nine both pass and the account lands eleven. Now said out loud, along with
the two things a reader cannot see from this file: the overshoot is bounded
because the rate limit above is a single atomic upsert, and the house
pattern for making it exact is an advisory lock, named with call sites. Left
unserialised on purpose — this catches a runaway loop rather than metering a
quota, and a lock on a credential mint buys nothing for what it costs.
2026-09-03 11:15:49 +02:00
Antiheld86 d9d4a5703a Note the token ceiling in the changelog
Filed under Changed rather than Added: v1.38.1 shipped the token, so this
is a limit arriving on something people already have.
2026-09-03 11:15:49 +02:00
Antiheld86 8ef909e970 Regenerate the API contract for the token ceiling
The mint endpoint's description and its new 409 landed in the OpenAPI source
without the generated spec following, which CI's drift check would have
caught. No behaviour change; the two hunks are the reworded limits sentence
and the ceiling response block.
2026-09-03 11:15:24 +02:00
Antiheld86 371c0c49f1 Cap how many live measurement tokens an account may hold
The mint's rate limit bounds a burst and does nothing about accumulation:
a stuck automation retrying politely inside its 10-per-minute allowance
still leaves several hundred live credentials behind in an afternoon,
each one to be revoked by hand.

Count live rows before the create and refuse at ten.

Live, not minted-ever, so revoking frees a slot and an expired token
stops occupying one — the ceiling bounds what currently exists rather
than what the account has ever done. Scoped to measurements:write for a
reason worth stating: signing in mints a wildcard access token per
session and those accumulate on their own, so counting every row would
let ordinary browser use exhaust the budget and then refuse a mint for a
reason invisible to the person hitting it.

409 rather than 429. This is a conflict with the account's current
state, not a rate: it does not clear by waiting, it clears by revoking,
and a 429 would tell the caller the opposite of what is true.

Placed after validation, so a malformed request hears about the
malformation rather than the ceiling, and before the create, so hitting
the limit costs no credential.

Ten is set to catch a loop rather than to ration — a household running
Home Assistant, a scale bridge and a couple of scripts sits at three or
four, and it is not a security boundary since the holder can revoke and
mint freely.

Tests pin the boundary, the query shape and the ordering, and were
mutation-checked: turning >= into > fails the ceiling case, and dropping
the scope filter fails the query-shape case. The integration leg seeds
a wildcard and an expired row as decoys, then revokes one live token and
asserts exactly one slot opens — the leg that fails if the count is of
mints rather than of tokens alive.
2026-09-03 11:15:24 +02:00
Antiheld86 07a38323e3 Merge upstream v1.38.7
Only CHANGELOG.md conflicted: v1.38.7 released while this branch was open,
so the new release heading landed where the branch's [Unreleased] section
sits. The HRV entries stay under [Unreleased] above 1.38.7; everything from
1.38.7 down is upstream's file verbatim.

docs/api/openapi.yaml auto-merged. Upstream's only change there was the
`info.version` bump to 1.38.7, which the merge took while keeping this
branch's DashboardLayoutReadResult, and package.json now reads 1.38.7 to
match — so the merged file should equal a fresh generate. It is a generated
file, though, so confirm with `pnpm openapi:generate` rather than trusting
the three-way merge.
2026-09-03 08:44:36 +00:00
Marc-André Bombeck 6db18d0b71 Merge pull request #920 from MBombeck/fix/backup-heap-budget
fix(backup): bound the blob, not the heap, so the weekly pass runs again
2026-09-03 10:31:31 +02:00
Antiheld86 7080ddea44 docs(api): regenerate the spec for unavailableWidgetIds 2026-09-03 10:30:03 +02:00
Marc-André Bombeck d540ebcc79 chore(release): v1.38.7 — the weekly backup produces a backup again 2026-09-03 10:11:49 +02:00
Antiheld86 45fe97e07b Declare unavailableWidgetIds in the wire contract
The widgets GET grew a response field and the spec was never told. Nothing
would have caught it: `openapi:check` compares the generated yaml against
the Zod registry, and an undeclared field changes neither — so CI stays
green while the published contract quietly stops describing what the route
returns. iOS decodes this payload.

`dashboardLayoutResult` is shared by the GET and the PUT echo, but the
field is resolved per request from the caller's modules and their data, so
it exists only on the read. A separate `dashboardLayoutReadResult` extends
the shared schema for the GET rather than widening both verbs and
describing a field the PUT never sends.

docs/api/openapi.yaml is NOT regenerated in this commit: `pnpm
openapi:generate` cannot run here (the Prisma engine download is refused,
so `@/generated/prisma/client` is missing and the registry will not load).
The tree is therefore in drift on purpose and `pnpm openapi:check` will
fail until `pnpm openapi:generate` is run and the yaml committed.
2026-09-03 08:08:57 +00:00
Marc-André Bombeck 24f3afd464 fix(backup): bound the stored copy, not the process heap
The writer added in v1.38.6 compared the process's live heap usage against
80 % of V8's heap limit and aborted above it. That reading is not the
backup's footprint; it is the whole process's, garbage included. A
long-running app sits at 400 MB of largely collectable heap, so on a 1 GB
container (a 419 MB budget) the weekly pass aborted the first flush of every
account: four out of four in seven seconds, the smallest of them a demo
record whose entire stored copy is 1.2 MB, each told its record was too large
and its operator to buy memory.

Drop the gauge. What the writer holds is bounded by its shape and needs no
reading to prove: the three unbounded tables are pulled a page at a time,
every other section is released as soon as its JSON is in the sink, and at
most one flush of text is pending. The one copy that does grow with the
record is the stored blob, so the bound moves there — counted in the
ciphertext bytes actually produced, against a fifth of this process's heap
limit, which is what two copies of the answer plus a live set have to fit
inside. The message names both numbers.

A pass that wrote nothing for anybody now fails its job instead of reporting
`ok: true` with `backed: 0`, so the failing-queue panel and the backups page
read the same thing an operator would. A pass where some accounts were
written keeps passing with the failures as counts.

Measured under --max-old-space-size=450 from a heap deliberately dirtied
first: 445 000 measurements peak at 28 MB held by the backup, a one-row
record at under 1 MB.
2026-09-03 09:51:05 +02:00
Antiheld86 263c61da16 Mock the two new route dependencies, and cover the dead switch
Both routes 500'd in their unit tests because the change gave them
dependencies the mocks did not know about: the widgets GET reads a module
flag and probes for an SDNN row, and the analytics slim slice resolves the
module map. Neither test mocks `@/lib/modules/gate`, and the widgets test's
prisma double has no `measurement` model — so both calls threw and the
handler answered 500. Real breakage from this branch, not stale
expectations.

The widgets GET no longer resolves the whole module map for one answer.
`hrv` is the only conditionally-dead widget and `recovery` the only module
that decides it, so it reads that one flag through `isModuleEnabled`, the
way this route's neighbours read a single flag.

Both gate mocks spread the real module so only the one call is stubbed;
everything else that imports it keeps live behaviour. The widgets
`beforeEach` states the modules-on default explicitly, because
`resetAllMocks` strips a factory's implementation and every test below
assumes it.

Added coverage for the behaviour itself rather than only unbreaking the
suite: recovery off with no SDNN marks `hrv` unavailable, an account WITH
SDNN keeps the toggle, and recovery on does not run the probe at all — the
one added read on a hot cached route must not touch the common account.
2026-09-03 07:42:00 +00:00
Antiheld86 6aac2070b4 Address review: label key, gate every feed, retire the dead switch
Five points from the review, in the order they were raised.

1. The RMSSD marker did not survive. The tile label paints truncated,
uppercase and on one line, so an appended `· RMSSD` was the first thing
dropped in the longer locales — the part a reader needs to tell a 40 ms
RMSSD night from a collapsed SDNN one. `measurements.typeHrvRmssd` already
exists in all seven bundles, so each series now carries its own key.
`pickHrvSummary` returns that key beside the series it chose, which keeps
one mapping from series to label rather than a conditional at the call site.

2. The module gate bit on one path only. `gateSummariesByModules` was
private to the snapshot builder, and with the snapshot flag off the tiles
are fed by `/api/analytics`, which filtered nothing — so recovery-off plus
RMSSD-only still painted the tile, on the exact path the helper's docblock
promised it could not. The filter moves next to the map it reads, and both
analytics slices apply it. Gated after the cache read, so the cached cell
stays module-independent and toggling a module takes effect on the next
request instead of waiting out the TTL.

3. The same class one step on: recovery off plus RMSSD only left a switch
that was on, a tile that could never paint, and no explanation. The repo
already calls that a dead switch and hides the row; HRV is only dead
sometimes, so the answer needs one fact the Settings screen does not have.
The server resolves it — `unavailableWidgetIds` on the widgets payload —
and Settings drops those rows. An account with SDNN keeps the toggle: its
tile still works with recovery off, because SDNN is a vital no module owns.
The SDNN probe is an index-only existence check that runs only when
recovery is off, outside the layout cache so the row goes the moment the
module does.

4. The brittle test sliced from the helper to the end of the file, so any
function added below it would have gone red pointing at HRV. Bounded to the
function's own body, with a guard on the bound itself. The three wiring
assertions matched formatted source text — they would have passed just as
well if the tile never rendered — and are replaced by a test that renders
the tile through a real TrendCard and asserts the reading is on screen.
One negative source check is kept, naming the expression the bug lived on
rather than the formatting of its replacement.

5. Rebased onto v1.38.6; the changelog entry sits under [Unreleased].

Not verified here: `pnpm db:generate` cannot run in this container (the
Prisma engine download is refused), so snapshot.test.ts, the widgets route
test and the analytics route test could not load, and typecheck is
incomplete. Lint, format and the HRV suite (17 tests) pass.
2026-09-03 07:25:58 +00:00
Antiheld86 4594b664e3 Type the empty-input cases so tsc accepts the loop
The "neither series" test walks three inputs in one array literal. Inferred
from the literals alone, the bare `{}` widens to `{ HRV_RMSSD?: undefined }`,
and TypeScript rejects that against `pickHrvSummary`'s
`Record<string, DataSummary> | undefined` — an optional-undefined property is
not assignable to the index signature. Vitest never typechecks, so the suite
ran green while `tsc --noEmit` failed.

Annotating the array pins the parameter type at the declaration and leaves all
three cases exactly as they were.
2026-09-03 07:03:54 +00:00
Antiheld86 a165ff9bb6 Show the HRV tile for an account whose HRV is RMSSD
HRV lives under two measurement types and they are not the same measure:
Apple Health / Fitbit / Google Health write SDNN as
`HEART_RATE_VARIABILITY`, while Oura / Polar / WHOOP — and a bridge
pushing a watch that reports it that way — write nightly RMSSD as
`HRV_RMSSD`. Every HRV surface unions the two: `/insights/hrv` through
`fallbackMeasurementType`, the Coach through
`COACH_SOURCE_MEASUREMENT_TYPES.hrv`, the MCP reads through
`withHrvFallback`. `sub-page-metric.ts` even says listing both is what
keeps "the tab, pill, and dashboard tile lit whichever source the user
has".

The dashboard tile did not. It read SDNN alone, so an RMSSD-only account
got a Settings → Dashboard toggle that turned on and rendered nothing,
with no explanation, while the insights page charted the same readings —
which is why it reads as a broken layout rather than a missing series.

`pickHrvSummary` picks the series with the same rule `withHrvFallback`
uses: the primary wins whenever it has any rows, the fallback only when it
has none. Never a merge — the two share `ms` but measure different things,
so blending them would invent a number no device reported. The caller gets
the winning type back, because the freshness caption has to read the
series on show and the label has to name the measure when it is not SDNN
(`· RMSSD`, as the insights chart title already does).

Second, less visible half: `HRV_RMSSD` is recovery-owned in
`METRIC_STATUS_MODULE_OWNERS`, but the dashboard snapshot gates off
`SUMMARY_TYPE_MODULE`, a different map, and that one did not list it. The
omission was inert while the tile read SDNN alone; adding the fallback
without it would hand a recovery-off account a tile built from
recovery-owned rows — the exact hazard the owner map documents. The entry
goes in beside the four sibling recovery types, so the gate stays server
side and the client keeps no competing copy.
2026-09-03 07:03:54 +00:00
Marc-André Bombeck 3cf65c2c90 Merge pull request #919 from MBombeck/integration/post-1385
v1.38.6 — glucose in mmol/L, backups inside key rotation
2026-09-03 08:17:59 +02:00
Marc-André Bombeck 2dc3f8984e test: derive the glucose import assertions from the shared factor
Two integration assertions carried the import path's own copy of the
mmol/L conversion, so unifying the two conversions left them asserting
numbers the code no longer produces. They now multiply by the exported
factor, which is what the unit tests already do.

The reason these were missed before the merge is worth writing down:
`pnpm test` does not run tests/integration, and neither the change that
unified the factor nor the gate on the integrated branch ran the suite
that covers the import path. A literal here re-pins whichever copy of a
conversion the caller happened to use when the test was written, so the
assertion is derived rather than pinned.
2026-09-03 07:42:59 +02:00
Marc-André Bombeck 6c43514596 chore(release): v1.38.6 — glucose in mmol/L, backups inside key rotation 2026-09-03 06:51:41 +02:00
Marc-André Bombeck 06fe87f5a3 Merge remote-tracking branch 'origin/fix/rotation-registry' into integration/post-1385
# Conflicts:
#	CHANGELOG.md
2026-09-03 06:35:38 +02:00
Marc-André Bombeck 405f0ebfd0 Merge remote-tracking branch 'origin/fix/backup-streaming' into integration/post-1385
# Conflicts:
#	CHANGELOG.md
2026-09-03 06:35:36 +02:00
Marc-André Bombeck 7c5f49c18e Merge remote-tracking branch 'origin/fix/unwired-columns' into integration/post-1385
# Conflicts:
#	CHANGELOG.md
2026-09-03 06:35:35 +02:00
Marc-André Bombeck 1d218e0a31 Merge remote-tracking branch 'origin/fix/greeting' into integration/post-1385
# Conflicts:
#	CHANGELOG.md
2026-09-03 06:35:34 +02:00
Marc-André Bombeck 01f06c4468 Merge remote-tracking branch 'origin/docs/correct-1385-backup-claim' into integration/post-1385 2026-09-03 06:35:32 +02:00
Marc-André Bombeck 26f01ad746 Merge pull request #912 from MBombeck/fix/strictschemas
fix: refuse an unrecognised request field where the caller can act on it
2026-09-03 06:34:47 +02:00
Marc-André Bombeck daaa8e17b2 Merge pull request #917 from MBombeck/test/settle-background-tasks
test: settle detached background work before a test file tears down
2026-09-03 06:34:39 +02:00
Marc-André Bombeck 45d0fe442f fix(crypto): rotate the backup blob and stop keying the registry on names
`DataBackup.data` holds every weekly disaster-recovery snapshot and every
uploaded pack, AES-256-GCM at rest like everything else, under a column
called `data`. The rotation registry was keyed on the `*Encrypted` naming
convention, so the script never read a backup, reported zero rows
remaining, and the runbook read that zero as permission to retire the
previous key. Following the documented procedure destroyed every stored
backup — the copy an operator reaches for precisely when nothing else
works.

Register it, and register the idempotent-replay response cache the same
sweep turned up. The backup column walks in bounded batches (one row is a
whole compressed account) and re-seals the ciphertext without reading the
plaintext, so both stored envelopes come back byte-identical and so will
any later one. The cache is marked disposable: a row it cannot read is
dropped rather than counted as an error, because keeping it only
guarantees the next replay gets a body it cannot parse.

Running the script against a seeded database rather than reading it turned
up two more. It died on the mood day-context note, whose table is keyed on
the entry rather than on an `id`, and abandoned every column after it —
the backups included. And the document index's verbatim text rotated
without ever being named in the summary.

Make the naming assumption stop carrying weight. A new guard traces the
encryption helpers through their wrappers, walks every Prisma write
payload, and fails when a column receives ciphertext without being
registered. It asserts an anchored, non-zero match count so a matcher that
stops matching fails instead of passing. A second check pins each model's
primary key against the schema.

The script now ends by naming the registered columns it did NOT walk and
exiting non-zero when any is missing: a zero that means "nothing left" and
a zero that means "never looked" must not print the same. The runbook's
retire-the-key step was rewritten around that signal, and tells an
operator who already rotated on an older release how to get their backups
back.
2026-09-03 06:29:57 +02:00
Marc-André Bombeck 41d9ef0713 docs: record the glucose unit, the export stamp and the provider status 2026-09-03 06:06:07 +02:00
Marc-André Bombeck 4cb15232a2 test: name the shared glucose factor where the CSV import pinned the old one
Three assertions repeated 18.016 and the product it gave. They were the
reason the two factors could sit in the tree at once looking correct. They
take the exported constant now, and the parser test asserts the round trip
a reader on mmol/L experiences rather than a magic product.
2026-09-03 06:05:58 +02:00
Marc-André Bombeck 9e47b47b00 fix: honour the chosen glucose unit in the measurements list
The list renders a reading through the metric/imperial transform registry,
and glucose is not in it, so the list kept saying 95 mg/dL while the
dashboard tile said 5.3 mmol/L for the same reading — correct on both
counts and disagreeing anyway.

The edit sheet is the half that could have done damage. Its label follows
the same resolution as the row, so on mmol/L the number in the input is in
mmol/L and has to come back the other way before the PATCH. Row, edit seed
and inversion move together; converting the display alone would rewrite a
95 mg/dL reading as 5.3 the first time somebody corrected a typo.

An mg/dL account edits in the unit the column already holds and stays on
the identity path, deliberately: the converter rounds, and sending an
mg/dL edit through it would quantise a stored 95.48 the moment somebody
opened the sheet to fix a note. A row whose stored unit is not the type's
canonical one still shows verbatim, as before.
2026-09-03 06:05:58 +02:00
Marc-André Bombeck 5078867203 feat: let an account choose the unit its glucose is shown in
`User.glucoseUnit` has existed since v1.2 and around thirty surfaces read
it — the dashboard tiles, the glucose page, the targets panel, the CSV and
FHIR exports, the doctor report, the Coach snapshot, the low-reading push
copy. Nothing could ever write it. No route, no schema, no field on any
form, so every account resolved to the mg/dL default and the mmol/L half
of the app was unreachable code. Anyone who reads glucose in mmol/L
converted in their head on every screen.

This is the missing end: a `GET`/`PATCH /api/auth/me/glucose-unit` scalar
on the pattern the unit-preference endpoint next door established, and a
dropdown in the profile form beside it. Deliberately its own control
rather than a branch of metric/imperial: metric countries are split on
which unit they read glucose in, so one dropdown would get half of them
wrong.

Storage is untouched and stays untouched. Every reading is written in
mg/dL by every ingest path and the unit only selects a display branch, so
nothing already recorded is reinterpreted. The entry form moved with the
preference, which is the half that could have hurt: it asks in the chosen
unit and inverts through `toCanonicalMgdl` on submit, so a 5.3 typed by an
mmol/L reader is filed as 95 mg/dL rather than as 5.3 — a value the
plausibility band accepts in silence and every surface reads back as a
severe hypo.

The contract gains the endpoint and nothing else; the account payload
already carried the field.
2026-09-03 06:05:58 +02:00
Marc-André Bombeck 841593a5b2 fix: converge the two factors a glucose reading was converted by
A value imported in mmol/L was multiplied by 18.016; one displayed in
mmol/L was divided by 18.0182. The two sat in different files, both
correct-looking, and a reading that went in as 5.3 did not come back out
as 5.3. Latent while nobody could select mmol/L, live the moment they can.

One exported constant now, on the guideline figure the display path
already used, and the glucose insight page takes it from there rather than
keeping a third copy. The test names the constant instead of repeating the
digits, which is how the two came apart in the first place, and it asserts
the round trip a reader on mmol/L actually experiences.
2026-09-03 06:05:58 +02:00
Marc-André Bombeck 5df2b36068 docs(schema): say why the device ledger keeps a first-sighting instant
`UserKnownDevice.firstSeenAt` has a database default, no application
writer and no reader anywhere in the tree, and it is invisible to the
column sweep because the sweep skips a column nothing writes. Annotated
rather than dropped: the first sighting a user sees is the audit row the
login-alert path writes, and that row goes on the audit-retention
schedule, while the ledger row does not. This column is the ledger's own
copy of the same instant, reachable through the database only — the model
holds salted hashes and a coarse label precisely so it has no user-facing
surface, and the backup excludes it wholesale.
2026-09-03 06:05:58 +02:00
Marc-André Bombeck 7dbec3bc4d feat(admin): name the status a failing provider came back with
The provider-health ledger has recorded the HTTP status of every failure
since v1.11.0 and nothing has ever read it. The operator card could say
three of five chains were failing without saying whose problem that was,
which is the one thing the operator needs: a 401 is a credential only they
can replace, a 429 or a 503 is the provider's afternoon and waiting is the
right move.

The fold carries the status of the failure whose instant the row already
shows, not an aggregate over the column. A MAX of two HTTP statuses is
arithmetic on a label, and a status describing a different failure than
the one on screen would send the operator to the wrong place. The column
joins the grouping key instead, and the fold picks the group belonging to
the newest failure.

Blank where there was nothing to record: a connection that never completed
has no status, and a chain that has since recovered had its status cleared
along with the rest of its failure state.
2026-09-03 06:05:58 +02:00
Marc-André Bombeck 2ea08c6966 fix: record the export stamp an Apple Health import already promised
The import status endpoint returns the instant the Health app stamped on
the archive, the published contract requires the field, and the schema
comment said the parser filled it during unpack. It never did: ExportDate
sat on the parser's ignore list, so the column answered null on every job
ever run, for a year.

The parser reads the element now and hands the stamp to the worker on the
next chunk boundary, so the value lands while the run is still going and a
job that later fails still records which export it was working from. An
archive that omits the element, or writes a value the runtime cannot read,
leaves the column null rather than guessing at an instant.

No contract change: the endpoint and the OpenAPI description already
described this behaviour.
2026-09-03 06:05:58 +02:00
Marc-André Bombeck 3118cf240c fix(backup): stream the weekly backup instead of building it whole
The compression that landed last release was real and was measured in the
wrong place. On a development machine with a multi-gigabyte heap the pass
finished; the container the job runs in is capped at 1 GB, which gives V8
a 524 MB limit, and there the same pass died of memory about fifteen
seconds in. Because the job shares the application process, that was not
one failed backup — it was a restart, and every signed-in session on the
host went with it.

Reproduced before touching anything, under `--max-old-space-size=450`
against a seeded account of 445 000 measurements, 30 000 mood entries and
60 000 intake events: `FATAL ERROR: Reached heap limit` at 34 s. The same
fixture doubled to 890 000 measurements now completes inside a 296 MB
limit, holding 16 MB of live heap where the old writer held 168 MB.

The document is written incrementally now. `buildFullBackupPayload` takes
a `deferBulk` mode that declares the three unbounded tables instead of
reading them, and `streamFullBackupJson` walks the payload in key order,
pulls those tables through page by page, and releases every other section
as soon as its JSON reaches the sink. `packBackupBlobStreaming` feeds that
into gzip and an AES-256-GCM stream, so nothing between the database rows
and the stored value ever exists whole. Both writers go through the same
per-row serialisers, and the round-trip suite pins their output byte for
byte rather than trusting that they agree.

The intake and mood reads are ordered totally now. A keyset cursor needs
it, and a partial order also let two exports of one account differ over a
tie, which every multi-dose day has.

The streamed ciphertext is a new shape at rest, because GCM only produces
its tag once the last block is in and a leading tag is what makes the old
layout unstreamable. It carries a marker no older writer can produce, so
the two families are disjoint by construction rather than by sniffing.
All three stored shapes — plain, compressed, streamed — restore, proved
both ways.

The writer also watches its own live heap and stops at 80 % of V8's
limit. An account too large for its host is now one failed backup,
counted in the run's meta, instead of a restart for everybody on it.

The stored column is the ceiling that is left: `data_backups.data` is a
single `text` value, so the finished artifact has to exist as one string,
and that is the only part of the job still growing with the record. The
operator runbook says so, with the number at which it starts to matter.
2026-09-03 06:05:52 +02:00
Marc-André Bombeck 50a88a9526 style: reflow the corrected v1.38.5 backup entry
The correction was inserted mid-bullet, which left the off-host sentence
trailing after it and the paragraph unwrapped. The off-host sentence goes
back with the technical description it belongs to, and the correction
reads last.
2026-09-03 05:55:54 +02:00
Marc-André Bombeck 40ff39aaa5 docs: record the greeting and locale fixes under Unreleased 2026-09-03 05:49:47 +02:00
Marc-André Bombeck 1850e2f564 fix(i18n): reconcile the stored locale from the request, not from a lost PUT
`User.locale` is the only signal a cookie-blind path has. The nightly
briefing warm, the Coach nudge, the reminder senders and the native aggregate
all resolve from that column; the screen in front of the user resolves from
the `healthlog-locale` cookie first, then the column, then Accept-Language. So
a browser can read the whole app in German while the column says English, and
while it does, nothing on screen looks wrong: the divergence surfaces as one
generated paragraph in the wrong language inside an otherwise correct page.

Keeping the two in step was a fire-and-forget PUT from a mount effect. A 401
on the paint before sign-in, an offline blip, a tab closed mid-flight — each
loses the write, and the next mount repeats the same unchecked attempt rather
than noticing the column is still wrong, so a stale column can stand for the
life of the account.

`getSession` now corrects the column when the request carries a valid locale
cookie the column disagrees with. It is ordered by the request pipeline,
needs nothing from the client, and is self-limiting: once the two agree the
condition is false. Only a cookie counts, and a cookie is only ever written
alongside a committed UI locale, so Accept-Language never stamps a guess onto
a column that generated prose depends on. The mount PUT stays for the
server-set cookie it gets in reply, which Safari's 7-day cap on script-written
cookies makes worth having; it is no longer the mechanism.

The obvious suspect was a first-paint race between two unordered writes. It is
not that: the provider takes the locale the server already resolved and
nothing on the mount path changes it, so the effect fires once with the right
value. `locale-first-paint-single-write` pins both properties so a future
mount-time flip has to face them.
2026-09-03 05:49:18 +02:00
Marc-André Bombeck 86f826351f fix(dashboard): resolve the aggregate greeting through the shared locale order
The salutation and the streak label are the two strings this route still
translates server-side, and the native client is its only caller: a Bearer
request carries no language cookie, so `User.locale` is the sole per-user
signal. The coercion here stopped at English when that column was NULL, so an
account that never opened the language picker was greeted in English on an
instance configured for German, while every string beside it was German.

`resolveJobLocale` is where the fallback order lives — stored preference, then
the operator default, then English — and every background writer was moved
onto it earlier. This was the last copy of the old coercion outside that tree.
The structural guard covers `lib/jobs` and `lib/daily` only, so it never saw
this one; the two tests added here pin the behaviour directly instead.
2026-09-03 05:49:18 +02:00
Marc-André Bombeck 4aaed5c312 fix(dashboard): give the time-of-day greeting one clock
Three pieces of code answered "what hour is it" for the salutation. The
snapshot builder computed a `greetingHour` in the user's zone and put it on
the payload so clients would not have to; no client ever read it. The
insights hero derived one through the shared `hourInTz`. The dashboard header
derived one through a local helper that fell back to the DEVICE clock
whenever the runtime could not resolve the configured zone, which is what
happens to an IANA entry the browser's data does not yet carry. At one
instant, for one account, those three returned 20, 21 and 05.

Keep the client end and drop the server one. The hour is a clock reading, not
a fact about the record, and the snapshot body serves stale for up to an hour
past its fresh TTL, so a stored hour can name a salutation the clock has left
behind. What the server IS authoritative for is the zone, and that already
travels on the same payload and is already what both surfaces read.

Both greetings now share `hourInTz`, so an unresolvable zone falls back to the
same default the rest of the app uses instead of to the device. The header's
private helper is gone; it had no other caller.

Two tests pinned the old shape by asserting the payload carried an hour.
Inverted rather than deleted: the payload must now be shown NOT to carry one,
which is the property that was missing when the field went unread for months.
`greetingHour` leaves the response contract, so a native client decoding it as
required needs the field made optional or dropped.
2026-09-03 05:49:18 +02:00
Marc-André Bombeck d6bc858899 fix: refuse an unrecognised request field where the caller can act on it
A `z.object()` without `.strict()` strips an unknown key and parses
clean, so a caller that misspells a field name gets a 200 and loses the
value with nothing to tell it. The worst of them was the Coach
question-dismiss endpoint, where an omitted `question` means "dismiss
all": a typo in that key wiped every pending question and answered as
though one had been dismissed.

Twenty-four inline schemas across twenty-two endpoints are strict now —
the settings toggles, the restore and bulk-delete endpoints, message
feedback, the admin user update, the onboarding acknowledgements, the
provider chain, the chart overlay preferences, the medication extractor
and the two client-side reporters.

The strip stays where it carries weight. Sync ingest, device
registration and the layout PUTs are built out of fields that shipped as
additive and optional, on the promise that a server which does not know
one ignores it; an app running ahead of the install it talks to is
routine here rather than exceptional, and refusing would turn a dropped
field into a refused batch — a year of history lost to one row, a
dashboard that will not save, a phone that quietly stops registering for
push. A read filter discards nothing when a stray query parameter rides
along, the OAuth endpoints are required by RFC 6749 and RFC 7591 to
ignore parameters they do not recognise, and an import file comes from
another version or another tool by definition. Each is registered with
its reason in a new inventory test, so a schema cannot join them without
someone making the call. That test parses the tree rather than grepping
it: fourteen of these schemas are written `z\n  .object({…})` and a
`z.object(` sweep never saw them.

`sanitiseZodIssues` renders `unrecognized_keys` instead of passing it
through. Zod leaves `path` empty and puts the names in `issue.keys`, so
the sanitised issue named nothing at all and the caller was told only
that its body had failed. The names now ride a bounded `keys` field and
the message is rebuilt from them, capped at ten keys of 64 characters
and restricted to identifier characters, so a caller-supplied key cannot
echo back verbatim through the error path or into the audit ledger. The
names survive `stripValuesFromMessage` because a field name is
structure, not user-typed content.
2026-09-03 05:49:13 +02:00
Marc-André Bombeck fc1ebeae9e Merge pull request #911 from MBombeck/fix/colaudit
fix(audit): teach the column sweep to tell a filter from a write
2026-09-03 05:47:37 +02:00
Marc-André Bombeck 006db19bee Merge pull request #910 from MBombeck/chore/advisory-floors-1385
chore(deps): clear the advisory list and drop an unused 340 MB dependency
2026-09-03 05:47:30 +02:00
Marc-André Bombeck a42d4083fa docs(changelog): correct the v1.38.5 backup claim
The entry said the weekly pass finishes again. It was written from a
measurement taken on a development machine with a multi-gigabyte heap,
and it does not hold on a small container: capped at 1 GB the runtime
gets a 524 MB heap, and the pass still runs out of memory there. It gets
roughly three times further than before, which is a real improvement and
is now described as one, but it does not complete, and the failure takes
the whole process down rather than failing as a job.

Building the record incrementally instead of whole is the fix and has not
landed. Until it does, an instance backing up a large record needs more
than 1 GB, and the entry says so.
2026-09-03 05:47:14 +02:00
Marc-André Bombeck bdf3ffb5da test: settle detached background work before a test file tears down
The unit suite reported all 1937 files green and then failed the job with
`EnvironmentTeardownError: Closing rpc while "onUserConsoleLog" was
pending`, naming a different scoring test each time.

Vitest replaces globalThis.console with a sink that forwards every write
to the main thread as an onUserConsoleLog RPC call. When a worker
finishes a test file it awaits the calls in flight and then rejects
whatever was started after that point, so a console write from work that
outlived its test lands in the gap and fails the run. The blame goes to
the file being torn down rather than to the test that started the work,
which is why the named file never logged anything itself.

Three paths detach a promise and log on the handle: fireAndForget, the
stale-while-revalidate cache refresh, and the offline query persister.
They now register the handled handle in a set that both suite setups
drain in afterEach, so no test leaves work in flight. The registry is
inert outside test: nothing there awaits it, and holding a reference to
an unsettled promise would retain it for the life of a worker. No
production behaviour changes, so there is no changelog entry.

Evidence. A focused harness that starts failing background tasks and
returns hit the teardown error 10 runs out of 10 before the change and
0 out of 10 after. Instrumenting the real suite showed two detached
console writes per run escaping their test, both from the rollup tail;
after the change, none, and thirteen writes per run now complete inside
the test that started them.

The guard asserts the behaviour, not a count: a registered task must
keep settleBackgroundTasks from resolving ahead of it, and the set must
drain back to empty. It goes red on unregistered work, on a disabled
registry, on an unwrapped call site, on a sweep that matches nothing,
and on a setup that drops the hook.
2026-09-03 05:30:08 +02:00
Marc-André Bombeck 118f100956 chore(deps): clear the advisory list and drop an unused 340 MB dependency
Three advisories stood open, all development-scope. Two are closed with
version floors in the workspace overrides, following the existing pattern:
@humanfs/node for GHSA-p498-v437-472g and esbuild for GHSA-g7r4-m6w7-qqqr.
Both patched lines stay inside the same minor, so nothing downstream moves.

The third, GHSA-jmr9-qjv8-65gv in extract-zip, had no patched release to
float to. It arrived through @openai/codex-security, which nothing in the
tree imports: the package was referenced only by its own declaration, a
knip ignore entry, and a release-age exclusion. Removing it closes the
advisory and takes about 340 MB of node_modules with it. The knip ignore
and the release-age exclusion go with it rather than being left to rot.

pnpm audit now reports no known vulnerabilities.
2026-09-03 05:19:31 +02:00
Marc-André Bombeck 252b09c00c fix(audit): teach the column sweep to tell a filter from a write
The column-reader sweep read every `field:` key as a write, so
`where: { ticketHash }` counted as writing `ticketHash`. All twelve columns it
reported were a lookup key or a cron's discovery predicate being filtered on,
and a review tool that has cried wolf twelve times is not consulted on the
thirteenth. It also reported only columns that already had a write, which made
a column with no write at all the one thing it could not see.

Mask each file, bracket-match every Prisma argument, and tag its contents as
write, projection or query so nesting resolves innermost-wins. Follow a payload
assembled before the call: a const handed to `update:`, a spread merged into a
`create:`, a `rows.push({...})` builder filling a typed array. Credit raw SQL
against the `@map` column name. Report a column nothing touches as its own
category, and split the output so a write with no reader reads differently from
a query predicate, a relation's foreign key and an annotated column.

Twelve false alarms become nineteen findings that hold up. Four are worth
acting on and are left for a decision rather than annotated away: the glucose
unit preference and an import job's export date have readers and no writer, and
the provider-health status code and the known-device first-seen stamp have the
opposite.

The matcher underneath is a test now, checked by breaking the fix three ways.
2026-09-03 05:09:00 +02:00
Marc-André Bombeck 1e4b30c417 Merge pull request #909 from MBombeck/integration/night-audit
chore(release): v1.38.5 — the backup finishes, the dashboard stops scanning
2026-09-03 04:00:46 +02:00
Marc-André Bombeck a6016eac90 chore(release): v1.38.5 — the backup finishes, the dashboard stops scanning
Carries the night's audit work: the weekly backup ran out of memory
rather than out of time and now completes, two dashboard reads stopped
scanning the largest tables, six webhook verbs compare a secret behind a
rate limit, three global channel switches actually stop delivery,
thirty-five settings reach the container, four guarded helpers are used
where their naive twins were, and three guards now see what they claim.
2026-09-03 03:37:25 +02:00
Marc-André Bombeck 3ae27ee843 Resolve the round-trip import conflict by keeping both sides 2026-09-03 03:24:23 +02:00
Marc-André Bombeck b2a8edf65f Merge fix/backup-timeout
# Conflicts:
#	CHANGELOG.md
#	tests/integration/backup-round-trip.test.ts
2026-09-03 03:23:41 +02:00
Marc-André Bombeck ee4afc7b9e Merge fix/guarded-twins
# Conflicts:
#	CHANGELOG.md
2026-09-03 03:23:40 +02:00
Marc-André Bombeck fe8ab36e12 Merge fix/env-whitelist
# Conflicts:
#	CHANGELOG.md
2026-09-03 03:23:39 +02:00
Marc-André Bombeck 5cac883c17 Merge fix/settings-that-do-nothing
# Conflicts:
#	CHANGELOG.md
2026-09-03 03:23:38 +02:00
Marc-André Bombeck b04d07923d Merge test/guard-coverage-gaps 2026-09-03 03:23:38 +02:00
Marc-André Bombeck a675daf0c1 Merge fix/module-gate-and-webhook 2026-09-03 03:23:37 +02:00
Marc-André Bombeck 98324b0eff Merge origin/main 2026-09-03 03:23:08 +02:00
Marc-André Bombeck f6a45ca5c5 Merge pull request #901 from MBombeck/perf/dashboard-seq-scans
perf(dashboard): stop scanning the two largest tables on every load
2026-09-03 03:15:58 +02:00
Marc-André Bombeck 2b7fd8322e Merge origin/main 2026-09-03 02:33:39 +02:00
Marc-André Bombeck 1eba3488d5 Merge origin/main 2026-09-03 02:33:34 +02:00
Marc-André Bombeck 48f24d7fb0 Merge origin/main 2026-09-03 02:33:29 +02:00
Marc-André Bombeck 5ae872c755 Merge origin/main 2026-09-03 02:33:24 +02:00
Marc-André Bombeck 69baecbe70 Merge origin/main 2026-09-03 02:33:19 +02:00
Marc-André Bombeck ea49dcb96e Merge origin/main 2026-09-03 02:33:14 +02:00
Marc-André Bombeck db6c8b2f0a Merge remote-tracking branch 'origin/main' into test/guard-coverage-gaps 2026-09-03 02:32:45 +02:00
Marc-André Bombeck 6a733c9272 Merge pull request #905 from MBombeck/chore/advisory-floors-0903
chore(security): raise two advisory floors that went stale overnight
2026-09-03 02:32:34 +02:00
Marc-André Bombeck 83b1400e5b refactor(labs): drop the fail-soft lab-note decrypt, which has no caller left
The export was its only user, and the export now reads through a helper that
marks an undecryptable note instead of blanking it. Nothing else wanted the
silent null: the list DTO never carries the note at all, only `hasNote`, and
the single-resource GET has always used the throwing decrypt so a key gap
surfaces there.

Deleted rather than kept behind a dead-code exemption. A fail-soft twin
sitting unused next to a strict one is the exact shape this branch has been
clearing out — the next person writing an export reaches for whatever is
nearest, and the whole point was that the nearest thing should not silently
swallow a row. It had no test of its own, so none was removed; the three
comments that pointed at it are rewritten to say what is true now.
2026-09-03 02:29:37 +02:00
Marc-André Bombeck 154c93b5e1 feat: surface a stalled or failed backup schedule
The weekly pass can stop and leave no trace where anyone looks. The
handler's own error never runs when the job is killed rather than thrown;
`recordError()` increments an unnamed counter; and the admin status page's
failing-queue panel looks back 72 hours, which for a weekly queue means a
permanent failure is on screen three days in seven. The backups page
itself showed an ordinary row with an ordinary timestamp, because a copy
made six weeks ago reads exactly like Sunday's until somebody subtracts
the dates.

The listing now carries two facts that fail at different times: the age of
the newest scheduled copy, which never leaves any retention window, and
the terminal state of the last scheduled run, which is the only place the
reason is written down. `readLastQueueRun` takes the newest run rather
than a window, so a weekly queue's outcome stays readable until the next
one replaces it, and it unwraps the value pg-boss stores a thrown error
under, so the page says "job timed out" instead of raw JSON. The
failing-queue reader gets the same unwrap.

Manual uploads are excluded from the cadence judgement by the shape of the
input, so an ad-hoc upload cannot make a dead cron look alive, and a fresh
instance is not called overdue for having no copy yet.

The listing also stops reading every blob into the web process to measure
it; `octet_length` answers that in the database, which on an instance with
large records was its own way of running out of memory.
2026-09-03 02:22:37 +02:00
Marc-André Bombeck d8196d5208 fix: compress the stored backup before encrypting it
The weekly pass built the whole account in memory, serialised it whole,
encrypted the string whole, and handed the result to the database whole.
That is four full copies of the record at the same moment — the object
graph, the JSON, the base64 ciphertext at 1.33x the JSON, and the copy the
driver makes of that parameter. Measured against a seeded account of
445 000 readings, the JSON alone is 242 MB and the run dies of heap
exhaustion; under a modest heap it never reaches the insert. The pass was
not slow, it could not finish.

A health record's JSON is extremely repetitive, so gzip takes that 242 MB
to 14 MB and every copy after it shrinks with it. The same run completes
in about twenty seconds with a peak heap of 434 MB and a stored row of
25 MB instead of 322 MB — which also matters because the copy lives inside
the database it would be needed to restore. Both backup jobs now hand the
serialised form back from a frame of its own, so the payload graph is
released before the compress step allocates anything.

The marker sits inside the ciphertext, so the stored column keeps the one
shape `decrypt()` already understands and rows written before this still
restore. The off-host object gets the same treatment through the version
byte its envelope always carried; version 1 objects still read back, which
both the restore drill and the restore script depend on.

The obvious saving — dropping soft-deleted readings, four rows in five on
a real record — is not taken, and the round-trip test now seeds a
tombstone and asserts it makes the journey. A tombstone inside the
retention window is what tells a synced client the row is gone and what
makes a re-sent sample a no-op; a restore without them brings back every
measurement the account ever deleted on the next device sync.
2026-09-03 02:22:21 +02:00
Marc-André Bombeck b5dd9372a7 fix: give the weekly backup a run window of its own
The `data-backup` queue was registered without send options, so every job
it minted took pg-boss's queue defaults: a fifteen-minute expiration and
two redeliveries. A snapshot that serialises every account's whole record
does not fit in fifteen minutes on a large one, so the pass was killed
part-way through, redelivered twice against the same record, and reached
`failed` with "job timed out" about three quarters of an hour after it
started — having never once completed.

Two hours, on the schedule rather than on the queue: `create_queue()` ends
in ON CONFLICT DO NOTHING, so a queue-level default would apply to a fresh
database and be inert on every instance that already has the queue. The
admin run-now route sends with the same options, or an ad-hoc snapshot
would silently keep the default the cron was rescued from.

The default two retries stay. The old redeliveries were pointless because
the first attempt could not succeed either; a transient failure genuinely
benefits from a second go, and the alternative is losing the week.
2026-09-03 02:22:07 +02:00
Marc-André Bombeck 97e610a173 docs: record the env-whitelist fix under Unreleased 2026-09-03 02:13:05 +02:00
Marc-André Bombeck ee14b9d564 test: gate every env read against the compose whitelist
Derives both sets mechanically — the whitelist from docker-compose.yml, the
read set from the source — and fails when a variable is read without being
forwarded. Written red against the tree before the fix, where it named 35.

A search for process.env. alone is not the read set: four modules resolve the
name through a helper and index process.env dynamically, which hides every
OIDC_* variable and ALLOW_LOCAL_AI_PRIVATE_HOSTS. Each is registered with its
own call-shape matcher and its own non-zero assertion, so a rename fails the
file loudly instead of quietly shrinking the set. The walk and the matchers
both assert a floor, because an empty match set agrees with any allowlist.

Thirteen deliberate exceptions each carry a written reason, and the list is
kept honest from both ends: an entry that stops being read, or that later
appears in the whitelist, fails too.
2026-09-03 02:13:02 +02:00
Marc-André Bombeck e9206bab0b fix(compose): forward the env vars the app reads but never received
The environment: block is a whitelist. Compose substitutes ${VAR} from .env
at compose-up, so a value set there looks configured, but a variable the block
does not name never reaches the Node process and the default stands silently.

Twenty-eight variables were in that state: DEMO_MODE, the four LOG_* knobs and
the three LOKI_* shipping vars, DATABASE_STATEMENT_TIMEOUT_MS, four retention
and alerting windows, TELEGRAM_WEBHOOK_SECRET, NIGHTSCOUT_PRIVATE_ORIGINS,
three OAuth callback overrides, both Open-Meteo endpoints, four AI knobs,
three APNs key-source vars, and DASHBOARD_SSR_PREFETCH.

APNS_KEY and APNS_KEY_FILE are the sharpest of them: .env.production.example
and the env manifest both document a precedence chain of APNS_KEY_B64 before
APNS_KEY before APNS_KEY_FILE, and only the first arrived.

Each is documented in .env.production.example in its neighbours' style. The
VAPID section's note claiming those three names are absent from the whitelist
is corrected; they have been on it since v1.17.1.
2026-09-03 02:12:55 +02:00
Marc-André Bombeck 98597232f2 fix(notifications): drop the unreachable WEB_PUSH_* VAPID aliases
Six WEB_PUSH_* names and NEXT_PUBLIC_VAPID_PUBLIC_KEY sat behind the three
real VAPID_* variables in the env fallback. None was ever on the compose
environment: whitelist and none appeared in .env.example, .env.production.example
or the env manifest, so under the bundled stack a value set under any of them
could not reach the process. Remove them and the self-hosting note that
advertised them.
2026-09-03 02:12:44 +02:00
Marc-André Bombeck ae731b92d9 docs(changelog): record the correlation, adherence, continuity and export fixes 2026-09-03 02:08:10 +02:00
Marc-André Bombeck ae3525a88e refactor(fhir): skip an adherence observation with no expectation rather than write 0
`adherenceRatePercent` returns null exactly when nothing was expected, so
callers render a placeholder instead of a misleading 0 or 100. The FHIR
exporter coalesced that null to 0, which would put a clinical claim of zero
adherence into an exported bundle. The guard above it means the branch
cannot be reached today; skipping rather than coalescing keeps it
unreachable if that guard ever moves.
2026-09-03 02:08:10 +02:00
Marc-André Bombeck 156f7e1523 fix(insights): skip tombstoned rows in the correlation channel and the cache gate
A deleted reading is kept with a `deletedAt` stamp, and the schema says in
as many words that normal reads filter it. Three did not.

The custom-metric correlation channel filtered the metric's own tombstone
but not its entries', so a reading the person deleted kept shaping the
correlation they were shown. The status input hash — which decides whether a
cached AI assessment is still current — filtered its measurement arm but not
its mood aggregate and not its custom-metric count or newest-entry probe. A
deletion left that fingerprint unchanged, so the gate re-dated yesterday's
text and served it as today's over data that was gone.

Pinned in the existing soft-delete guard, whose matchers were checked by
removing each filter again.
2026-09-03 02:08:09 +02:00
Marc-André Bombeck 4d98a273b1 fix(export): carry an undecryptable note as a marker instead of as nothing
A lab note or a biomarker context written under a key this instance no
longer holds came out of a portable export as `null` — byte-identical to a
column that was never written. The restore importer then wrote nothing, so
the text was gone and nothing said it had ever been there. The whole loss
fit inside a fail-soft `catch` written for a list view, where returning null
is the right answer.

Both now export a short marker naming what happened, and the marker survives
a restore. The Coach transcript already did this with a placeholder sentence
and the doctor report with a rendered flag; the marker is now one constant
the transcript shares, and its comment says why an empty string will not do.

The unit test that required `note: null` here pinned the loss. It keeps the
half that matters — one bad row must never abort the export — and asserts
the marker instead. The round trip is proven end to end against a real
restore.
2026-09-03 02:08:09 +02:00
Marc-André Bombeck c2c018aa08 fix(insights): exclude unlogged days from the medication-continuity pairing
The blood-pressure medication continuity series joined every day that had a
systolic reading against `takenByDay.get(day) ?? 0`, so a day with no intake
record at all entered the scatter and the coefficient as a measured 0 %
continuity. A week away from the app read as a week off the medication.

Only days carrying an intake record are paired now. A logged skip is a real
zero and stays; a day with no record is absent, and absence is not zero.

The timezone-parity fixture in the route test recorded three logged days out
of five and relied on the other two arriving as zeros, which pinned the
defect rather than the timezone question it asks. Its two remaining days are
recorded as skips, which keeps five paired days and keeps every one of them
something the person actually logged.
2026-09-03 02:07:52 +02:00
Marc-André Bombeck 04361a9fe7 fix(medications): drop a medication with no schedule from every adherence surface
`calculateCompliance` answers `rate: 100, totalExpected: 0` for a medication
that expects no dose. Arithmetically honest, and a lie on a surface that
reads the number as adherence — it also inflated the averages the AI prompts
are built from. The doctor report has excluded both the PRN arm and the
empty-schedule arm since it was written, with the reason beside it. The
insights envelope, the blood-pressure gate and the medication-compliance
snapshot filtered only PRN, and the empty schedule is reachable:
`POST /api/medications` accepts `schedules ?? []` on a scheduled medication.

Move both arms into one predicate, `expectsDoses`, and route all four
surfaces through it so they cannot drift apart again.
2026-09-03 02:07:43 +02:00
Marc-André Bombeck 1354e1d9b5 Raise two advisory floors that went stale overnight
Four advisories landed against the URI parser that arrives under ajv,
including the copy the connector SDK pulls, all of them host confusion
or request forgery through percent-encoded schemes, skipped IDN
canonicalisation and malformed authorities. The floor set yesterday was
one patch below the fix. A query-string parser needs 6.16.0 for an
array-limit bypass and a denial of service.

The audit reads no known vulnerabilities after the bump.
2026-09-03 02:07:38 +02:00
Marc-André Bombeck f72e236b8a fix(insights): gate the mood correlation cards on significance
The mood page called the plain `pearsonCorrelation` — strength banded from
|r| alone above a floor of five pairs, no significance test — so five days
of noise sloping the right way arrived at the reader as a "Strong" badge,
with n and r behind an info icon. The guarded twin was written for exactly
that failure and names it in its own comment, and the weight, blood-pressure
and mood-status surfaces had already moved onto it. The mood page had not.

Route the page's five cross-metric channels through
`significantPearsonCorrelation` (n >= 20 AND p < 0.05) and carry the reason
a pairing was refused, so the card can distinguish "still building" from
"twenty days and nothing in them" instead of showing the same blank for
both. New copy in all seven locales.

Add a structural guard that fails when a new caller of the unguarded helper
appears outside a written allowlist. Two callers remain on it, each named as
open work rather than as a blessing: the /insights envelope and the AI
feature payload both still band at n >= 5, and moving them changes payload
shapes their own tests pin.
2026-09-03 02:07:29 +02:00
Marc-André Bombeck 8409d7a0a0 docs(changelog): record the three settings that did nothing 2026-09-03 02:02:33 +02:00
Marc-André Bombeck f39f2f32ce fix(insights): read the dismissed evidence hash in the resurface gate
Dismissing a correlation pattern stores `dismissedEvidenceHash` alongside
the effect size and sample size, and the gate that decides whether to raise
the finding again read the two numbers and never the hash. The hash is the
only part of the snapshot that covers the whole evidence tuple, and a
snapshot that carries it without the two numbers — what a partial restore
leaves behind — could not be released by anything: the gate had no value to
compare and fell through to `false` on every future run.

Move the decision into `shouldReleaseDismissal`, which reads the hash twice
and for two different reasons. Evidence byte-identical to what was
dismissed settles immediately, without evaluating a threshold. Evidence
whose hash no longer matches goes to the existing thresholds when the
numbers are there, and releases the dismissal when they are not, because a
changed hash is still proof the evidence moved.

The thresholds themselves are untouched. A dismissal still has to survive
ordinary sampling noise, which is what they are for; a hash that changes on
every recomputation would otherwise undo a deliberate dismissal on the next
nightly run.
2026-09-03 02:02:30 +02:00
Marc-André Bombeck 4dbad48d89 fix(admin): persist the assistant flags sent to the settings route
`adminSettingsSchema` validates five `assistant*` booleans and the strict
schema refuses anything else, but the route's `booleanFields` list never
carried them. Sending one alone answered 422 "No valid fields"; sending one
alongside a real field answered 200 and dropped it. The schema comment says
the entry exists so an operator scripting their settings over the single
route can carry the values, so the route is brought up to the contract
rather than the contract cut down to the route.

The flags are echoed in the GET and PUT payloads as raw column values — the
master-over-sub resolution stays with `/settings/assistant-flags`, which
owns that shape and was never affected.
2026-09-03 02:02:22 +02:00
Marc-André Bombeck de0876b215 fix(settings): refuse enabling a channel the operator switched off
With the switches now enforced at dispatch, a user could still flip a
channel on, see the toggle stick, and get nothing. Refuse the enable
instead, with 403 and a message that names the reason: the ntfy and
Telegram config endpoints on both accepted body shapes, and the Web Push
subscribe endpoint, which is the enable step for that channel because it
creates the channel row.

Telegram is checked before the webhook registration, so a refused enable
makes no outbound call and stores nothing. Disabling a channel keeps
working while the switch is off — a user must always be able to turn a
channel off, whatever the operator has done.

The three refusals are published in the contract; `/api/settings/global-services`
already exposes the switches so a client can hide the control instead of
provoking the refusal.
2026-09-03 02:02:15 +02:00
Marc-André Bombeck 8d2753f942 fix(notifications): apply the global channel switches at dispatch
`AppSettings.telegramGlobal`, `.ntfyGlobal` and `.webPushGlobal` were read
in two places, and neither of them was the one that matters: the setup-card
visibility on Settings -> Integrations and an echo in the preferences
payload. The dispatcher never looked at them. An operator who switched a
channel off instance-wide lost the setup card and kept every existing
delivery on that channel, indefinitely.

Gate each of the three in the dispatcher, in the shape
`isApiGloballyEnabled()` already uses for the twelve API routes. The read
sits above the per-user channel row and below the per-event preference, it
happens at most once per dispatch, and only when a switchable channel is
actually in the cascade. A skip writes a `globally_disabled` row to the
push-attempt ledger so the admin diagnostics name the cause, and does not
count as an attempt, so `dispatched` keeps telling the truth. The account's
own channel row is left enabled: the switch is the operator's, and flipping
it back has to restore delivery without every user re-enabling anything.

APNs, the generic webhook and email carry no instance-wide switch and are
not gated here; they are turned off at their source instead.

The unit test drives the real dispatcher over a stubbed settings row; the
integration test writes the actual singleton and reads the ledger back out
of Postgres, which is the layer that proves the column the admin route
writes is the column the dispatcher reads.
2026-09-03 02:02:04 +02:00
Marc-André Bombeck 6633f0fb19 fix(lint): cover the unguarded egress paths and aliased fetch
Two spellings the egress guard could not see, both probed.

src/proxy.ts, src/instrumentation.ts and src/cli/ sat outside the enforced
roots (src/lib/ and src/app/), and the companion api-fetch-required guards
the client surface, so it did not reach them either. A raw fetch dropped
into instrumentation.ts linted clean. All three are egress-free today, but
instrumentation is exactly where an exporter pointed at an operator-supplied
URL would land.

The callee match knew the identifier `fetch` and the globalThis / window /
self member forms only, so an aliased import escaped it in every file:
`import { fetch as f } from "undici"` then `f(url)` linted clean under
src/lib. That spelling is what src/lib/safe-fetch.ts itself writes. Local
names bound to an imported `fetch`, and namespace-imported `ns.fetch(…)`,
are now callees; the wrapper internals and test files stay exempt as
before, and the wrapper's own aliased import is pinned as a valid case.

Adds the rule's missing unit-test file. The header records what the
binding scan still cannot see: require(), dynamic import, a fetch passed
as a parameter, and egress that never spells fetch at all.
2026-09-03 01:50:25 +02:00
Marc-André Bombeck b956636d9a docs: record the faster dashboard open in the changelog 2026-09-03 01:47:52 +02:00
Marc-André Bombeck 83b6ce4b15 test: pin the dashboard summary read shapes against a plan regression
Neither read is a bug a behavioural test can see: both shapes return the
right rows, and only the plan differs. So the guards split by what each
can actually answer.

The unit guard asserts on the SQL the readers build, with comments
stripped so it matches the query text and never the prose describing it:
no DISTINCT ON on this path, a LATERAL driven from an unnested type list
with a LIMIT on the per-type branch, a bound type predicate on the rollup
read sitting alongside the user and granularity filters, and the route
still calling the shared readers rather than growing a second copy. Four
of its five cases fail against the pre-change SQL.

The integration companion runs the shipped readers and the pre-change SQL
side by side over one fixture on the real Postgres and requires identical
rows. The fixture carries the cases the rewrite could have broken: a type
whose only rows are tombstoned, a type with no rows, a type whose newest
row is a tombstone over a surviving one, and coarser rollup granularities
the DAY read must ignore. Dropping the soft-delete filter or shortening
the type list makes both cases fail.

Plan assertions are deliberately not in the integration file: a
testcontainer fixture is too small for the planner to choose the access
paths a real account produces, so an EXPLAIN there would pin nothing.
2026-09-03 01:47:52 +02:00
Marc-André Bombeck f2e98e3885 perf(dashboard): drive the per-type summary reads from the type list
Two reads behind the metric tiles scanned far more than the rows they
return, because PostgreSQL 16 has no index skip scan: a query that wants
one row per measurement type but never names a type cannot be served by
any index keyed on (user_id, type, ...).

The latest-reading read used DISTINCT ON (type), so it produced every
live row of the account in (type, measured_at DESC) order before keeping
one row per group. On a multi-year account that is a sequential scan plus
a sort that spills to disk once it outgrows work_mem. It is now a LATERAL
join over the type list, one lookup per type against the live-row partial
index from migration 0183, each stopping at the first row. CROSS JOIN
LATERAL is an inner join, so a type with no live reading drops out as
DISTINCT ON dropped it, and ORDER BY reproduces the same enum ordering.

The sparkline read filtered measurement_rollups on user_id and
granularity only, skipping the second column of the table's key, so on a
single-account host neither the primary key nor the user/type/
granularity/bucket index could drive it and every stored granularity got
scanned. It now names the full canonical enum, which filters nothing out
and restores the equality the key needs; the existing index serves it.

Measured on a fixture matching a real account (454k measurements, 79%
tombstoned, 75.5k rollup rows): the first read goes from a seq scan plus
a 3.2 MB external-merge sort at 112 ms to a nested loop at 0.7 ms, and
the second from a seq scan discarding 72k rows at 6.9 ms to a bitmap
index scan at 1.6 ms. Same rows, same order, same types.

Both reads move out of the route into src/lib/dashboard/summary-reads.ts
so the integration suite can exercise the SQL itself rather than a copy
of it, the same seam buildMedsTodayBlock already uses. No schema change:
adding an index on (user_id, granularity, bucket_start) would have landed
in the same range while leaving the existing index unused and adding a
fourth write target to a table the rollup workers upsert into constantly.
2026-09-03 01:47:41 +02:00
Marc-André Bombeck 1f5115fbf3 fix(lint): see positional query keys and the app tree
Two holes, both proven with a probe that produced zero errors.

The rule matched the object properties `queryKey:` and `mutationKey:` and
nothing else, so the positional form was never seen —
`setQueryData(["bare"], 1)` seeds the same cache cell a `queryKey:` reads,
and `getQueryData` / `getQueryState` / the four defaults setters read and
write it the same way. Those seven methods are checked at their first
argument now, whether the call is bare, a member, or a computed member.

The enforced roots were components, hooks, query modules, and files
carrying their own "use client", which left src/app out. That is where the
server prefetch pages build the keys the client later reads, and they
carry no directive, so a server key diverging from the client's was
unguarded. src/app is a root now.

No violation surfaces on the current tree. The rule header records what it
still cannot see: a key assembled into a variable before the call site,
and the method-name match, which neither follows a project helper nor
knows an unrelated object with the same method name.
2026-09-03 01:46:29 +02:00
Marc-André Bombeck 3989d9e9f9 test(modules): derive the route-gate inventory from the module registry
The inventory walked a flat, hand-written array of route trees, so its
coverage grew only when somebody remembered to grow it. It had stopped
growing: the coach, environment, mental-health, inbound-document and MCP
trees were all outside it, and so was the doctor-report export route the
header already named as a doctorReport surface. Every route in the first
four turned out to be gated, so nothing leaked — but that was the authors'
care rather than the inventory's, and a green run claimed more than it
covered.

The trees are declared per module key as an exhaustive Record<ModuleKey, …>:
a new registry key does not compile without an entry, one test asserts every
key is declared, another asserts every declared tree exists, and a third
discovers an API directory named after a module key on disk and fails when
it is not declared. An empty array is now a claim with a reason beside it
(glucose and recovery ride the measurement engine), not a silence.

Walking the newly covered trees classifies every route: coach, environment,
mental-health, the document vault and /api/export/health-record all gate
directly. The seven /api/mcp routes are the credential surface behind the
remote endpoint and go on the exempt list with the reason written out — the
endpoint itself lives outside /api and carries the gate, so a credential
minted while the module is off is inert. That refusal is added to the
behavioural list so deleting its proof fails here.

/api/export/health-record joins /api/fhir as a key-pinned tree: both serve
the whole-record aggregate, so doctorReport is the only correct key.
2026-09-03 01:46:01 +02:00
Marc-André Bombeck 20812b54f5 fix(webhooks): rate-limit every verb that checks the shared secret
The Withings entrypoints, the Telegram bot webhook and the Coolify deploy
hook limited POST and left the verification verbs unlimited. GET and HEAD
compare the same secret and answer 200 against 401, which is an oracle for
guessing it and a free load channel besides; timingSafeEqual protects the
timing channel, not the status code. The project's rule is that the
per-source limit runs before secret verification, and it was being applied
per handler rather than per file.

Each verification verb now runs the same limit its POST sibling used, on the
same bucket. Telegram and the deploy hook grow the small local helper the
Withings routes already share. HEAD re-shapes the limiter's JSON envelope
into a bodyless 429 and keeps the rate-limit headers.

The new guard walks every webhook route from the filesystem, resolves which
local helpers reach a comparison and which reach the limiter, and fails when
an exported verb reaches a comparison without the limiter in front of it. It
asserts a non-zero match count so an empty match set cannot read as green.
WHOOP already passed: it exports POST only.
2026-09-03 01:42:56 +02:00
Marc-André Bombeck 84437d5f95 test: read every spelling of a dependency override pin
The lockstep guard compared only the pins both matchers happened to
recognise, and neither matcher said so when it recognised fewer.

Workspace side: the key had to be quoted. Every entry in the file carries
an `@<selector>` suffix and therefore needs quoting, so the matcher looked
complete — but `mysql2: "^3.22.0"` is a valid pnpm override with no
selector and no quotes, and it parsed to nothing. Unquoting that key and
pointing the Dockerfile at `^1.0.0` left all six tests green.

Dockerfile side: only `npm pkg set 'overrides.X=Y'` was recognised, so
re-quoting the same line as `npm pkg set overrides.X=Y` removed the pin
from the comparison without changing what the image installs.

Both sides now parse line by line: quoted or bare keys and values on the
workspace side, any shell quoting of the same assignment on the Dockerfile
side, plus a raw JSON `"overrides"` block. What neither table can read is
collected and asserted empty, so a future spelling fails loudly instead of
shrinking the compared set in silence.
2026-09-03 01:42:16 +02:00
Marc-André Bombeck 214b268b41 Merge pull request #898 from MBombeck/release/v1.38.4
chore(release): v1.38.4 — the shared key finds its provider
2026-09-02 17:24:10 +02:00
Marc-André Bombeck 253bd3175a chore(release): v1.38.4 — the shared key finds its provider
The admin AI key now goes to the API its base URL names, seven code
scanning findings are closed at their source, and the guard that was
meant to hold the image's two dependency pins in step can see scoped
packages for the first time. Two accessibility markers and one audit
read no longer race their own page.
2026-09-02 17:01:06 +02:00
Marc-André Bombeck a0f2e0d260 Merge pull request #894 from MBombeck/chore/scanning-sweep
chore(security): close seven scanning alerts and the guard that hid one
2026-09-02 17:00:26 +02:00
Marc-André Bombeck 0635db898a Merge origin/main into chore/scanning-sweep 2026-09-02 16:42:17 +02:00
Marc-André Bombeck 15ded13b79 Merge pull request #896 from MBombeck/test/a11y-visible-locators
test(a11y): match only the visible copy of a painted marker
2026-09-02 16:41:57 +02:00
Marc-André Bombeck 0e605b0698 Merge pull request #897 from MBombeck/fix/admin-provider-host
fix(ai): send the admin key to the provider its base URL names
2026-09-02 16:34:56 +02:00
Marc-André Bombeck eb53e9aaf4 Merge remote-tracking branch 'origin/main' into fix/admin-provider-host 2026-09-02 16:17:55 +02:00
Marc-André Bombeck b34e911c8e docs(admin): say which providers the server-key base URL accepts
The operator card offered a free-text base URL with an OpenAI placeholder
and no word about what else it takes, so an Anthropic endpoint looked
unsupported even though the field accepts that host. One line beside the
existing hints, in all seven locales, plus the changelog entry.
2026-09-02 16:17:17 +02:00
Marc-André Bombeck f4c90dc134 fix(ai): pick the admin client from the configured base URL
The operator's global provider always built an OpenAI client, so an admin
who saved an Anthropic key and https://api.anthropic.com/v1 (a host the
settings allowlist accepts) had every AI call fail: an OpenAI-shaped body
posted at Anthropic's Messages API, with nothing in the error pointing at
the mismatch.

Route by hostname instead. api.anthropic.com and any subdomain of
anthropic.com get the same AnthropicClient the per-user ANTHROPIC arm
builds, with the same Claude model default; every other host keeps the
OpenAI client, which is what an OpenAI-compatible endpoint needs. The
match parses the URL rather than searching the string, so a lookalike
host cannot claim the Anthropic wire, and an unparseable value keeps the
OpenAI path it had before.

The chain tag stays admin-openai: it names the slot, not the wire, and it
is persisted in user chains and pinned by the OpenAPI enum. The wire is
already visible in the instance type the wide events read.
2026-09-02 16:17:10 +02:00
Marc-André Bombeck a9055c96a4 Merge pull request #895 from MBombeck/docs/readme-thanks
docs: say thank you where people can see it
2026-09-02 16:14:57 +02:00
Marc-André Bombeck f2c7ed38a4 test(a11y): match only the visible copy of a painted marker
The login case failed with a strict-mode violation: the marker it waits
for resolved to two elements, one of them hidden. Two copies of a page
coexist for a moment during a route transition, so a bare attribute
locator can see both, and Playwright refuses an ambiguous match rather
than picking one. The run had passed on the same page code minutes
earlier, which is what a race looks like.

Four locators in this file already carry the :visible filter for that
reason. Seven did not, and had no .first() either, so every one of them
was exposed to the same failure on a slow enough runner. They carry it
now, which leaves the assertion aimed at the copy a reader would see.
2026-09-02 16:07:08 +02:00
Marc-André Bombeck 915d5dea3c Say thank you where people can see it
The contributor graph has carried every outside author correctly, because
fork pull requests are merged as merge commits and the authorship
survives onto main. But nobody reads a graph tab. The front page now
names the practice and renders the graph inline, so a first-time
contributor sees their own avatar on the page they landed on.

The avatar strip comes from a third-party renderer, the same class of
service as the four shields badges already at the top, and GitHub proxies
it so no visitor address reaches that host. It is generated rather than
hand-written on purpose: a hand-kept list is the kind of thing that goes
stale quietly.
2026-09-02 15:56:15 +02:00
Marc-André Bombeck 6cac31403b docs(changelog): record the dependency floors and the token scope 2026-09-02 15:47:14 +02:00
Marc-André Bombeck c5fc707e59 ci: scope the dependabot auto-merge write token to its job
The workflow granted contents: write and pull-requests: write at the top
level, so every step in the run held them, including the checkout and
the dependency install that execute code from the pull request being
merged. Scorecard flags the shape, and the shape is the problem: a
compromised transitive in a Dependabot branch would run with a token
that can write to the repository.

The workflow default is contents: read now, and the two write scopes sit
on the auto-merge job, which is the only job there is and the only place
they are spent. gh pr merge --auto needs contents: write to enable
merge-on-green and pull-requests: write to act on the pull request; the
major-bump comment needs pull-requests: write. The metadata fetch and
the test run need neither. Nothing about which updates merge
automatically changes.
2026-09-02 15:47:14 +02:00
Marc-André Bombeck c9f8aee476 build(docker): mirror the hono and valibot pins into /opt/prisma-cli
The image carries two installs. pnpm builds the app tree from
pnpm-workspace.yaml; npm builds /opt/prisma-cli and reads only its own
overrides field. The scan reported @hono/node-server@1.19.11
(GHSA-frvp-7c67-39w9, CVE-2026-39406) and valibot@1.2.0
(CVE-2026-59952) under that path while both packages were pinned and
clean in the app tree. Same shape as the deepmerge-ts finding, same
cause.

Rebuilt this exact install both ways to confirm rather than assume.
Without the two fields npm resolves @hono/node-server 1.19.11 and
valibot 1.2.0, which are the two versions the scan named. With them it
resolves 1.19.17 and 1.4.2, and prisma --version still reports 7.8.0.
Both arrive through prisma -> @prisma/dev.

The lockstep guard could not have caught this. Its workspace matcher
started a package name at [^"@], so every scoped key was invisible to
it: @hono/node-server was in the workspace file and absent from the
Dockerfile, the shared set never contained it, and the guard stayed
green. Scoped keys parse now, a test pins the reduction itself so the
blind spot cannot return quietly, and a second test asserts that the
three packages the image scan has actually flagged under /opt/prisma-cli
keep their npm-side mirror. Both fail when the pin is removed or moved
out of step.
2026-09-02 15:47:13 +02:00
Marc-André Bombeck f62cd59789 chore(deps): raise the stale advisory floors and pin valibot
Three overrides had drifted behind the advisories they were written for,
and the scan found the packages at versions the pins were supposed to
exclude.

dompurify moves from <=3.4.10 to <3.4.13. GHSA-55q2-fjhq-7xh7 is fixed
in 3.4.13 and the tree carried 3.4.12. The copy is jspdf's optional HTML
renderer, an optionalDependency at ^3.3.1, so the raise stays inside the
range jspdf declares.

postcss moves from <8.5.10 to <8.5.23 for CVE-2026-69153. next declares
an exact postcss@8.4.31, so nothing but this bound moves it; the build
has run on the 8.5 line since the first bump and stays there.

valibot gets a floor it never had, <1.4.2, for CVE-2026-59952. Two
copies arrive and neither is ours to call: an optional peer of
@hookform/resolvers, which this app does not use because it validates
with zod, and prisma's local dev server. 1.4.2 is the same major, so no
consumer is moved onto a new one.

@hono/node-server moves from <1.19.13 to <1.19.15 for
GHSA-frvp-7c67-39w9. The app tree already resolved 1.19.17, so this
changes nothing here; it exists so the bound states the real floor and
so the Dockerfile mirror has something correct to match.

The floor test in ci-determinism asserted the exact key and replacement
string, which meant every legitimate raise failed it while a floor gone
stale against a newer advisory passed it unchanged. It now reduces each
key to a package name and asserts the pin is at or above the fixed
version, with a case proving the comparison can return false.
2026-09-02 15:46:55 +02:00
Marc-André Bombeck c2ea07b0bc Merge pull request #891 from MBombeck/test/sharing-fence-flake
test(sharing): wait for the refusal audit row instead of guessing
2026-09-02 15:25:15 +02:00
Marc-André Bombeck 1de8634625 Merge pull request #890 from MBombeck/release/v1.38.3
chore(release): v1.38.3 — delete from the phone, name every source
2026-09-02 15:24:46 +02:00
Marc-André Bombeck 9d77120136 test(sharing): wait for the refusal audit row instead of guessing
The scope-fence test asserts that a refused section leaves a
sharing.access.denied audit row naming the reason. That row is written
without being awaited, on purpose, so the audit never delays the 403 the
caller is waiting on, and it lands some time after the response returns.
The test bridged that gap with a fixed 150 ms sleep, which a slow runner
outran: the read found an empty table and the assertion reported no
refusal, which reads exactly like the section having reached the wire,
the one thing this file exists to catch.

The positive case now polls for the row and fails with a message naming
the caller when none arrives within five seconds. The absence case keeps
a fixed wait, longer than before, because an absence claim is only worth
something if it waited. Proven by dropping the audit write behind an env
flag: eleven cases fail with the new message, and pass again with the
write restored.
2026-09-02 13:01:23 +02:00
Marc-André Bombeck 397baac818 chore(release): v1.38.3 — delete from the phone, name every source
The account-deletion fix landed after v1.38.2 was tagged, so its entry
moves out of that section and into this one where it belongs. Also in
this release: every measurement source carries a display name in all
seven languages, with a test that reads the enums out of the schema.
2026-09-02 12:29:09 +02:00
Marc-André Bombeck 71a6dd0e2a Merge pull request #889 from MBombeck/fix/source-priority-labels
fix(i18n): name every measurement source instead of showing its enum
2026-09-02 12:28:06 +02:00
Marc-André Bombeck 4918e9fd63 Merge remote-tracking branch 'origin/main' into fix/source-priority-labels 2026-09-02 12:09:58 +02:00
Marc-André Bombeck 7ee8bc8134 Fail the suite when a source enum member has no label
The four raw values in the sources ladder shipped because nothing checks
the catalogues against the enum they render. The new guard reads
MeasurementSource and IntakeSource out of prisma/schema.prisma, not out
of a copy, and fails naming every member no catalogue labels; it also
asserts the key each entry names resolves in all seven bundles, since a
key that resolves nowhere renders no better than the enum value. Run red
against the tree before the labels landed, it reported seven unlabelled
measurement sources per catalogue and one unlabelled intake source.

The schema reader now carries each enum's declared members so the guard
can read them.
2026-09-02 12:08:38 +02:00
Marc-André Bombeck 0548c0265e Label every ingest source instead of leaking its enum value
Settings, Sources listed GOOGLE_HEALTH, OURA, POLAR and STRAVA by their
internal name: the catalogue was written for seven sources and every
provider added since fell through to the raw value. The measurement list
carried the same fall-through in its source filter and its table column,
and the medication intake history read "via APPLE_HEALTH" for a dose
synced from Apple Health.

The three catalogues move into one module keyed by the enum, so an
omission is a type error rather than a raw value on screen, and the sleep
discrepancy tooltip drops the private brand-name map it had grown to work
around the gap.
2026-09-02 12:08:31 +02:00
Marc-André Bombeck 53689ee99e Merge pull request #888 from MBombeck/fix/account-delete-bearer-mfa
fix(auth): let the app delete an account that has a second factor
2026-09-02 12:08:20 +02:00
Marc-André Bombeck 101c11f85e Merge remote-tracking branch 'origin/main' into fix/account-delete-bearer-mfa 2026-09-02 11:52:34 +02:00
Marc-André Bombeck df5dd1c160 docs: publish the Bearer arm on the two erasure routes
The published contract still told a client that a Bearer token can never
clear the step-up on account deletion or the record wipe, which is what
an app generates its client from. Describe the elevation arm on both:
which factors qualify, that a password proof does not, that the proof
rides the X-Step-Up header, and that it is spent only when the erasure
runs. The 403 a narrow-scope token gets was never published either;
it is named now, ahead of the second-factor question it precedes.

The mint endpoint lists the surfaces an elevation unlocks, so both
routes join that list.

Also note on the record wipe that API tokens are on its own delete list:
a client that wipes over Bearer signs itself out, which is worth knowing
before the retry rather than after it.
2026-09-02 11:51:19 +02:00
Marc-André Bombeck 5856b2a547 auth: let a token prove a second factor for erasure
Account deletion and the record wipe both demand a fresh second-factor
proof once a factor is enrolled, and that proof lived on the session row.
A native client has no session row, so an account with TOTP or a security
key could not delete itself from the app on any request it could build:
requireFreshMfaIfEnrolled fell through to requireFreshMfa, which resolves
via getSession and answers 401 to a perfectly valid token. App Store
guideline 5.1.1(v) asks for exactly that deletion.

Add requireFreshMfaOrElevationIfEnrolled beside the cookie-only sibling
rather than softening it. Its cookie arm is the sibling's, unchanged;
its Bearer arm takes the single-use elevation the second-factor
management routes already accept, with the fresh-factor rule pinned on,
so a password-proved elevation cannot erase an account any more than a
password login satisfies the gate on the web. No factor rides the request
body: one mint surface, one redemption path. Scope stays fail-closed, so
a narrow token is refused before the header is read.

The elevation is spent immediately before the erasure, after the typed
confirmation and the last-admin check, so a rejected request does not
burn a proof against a 5-per-15-minute mint ceiling. The Bearer branch
of requireMfaManagementAuth moves into a shared helper so both gates read
and claim in the same place.

The elevation guard grows a section naming the two routes, because the
set of surfaces an elevation can unlock only stays small if adding to it
is a visible edit.
2026-09-02 11:51:09 +02:00
Marc-André Bombeck 72117104d5 Merge pull request #887 from MBombeck/release/v1.38.2
chore(release): v1.38.2 — Anthropic on current models, briefing in your language
2026-09-02 11:33:55 +02:00
Marc-André Bombeck 56ded00395 chore(release): v1.38.2 — Anthropic on current models, briefing in your language
No assistant prefill on Anthropic JSON calls, Claude 5 and Fable count as
vision-capable, the briefing cache carries its language and is never
served to a reader of another one, and job paths resolve a missing
account language to the instance default.
2026-09-02 11:10:35 +02:00
Marc-André Bombeck ad0a055fdc Merge pull request #886 from MBombeck/fix/briefing-locale
fix: never serve the briefing in another language than the reader's
2026-09-02 11:09:23 +02:00
Marc-André Bombeck a55ecc5a48 Merge origin/main into fix/briefing-locale 2026-09-02 10:51:56 +02:00
Marc-André Bombeck 718cc3568f Merge pull request #885 from MBombeck/fix/anthropic-no-prefill
fix(ai): no assistant prefill on Anthropic, Claude 5 counts as vision-capable
2026-09-02 10:51:25 +02:00
Marc-André Bombeck 7414f6e79b Note the briefing language fix in the changelog 2026-09-02 10:44:04 +02:00
Marc-André Bombeck f003b6f413 Resolve job-side locale through the operator default
Every background path that resolved a user row's locale collapsed a
NULL column to English: the nightly briefing warm, the status crons,
the period-narrative warm, reaction lines, the morning refresh, the
briefing push, coach nudges, the reminder workers, and the document and
workout summaries each carried their own copy of
`locales.includes(x) ? x : defaultLocale` or called
`normalizeLocale(user.locale)`. None consulted the instance's configured
default language, so an account that never touched the language picker
got English prose and English pushes on a German-language instance.

Add resolveJobLocale (src/lib/i18n/job-locale.ts): stored user locale
when valid, else the operator's app_settings.default_locale when valid,
else English. The settings read lives beside the other app-settings
accessors. Every job and daily path resolves through it once, where it
has the row; the template helpers keep coerceLocale for a value that is
already resolved, and queue payloads keep normalizeLocale.

The briefing push hands its resolved locale down to the digest, and the
digest to the snapshot read, so the push copy and the digest lines are
in the same language instead of two different fallbacks.

A structural test walks src/lib/jobs and src/lib/daily and fails on a
hand-rolled coercion, a validator applied to a row column, or a row
reader that does not import the helper. It was red against the previous
tree on all three counts.
2026-09-02 10:44:04 +02:00
Marc-André Bombeck ba4e34f09e Tag the briefing cache with its language and refuse a foreign one
The comprehensive-briefing cache (User.insightsCachedText) is one slot
per account with no record of the language it was written in. Every
reader served whatever was there, so a German-language account whose
nightly warm had written English kept seeing English on the dashboard
lead and the Today briefing. The request path only replaced it once the
row was a day old and the provider answered, which with a provider at
its usage limit was never.

Add User.insightsCachedLocale (migration 0335). Both writers store the
locale they generated in; the timestamp-only refresh on an unchanged
snapshot tags the row too, since the fingerprint covers the generation
locale. Every reset that nulls the text nulls the tag.

The snapshot briefing lift and GET /api/insights/generate treat a tag
that differs from the reader's locale as an empty cache: no prose, no
timestamp, the preparing / no-provider state, and the out-of-band warm
enqueued in the reader's locale through the existing path. The
generator's own short-circuit and the POST short-circuit refuse to call
a foreign-language row fresh. A NULL tag (rows written before this
change) is served as before until the next write tags it. The Today
digest derives from the snapshot and follows.

Covered by unit tests on the lift, the route and the generator, and an
integration test that writes the row through Prisma and reads the
snapshot for a reader in another language.
2026-09-02 10:44:03 +02:00
Marc-André Bombeck 7d93af9d09 fix(ai): recognise Claude 5 and Fable models as vision-capable
The Anthropic vision check listed the Claude 3 and 4 families by prefix,
so a key pinned to claude-sonnet-5, claude-opus-5 or a Fable model was
told the provider cannot read images, and lab and document OCR refused
the upload even though the model handles image and PDF blocks.

Replace the per-release prefix list with a rule: any claude-<tier>-<major>
slug from the 4 family upward, plus every claude-fable-* model, counts as
vision-capable. Claude 3 handling is unchanged. The Settings preset list
gains claude-sonnet-5 and claude-opus-5 alongside the existing entries.
2026-09-02 10:32:50 +02:00
Marc-André Bombeck a463206774 fix(ai): stop prefilling the assistant turn on Anthropic JSON calls
The Anthropic client steered JSON replies by appending an assistant turn
containing an opening brace and gluing the brace back onto the reply.
Current Claude models (the 4.6 / 4.7 / 4.8 family, Opus 5, Sonnet 5,
Fable 5 and 5.1) reject an assistant prefill with HTTP 400, so every
JSON surface on the provider (briefing, status cards, document and lab
extraction) failed for a self-hoster on a current model while plain chat
kept working.

Drop the prefill on every model. The request now carries a plain
instruction on the last user turn to reply with a single JSON object and
nothing else, and the reply is narrowed to the outermost object body via
a shared extractJsonObject helper, so a fenced or prefixed answer still
parses. The insights stripJsonFences helper delegates to the same
function rather than keeping a second copy. The tool-use path is
unchanged.

Reported independently by @sweidinger.
2026-09-02 10:28:05 +02:00
Marc-André Bombeck d5cf82fb6e Merge pull request #884 from MBombeck/release/v1.38.1
chore(release): v1.38.1 — push readings in, see the range at a glance
2026-09-01 21:26:13 +02:00
Marc-André Bombeck a2e50c761f Note the callback-notice fix and the mysql2 pin in the changelog 2026-09-01 21:00:50 +02:00
Marc-André Bombeck 05d3736d75 Resolve OAuth callback URLs on the server for integration cards
The v1.38.0 notice that warns when the configured OAuth callback origin
differs from the origin the browser is on never rendered in the published
image, and the copyable callback address in the redirect guide showed a
bare path. `integrationCallbackUrl()` read `process.env.NEXT_PUBLIC_APP_URL`
inside a "use client" module. Next.js inlines NEXT_PUBLIC_* into client
bundles at build time, and the GHCR image is built without that variable
(only the version, build-sha and built-at args reach the build), so the
base compiled to an empty string, `new URL("/api/<provider>/callback")`
threw, and the notice returned null on every card for every self-hoster.

The value now comes from the server at request time. A new map
(`src/lib/integrations/callback-urls.ts`) calls each provider's own
redirect-URI function (the four private `getRedirectUri()` helpers are
exported under provider-specific names; Polar, Oura and Strava already
exported theirs), so the page shows exactly what the handshake registers,
explicit `*_REDIRECT_URI` override included. The settings route resolves
the map and passes it as a prop through `IntegrationsSection` and
`ConnectionsPanel` to every card. Fitbit and Google Health validate their
URI and throw on a bad configuration; that surfaces as `null`, the notice
skips the comparison and the guide falls back to the fixed path.

Tests: a map test proving the explicit override wins and the derived form
is used otherwise, a component test rendering the notice from a passed
value (mismatch renders, match does not), and a structural guard that
fails when any "use client" file under src/components/settings/integrations
reads NEXT_PUBLIC_APP_URL.
2026-09-01 21:00:12 +02:00
Marc-André Bombeck 97b1603cb9 Pin mysql2 past GHSA-3f6p-5ww8-9rcr in both installs
The dependency audit went red on the release branch: mysql2 below 3.22.0
downgrades its auth plugin to mysql_clear_password and leaks the
credential. It reaches the tree only through prisma's MySQL driver, which
this app never opens, but the gate does not distinguish reachable from
present. Pinned to ^3.22.0 in the workspace overrides and mirrored with
npm's own override for the /opt/prisma-cli install, the pair the
lockstep guard holds together. The audit reads three moderates, below
the gate.
2026-09-01 20:53:47 +02:00
Marc-André Bombeck c462d9a282 chore(release): v1.38.1 — push readings in, see the range at a glance
A measurement ingest token for readings from your own hardware, a
reference-range bar beside every lab reading, lab OCR working with a
GPT-5 model, an impossible reference window no longer written to the
record, and the image build kept intact across the Prisma adapter bump.
Dependency updates ride along.
2026-09-01 20:33:30 +02:00
Marc-André Bombeck cba389515c ci: split the integration suite four ways and widen the guard
Three of the last four pushes to main failed the integration workflow
without a single failing test. Shard 1 of 3 was still logging green
results when the 25-minute job timeout cancelled it; the same tests in
the same shard had run in 13 minutes the day before. A slow runner day
doubles every test's wall time, and a guard under twice the ordinary
run cannot absorb that.

Four shards keep each slice around fifty files, and the guard moves to
40 minutes, three times an ordinary run. A wedged test still fails
through vitest's own 60-second budget, so the job timeout only has to
catch a container that never boots. The fan-in job is unchanged; it
still refuses a matrix with any cancelled shard.
2026-09-01 20:28:32 +02:00
Marc-André Bombeck 8016d375c6 Merge pull request #880 from TimonBed/lab-visual-improvement
Improve lab range and trend visual alignment
2026-09-01 19:06:09 +02:00
Marc-André Bombeck 60939475b4 Give an impossible reference window no verdict at all
A floor at or above its ceiling fell through to the one-sided branch and
was read as "minimum only", which paints a high reading green. That is
the wrong direction for a transcription error to fail in: the colour
answers a question nobody could answer from that data.

Each one-sided branch now requires the OTHER bound to be absent, so a
present-but-impossible pair lands on the neutral dot instead. It matches
lab-reference-range-bar.tsx, which renders nothing for the same input —
the two components sitting next to each other should not disagree about
what a nonsense range means.

The file had no test. It has one now, covering all five window shapes
plus the zero-width band; with the two conditions relaxed again, exactly
the two new cases fail and the four existing ones stay green.
2026-09-01 18:51:07 +02:00
Marc-André Bombeck 1cc5779282 Merge pull request #883 from MBombeck/docs/knip-triage-current
Say which knip entry is kept on purpose, and re-measure the count
2026-08-31 21:43:05 +02:00
Marc-André Bombeck 6d98a67751 Say which knip entry is kept on purpose, and re-measure the count
The production pass reports 22 files, and the comment said 21 — a small
drift, but the paragraph reads as a triage nobody has redone, so the
number is dated now and carries an instruction to re-measure.

Two things the block did not say:

The standing exception. `signals/adapters/metric-status.ts` is reported
unreachable because its only importer is its own registry-invariant test.
That is what the module is for: it projects the signal registry onto the
MetricStatusMeta shape so the test can assert the two agree field for
field. Deleting it to clear the line removes a check rather than ballast.
Someone triaging the list without that written down has to rediscover it,
and the obvious move is the wrong one.

The healed example. The false-positive slot cited a module reported
because scripts/ sits outside the tsconfig that defines the @/ alias.
It no longer appears — module and importing script both still exist, so
resolution improved under us. Replaced with the case that does hold
today, the service-worker policy that public/sw.js mirrors by hand, and
the old one kept as a note: an example that heals silently makes the
reasoning around it look wrong to whoever checks it next.
2026-08-31 21:04:22 +02:00
Marc-André Bombeck e6751f0f0c Merge pull request #882 from MBombeck/fix/transposed-reference-window-v2
Drop a reference window whose floor sits above its ceiling
2026-08-31 20:35:14 +02:00
Marc-André Bombeck 963f61cf0f Drop a reference window whose floor sits above its ceiling
A lab report's reference range reaches the record by four paths. Three of
them validate that the floor does not exceed the ceiling; the document
path did not, and the catalog store writes what it is handed. An
integration run against a real Postgres confirmed the consequence: a
100/30 pair landed on the row and on the freshly minted biomarker, so
every later reading of that analyte inherited a window that cannot be
true and a high value came back reassuring.

Dropping beats swapping. A transposed pair says the transcription is
wrong, not which of the two numbers is, and inventing an order would
state something the report never printed. The verbatim string survives
either way, so nothing the document actually said is lost.

Three points, answering according to what each one is:
- the extraction schema drops the pair, because every field there is
  catch-guarded so one bad value cannot sink a 120-fact document
- the review-screen edit refuses with the wording the lab schemas
  already use, because a person can see both numbers and fix them
- the commit path drops it as the last gate, which is what covers facts
  staged before this rule existed and confirmed afterwards

parseReferenceRange has answered a transposed PRINTED window this way
since it was written, and the commit path already counts a window it
could not read at all. This extends both to the case that was readable
and cannot be true.
2026-08-31 19:38:08 +02:00
Marc-André Bombeck a852860654 Merge pull request #881 from Antiheld86/feat/measurements-write-scope
Feat/measurements write scope
2026-08-31 16:03:44 +02:00
Antiheld86 a778acac4e chore: regenerate OpenAPI spec 2026-08-31 12:48:18 +00:00
Antiheld86 7c23b14053 Teach the arrival-wiring mock about isScopedCredential
That file stubs @/lib/api-handler wholesale, so it lists the exports it
knew about when it was written. /api/measurements now reaches for
isScopedCredential to decide source attribution and whether the sync
checkpoint may move, the mock does not provide it, and every test in the
file dies on import rather than on an assertion.

`false` is the honest stub: those cases resolve as a cookie session,
which is exactly what unscoped means, so the route takes its ordinary
path through both rules.

Checked the rest of the tree rather than fixing only the file that went
red — this is the only suite mocking that module for a route which
reaches the new export. The batch route's tests mock at a different
seam and are unaffected.

Not verified here: this environment cannot generate the Prisma client,
so that file is one of the suites which fail to import for an unrelated
reason and the fix could not be run.
2026-08-31 12:14:51 +00:00
Antiheld86 19b69dee21 Fix the B8 delegation cases to actually claim a record
Three failures in the integration run, all mine, none in the product.

The two delegation cases set the account selector as a header on the
NextRequest. Nothing reads it there. `readSelectorHeader()` resolves
through `next/headers`, which this suite mocks against the shared
`headerJar`, so the carrier came back `none` and both cases quietly
exercised the ordinary own-record path instead of the one they name. The
scoped case wrote to its own record and returned 201; the wildcard
control wrote to the caller rather than the owner. Neither was testing
delegation at all.

That is worse than a broken test. The refusal these two cover is the
regression this change could most easily have shipped in silence, and
the tests standing in front of it were not looking at it.

They now set the selector on the jar, through the exported
ACCOUNT_SELECTOR_HEADER rather than a literal, so a rename cannot
reintroduce the same gap.

The third failure is unrelated and smaller: the read-leg case read the
audit row once, racing a fire-and-forget write, and reported `undefined`
for a row about to exist. It now polls, matching B1, which carries a
comment about this exact hazard that I did not follow.

Not verified here: this environment has no Docker daemon, so the
integration suite cannot be run against a real Postgres. The diagnosis
is from the mock and the resolver, not from a green run.
2026-08-31 11:57:26 +00:00
Antiheld86 56d6fb180a Make the measurement-token mint cookie-only
The mint used requireAuth() with no scope, which refuses a narrow token
but still admits a cookie-equivalent one. The reach is not the problem —
a wildcard token can already do everything this endpoint does. The
lifetimes are: a native access token lives a day, and what it mints here
lives a year. So a credential that leaked for an afternoon could leave
behind one that outlives revoking it, and the revocation would look like
it had worked.

requireCookieAuth() closes that. It is the helper the passkey
registration and trusted-device routes already use for the same reason,
and the sharing guard recognises it as cookie-only.

The prose said more than the code did, in three places: the route header
and the OpenAPI description both claimed the endpoint "cannot mint
another token", which held only for narrow tokens, and the 403 arm
described a scope refusal that a Bearer never reaches. All three now say
what is true — no Bearer credential reaches this endpoint at any scope,
and a Bearer is refused 401 before the operator switch is read.

Tests follow the status change: the integration case asserting a scoped
token cannot mint now expects 401 rather than 403, since the refusal is
authentication and not scope, and a companion case pins the wildcard —
the credential class this change is actually about — and asserts no
token row is created.
2026-08-31 11:38:16 +00:00
Timon_bed 68a3b57597 Improve lab range and trend visual alignment 2026-08-31 11:56:54 +02:00
Antiheld86 8f61e0bc6a Plainer copy on the measurement token card
The card read like API documentation sitting in a settings page: it named
the Authorization header, spelled out both endpoint paths, and listed the
scope's limits as four clauses. None of that is what someone deciding
whether to mint a token needs, and the endpoint paths were already in the
API endpoints card immediately above it.

Rewrite to the shape the MCP connector card next door uses — a short
title, one line on what the token is for, one line saying it is shown
once, and one sentence on what it can and cannot do. Drop the endpoints
note entirely rather than rephrase it, since the card above owns that.

Say the useful consequence instead of the mechanism: readings arrive as
if entered by hand, so they can be corrected. That is the thing a person
will actually notice.

Translations were revised across all seven locales — the previous German
in particular read as translated English rather than as the rest of the
app, which uses short informal sentences.
2026-08-31 09:50:47 +00:00
Antiheld86 e79709379b Fix duplicate status keys in the new OpenAPI response blocks
`stdResponses` already carries 401, 422 and 429. The three response
blocks added with the measurements:write scope each declared their own
422 (and, on the mint route, a 429) BEFORE spreading it, so the generic
wording overwrote the specific wording and TypeScript refused the
duplicate key. The build failed at auth.ts with "'422' is specified more
than once".

Move the explicit keys after the spread, which is what the MCP mint next
door already does and the only order in which a per-route description
survives.

Worth stating because the failure mode is quiet: had TypeScript allowed
it, the published contract would simply have carried "Request validation
failed" everywhere instead of naming
measurement.create.source_not_permitted and its siblings.
2026-08-31 09:22:38 +00:00
Antiheld86 cba7a0fce5 Add a self-service measurements:write API token scope
Since v1.30.17 there has been no self-service path to a token that can
write a measurement. That release made the Bearer scope default
fail-closed, which closed a real privilege-escalation hole, and removed
the generic mint at POST /api/tokens along with it. The generic mint had
been the only way to get a token that could reach /api/measurements, so
a local sensor pushed through Home Assistant or Node-RED lost its door
while the OAuth integrations kept theirs.

Add a narrow scope accepted by exactly two routes, both writes, both on
the holder's own record.

The scope constant is a leaf module beside the surface that consumes it,
matching FHIR_READ_SCOPE and the MCP scopes. requireRecordAuth grows an
options object rather than a sibling function, because the sharing
surface guard keys every leg on that one identifier and a second name
would mean two copies of the delegable declaration. AuthContext carries
the admitting scope as a single nullable string rather than the token's
permission array, so nothing downstream can re-derive an authorisation
decision from it.

A scoped credential is refused a record selector before any grant is
read. Placing the refusal above the sharing check rather than beside it
means no future widening of what a grant permits can reach one of these
tokens.

Rows are attributed MANUAL. An entry that explicitly names APPLE_HEALTH
is refused 422 rather than relabelled: that source is half the
(userId, type, source, externalId) dedup key the iOS client writes into,
it participates in the cross-source merge, and it gates the HealthKit
sync fields. For the same reason a scoped write no longer advances
User.lastSyncedAt, which the phone reads to size its undelivered window.

Also closes a narrower gap found while building this. The idempotency
wrapper resolved a replayed delegated response against a live grant
without considering which credential was presenting it, so a cached
response about a shared record could be returned to a token the handler
itself would refuse. No write was reachable that way; the response body
was.

Guards: T3 gains the mint site, T4's vocabulary gains the scope and
learns to read the requireRecordAuth form (without which this change
would open a way to widen a route that the closed vocabulary could not
see), and a new T5 freezes the set of delegable routes naming a scope.
The sharing surface guard's AST matcher reads only the first two
arguments, so it needed prose but no code.
2026-08-31 08:46:16 +00:00
Marc-André Bombeck 4308114c5b Merge pull request #879 from MBombeck/fix/lab-outlier-range-assertion
test(labs): assert the outlier's distance from the edge, not one string
2026-08-31 00:22:15 +02:00
Marc-André Bombeck 5e89a201f7 test(labs): assert the outlier's distance from the edge, not one string
Follow-up to #860, promised in review rather than asked of the
contributor. `not.toContain("left: 4%")" passes for a marker at 4.02%,
which is the same defect one rounding away, so the test now reads the
marker position and asserts it sits inside the padding at both ends.

EDGE_PADDING_PERCENT moves to module scope and is exported, so the
assertion uses the number the component clamps with instead of a copy
that can drift. It was being reallocated on every render besides.

Verified by mutation: dropping the outlier expansion puts the marker at
exactly 4 and turns this test red.
2026-08-31 00:06:50 +02:00
Marc-André Bombeck 7cca0a0710 Merge pull request #860 from TimonBed/feat/labs-ocr-openai-fix
rework of range bar ind lab list
2026-08-31 00:04:14 +02:00
Timon_bed f30a202a67 fix: keep lab outliers clear of range bar edges 2026-08-30 23:45:47 +02:00
Marc-André Bombeck b1d6765790 Merge pull request #875 from MBombeck/dependabot/npm_and_yarn/vitejs/plugin-react-6.1.0
chore(deps-dev): bump @vitejs/plugin-react from 6.0.4 to 6.1.0
2026-08-30 22:24:11 +02:00
Marc-André Bombeck 78921399fb Merge pull request #877 from MBombeck/dependabot/npm_and_yarn/radix-ui-1.6.7
chore(deps): bump radix-ui from 1.6.2 to 1.6.7
2026-08-30 22:07:32 +02:00
Marc-André Bombeck e7d40e22b0 Merge pull request #876 from MBombeck/dependabot/npm_and_yarn/lucide-react-1.34.0
chore(deps): bump lucide-react from 1.27.0 to 1.34.0
2026-08-30 22:05:58 +02:00
Marc-André Bombeck 68f33dad5f Merge pull request #874 from MBombeck/dependabot/npm_and_yarn/next/bundle-analyzer-16.3.3
chore(deps-dev): bump @next/bundle-analyzer from 16.3.1 to 16.3.3
2026-08-30 22:00:18 +02:00
Marc-André Bombeck 0be1663989 Merge pull request #873 from MBombeck/dependabot/npm_and_yarn/hookform/resolvers-5.9.1
chore(deps): bump @hookform/resolvers from 5.4.0 to 5.9.1
2026-08-30 21:58:27 +02:00
Marc-André Bombeck a4b2a1541d Merge pull request #872 from MBombeck/fix/pg-runtime-dependency
fix: declare pg as the runtime dependency it already was
2026-08-30 21:57:26 +02:00
dependabot[bot] c532f60c57 chore(deps): bump radix-ui from 1.6.2 to 1.6.7
Bumps [radix-ui](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/radix-ui) from 1.6.2 to 1.6.7.
- [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/radix-ui/CHANGELOG.md)
- [Commits](https://github.com/radix-ui/primitives/commits/1.6.7/packages/react/radix-ui)

---
updated-dependencies:
- dependency-name: radix-ui
  dependency-version: 1.6.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-30 19:17:23 +00:00
dependabot[bot] 07b32617d2 chore(deps): bump lucide-react from 1.27.0 to 1.34.0
Bumps [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) from 1.27.0 to 1.34.0.
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.34.0/packages/lucide-react)

---
updated-dependencies:
- dependency-name: lucide-react
  dependency-version: 1.34.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-30 19:02:53 +00:00
dependabot[bot] 098cc9d5d4 chore(deps-dev): bump @vitejs/plugin-react from 6.0.4 to 6.1.0
Bumps [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) from 6.0.4 to 6.1.0.
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react)

---
updated-dependencies:
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-30 19:02:16 +00:00
dependabot[bot] 5898742fa3 chore(deps-dev): bump @next/bundle-analyzer from 16.3.1 to 16.3.3
Bumps [@next/bundle-analyzer](https://github.com/vercel/next.js/tree/HEAD/packages/next-bundle-analyzer) from 16.3.1 to 16.3.3.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/commits/v16.3.3/packages/next-bundle-analyzer)

---
updated-dependencies:
- dependency-name: "@next/bundle-analyzer"
  dependency-version: 16.3.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-30 19:01:40 +00:00
dependabot[bot] 2e6e133409 chore(deps): bump @hookform/resolvers from 5.4.0 to 5.9.1
Bumps [@hookform/resolvers](https://github.com/react-hook-form/resolvers) from 5.4.0 to 5.9.1.
- [Release notes](https://github.com/react-hook-form/resolvers/releases)
- [Commits](https://github.com/react-hook-form/resolvers/compare/v5.4.0...v5.9.1)

---
updated-dependencies:
- dependency-name: "@hookform/resolvers"
  dependency-version: 5.9.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-30 19:00:56 +00:00
Marc-André Bombeck b4c18d131a Merge pull request #871 from MBombeck/fix/codeql-action-4.37.9
ci: move every codeql-action pin to v4.37.9 in one commit
2026-08-30 20:50:25 +02:00
Marc-André Bombeck 9f07a46633 fix: declare pg as the runtime dependency it already was
The Dockerfile asserts that the standalone image can resolve pg, because
pg-boss loads it through native Node resolution. That assertion has been
passing on a coincidence: pg sat in devDependencies, and the version our own
entry pinned happened to match the one @prisma/adapter-pg pulled in, so both
names resolved to a single copy in the store and Next's file tracer packed it
whole.

Bumping the adapter to 7.10.0 moves its transitive pg to 8.23.0 while ours
stayed at 8.22.0. The tracer packs only the copy the adapter reaches, the
top-level link points at the other one, and the image fails to build on both
architectures:

    Error: Cannot find module '/app/node_modules/pg/lib/index.js'

Move pg into dependencies at ^8.23.0. The lockfile now carries one pg version
instead of two, so the two resolutions cannot drift apart again on the next
adapter release. Carries the adapter bump from #865, which cannot build alone.
2026-08-30 20:49:46 +02:00
Marc-André Bombeck eb49580271 Merge pull request #868 from MBombeck/dependabot/npm_and_yarn/zod-openapi-6.0.1
chore(deps): bump zod-openapi from 6.0.0 to 6.0.1
2026-08-30 20:47:35 +02:00
Marc-André Bombeck 95a75cd9e0 Merge pull request #862 from MBombeck/dependabot/npm_and_yarn/knip-6.32.3
chore(deps-dev): bump knip from 6.32.2 to 6.32.3
2026-08-30 20:47:27 +02:00
Marc-André Bombeck 314f35b2ee ci: move every codeql-action pin to v4.37.9 in one commit
init, analyze and upload-sarif are the same release pinned in three
workflows. Dependabot opened them as three separate pull requests, so each
run mixed two versions and analyze rejected the config init had written:
"Loaded a configuration file for version 4.37.7, but running version
4.37.9". None of the three could go green alone, and the code-scanning
analysis stayed red while they waited on each other.

Bump all five references together and group the action in dependabot.yml so
the next release arrives as one pull request.
2026-08-30 20:20:31 +02:00
Marc-André Bombeck 58de37cf52 Merge pull request #869 from MBombeck/dependabot/npm_and_yarn/simplewebauthn/server-13.3.3
chore(deps): bump @simplewebauthn/server from 13.3.2 to 13.3.3
2026-08-30 20:19:17 +02:00
dependabot[bot] e87d44952c chore(deps-dev): bump knip from 6.32.2 to 6.32.3
Bumps [knip](https://github.com/webpro-nl/knip/tree/HEAD/packages/knip) from 6.32.2 to 6.32.3.
- [Release notes](https://github.com/webpro-nl/knip/releases)
- [Commits](https://github.com/webpro-nl/knip/commits/knip@6.32.3/packages/knip)

---
updated-dependencies:
- dependency-name: knip
  dependency-version: 6.32.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-30 18:16:04 +00:00
Marc-André Bombeck d67115b115 Merge pull request #867 from MBombeck/dependabot/npm_and_yarn/node-rs/argon2-2.1.0
chore(deps): bump @node-rs/argon2 from 2.0.2 to 2.1.0
2026-08-30 20:12:57 +02:00
Marc-André Bombeck 2326ca585b Merge pull request #861 from TimonBed/feat/openai-ocr-only
fix: fixes ocr for newer open ai models
2026-08-30 20:02:24 +02:00
Marc-André Bombeck fe0c248d5c Merge pull request #864 from MBombeck/release/v1.38.0
chore(release): v1.38.0 — the score works with the record you keep
2026-08-30 18:50:21 +02:00
Timon_bed d1251634b3 prettier fix 2026-08-30 18:07:19 +02:00
Timon_bed 34e37fe850 prettier fix 2026-08-30 18:01:47 +02:00
dependabot[bot] a425cf58bf chore(deps): bump @simplewebauthn/server from 13.3.2 to 13.3.3
Bumps [@simplewebauthn/server](https://github.com/MasterKale/SimpleWebAuthn/tree/HEAD/packages/server) from 13.3.2 to 13.3.3.
- [Release notes](https://github.com/MasterKale/SimpleWebAuthn/releases)
- [Changelog](https://github.com/MasterKale/SimpleWebAuthn/blob/master/CHANGELOG.md)
- [Commits](https://github.com/MasterKale/SimpleWebAuthn/commits/v13.3.3/packages/server)

---
updated-dependencies:
- dependency-name: "@simplewebauthn/server"
  dependency-version: 13.3.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-30 15:56:00 +00:00
dependabot[bot] 89b630060d chore(deps): bump zod-openapi from 6.0.0 to 6.0.1
Bumps [zod-openapi](https://github.com/samchungy/zod-openapi) from 6.0.0 to 6.0.1.
- [Release notes](https://github.com/samchungy/zod-openapi/releases)
- [Changelog](https://github.com/samchungy/zod-openapi/blob/master/CHANGELOG.md)
- [Commits](https://github.com/samchungy/zod-openapi/compare/zod-openapi@6.0.0...zod-openapi@6.0.1)

---
updated-dependencies:
- dependency-name: zod-openapi
  dependency-version: 6.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-30 15:55:30 +00:00
dependabot[bot] b16f5f9947 chore(deps): bump @node-rs/argon2 from 2.0.2 to 2.1.0
Bumps [@node-rs/argon2](https://github.com/napi-rs/node-rs) from 2.0.2 to 2.1.0.
- [Release notes](https://github.com/napi-rs/node-rs/releases)
- [Commits](https://github.com/napi-rs/node-rs/compare/@node-rs/argon2@2.0.2...@node-rs/argon2@2.1.0)

---
updated-dependencies:
- dependency-name: "@node-rs/argon2"
  dependency-version: 2.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-30 15:55:00 +00:00
Marc-André Bombeck f71b0142a8 chore(release): v1.38.0 — the score works with the record you keep
Three areas of health become a recommendation rather than a gate. A one
or two area record now scores, the card says what the number rests on,
and refusal narrows to the one honest case: nothing scoreable yet.

Carries the composition notice, the reference-citation guard that keeps
invented targets out, @TimonBed's OAuth callback warning, and the fix
for a geometry check that had never measured in CI.
2026-08-30 17:54:02 +02:00
Marc-André Bombeck 28af7c13d3 Merge pull request #859 from MBombeck/feat/health-score-target-guards
feat: pin the rule that keeps invented targets dead
2026-08-30 17:50:57 +02:00
Timon_bed 6ab3b02935 fixes ocr for newer open ai models 2026-08-30 17:37:52 +02:00
Marc-André Bombeck b4ebd6ffce test: drop the fixture's unused module-path export
The constant was left over from an earlier shape of the guard, which
located the fixture by path before it imported it directly. Nothing reads
it now, and the dead-code gate says so.
2026-08-30 17:33:07 +02:00
Timon_bed de9a16b69d rework of range bar ind lab list 2026-08-30 17:24:46 +02:00
Marc-André Bombeck f29995a18c docs(api): correct the score descriptions the adaptive rule outdated
Three descriptions in the OpenAPI registry still describe the floor that
v1.38 removed, and one of them contradicts its own error-response
description two dozen lines below it.

- The score-config PATCH still said the write is refused below three
  distinct areas and one physical measurement. The route refuses the
  empty selection and nothing else; its 422 description already said so.
- The dashboard snapshot's healthScore still said the block is null until
  three eligible domains include a physiological one. It is null only
  when no pillar is readable at all.
- The pillar domain field still pointed at a three-distinct-domains rule
  that no longer exists, where what a client needs to hear is that domain
  count comes resolved on scoreBasis and must not be counted out of
  composition.

Regenerated docs/api/openapi.yaml.

The user-facing description of the score lives in the docs site's own
repository, not here; nothing under docs/ describes the composite.
2026-08-30 17:08:39 +02:00
Marc-André Bombeck 81be61b6d1 fix(seed): give the demo every area of health the score can span
The demo seeds no waist measurement and no wellbeing screener, so two of
the seven pillars have never had data and the score rests on three areas
instead of five. Adiposity and wellbeing render as empty rows on the card
that is meant to show the feature.

Both are seeded now: a fortnightly waist that walks 96 cm down to 88 cm
over the window (0.527 to 0.484 at the demo profile's height, so the
ratio crosses NICE 2022's threshold inside the seeded span rather than
sitting flat green), and six WHO-5 / PHQ-9 / GAD-7 administrations with
their item answers encrypted the way the check-in route writes them, each
with the COMPUTED projection measurement so the history view and the
trend chart agree. Totals sit in the calm bands and item 9 is answered
zero throughout, which also keeps the pillar clear of its
crisis-signposting arm.

Verified against a throwaway Postgres: before, five ok pillars over three
areas; after, seven over five, tier full.

The dates were never the problem. Every timestamp the seed writes is
already relative to the run, and the header says so. What ages is the
seeded DATA — the pillar windows keep moving after a seed, so four weeks
on, activity and sleep fall out of theirs and the score narrows to
whatever cardiometabolic data is still fresh. Since v1.38 that is a
labelled partial score rather than a blank card, but it is still not the
demo at its best, and the header now says that too.
2026-08-30 17:08:29 +02:00
Marc-André Bombeck d98d714ee7 feat(score): pin the rule that keeps invented targets dead
The score once graded weight against 22 x height squared, widened by 2 kg
either side: a band nobody set, no surface named, and the only producer
of that pillar's verdict. v1.34 removed it and the composite rebuild left
a pillar set where every scored band cites somebody. Nothing but review
has kept it that way since, and review is what let the original in.

So the rule is written down. PillarReference.kind becomes a runtime list
carrying the reason there is no fourth kind, reference.source is
documented as a citation a reader could go and look up, and a guard
beside the pillars checks all seven modules three ways.

The arm worth arguing about is the second. An invented target is a
continuous function of a profile field; a guideline band is a step
function into a published table. So the guard sweeps every pillar across
a matrix of heights and ages and requires the scored bands it emits to
land inside a small enumerated set transcribed from the guideline that
pillar cites. No finite enumeration can hold a per-person curve, which is
what makes the arm able to fail rather than merely able to pass. The
other two arms cover the citation string and freeze which pillar may read
which profile field, with the reason written beside it and stale entries
failing as loudly as missing ones.

The proof is in the file: the pre-v1.34 weight target is restored as a
fixture in today's shape and each arm is shown refusing it.
2026-08-30 17:08:16 +02:00
Marc-André Bombeck a2a743c9e1 Merge pull request #858 from MBombeck/feat/health-score-composition-notice
feat: the score says when a pillar stopped counting
2026-08-30 16:42:42 +02:00
Marc-André Bombeck 58701706db Merge pull request #857 from MBombeck/fix/geometry-guard-must-measure
fix: the geometry guard has never measured in CI
2026-08-30 16:42:27 +02:00
Marc-André Bombeck e4880dcdc1 feat: the score says when a pillar stopped counting
A pillar can leave the set behind the number without anybody choosing it:
a window rolls past its floor, a module goes off, a source goes quiet. The
delta already refuses to narrate that as a health event, which stops a
false "you dropped six points" and puts nothing in its place. The level
moves, the panel shows a different number, and the cause is nowhere on the
surface. Under the adaptive minimum this matters more rather than less,
because compositions are smaller now and sit closer to their floors.

The report carries `compositionNotice` when today's set differs from the
last local day the account has a stored score for. Optional and nullable,
the additive shape the score's wire has used six times, so a payload
cached before it existed stays valid. It names what left and what joined
as pillar ids; the surfaces already own the labels, and the reason a
departed pillar stopped counting comes from that pillar's own row in the
same report rather than from a second vocabulary.

Two changes deliberately do not raise it. A method move and a recipe
change each already have their own note, and telling someone twice about
one event teaches them to ignore both.

The key is `health-score:v<version>:composition:<hash of the sorted set>`
and rides the existing dismissed-item ledger, so a dismissal holds until
the set moves again rather than until tomorrow. The read excludes today on
purpose: the row for today is written by the same request that computed
the report, so comparing against the newest row would find today's own
composition on the second load of the same page and the note would vanish
between two views of it.

This gives `HealthScoreRecord` its first production reader. Since it
shipped it has been written on every scored read and consumed by nothing
but backup and restore, which is the write-only shape the contributor
notes call a liability and which nothing in the gate can notice, because
every check proves one end. The round trip is proved against real
Postgres: raise the note, wipe the table, restore it through the admin
route, get the same note back, and hold the dismissal across it.

Rendering is one muted line on the score card and a card of its own on the
settings page, beside the recipe note rather than inside it. Deliberately
not a push.

Four fake Prisma clients gain the new read. They are doubles of a client
the reader really does call now; leaving them short and guarding the call
site instead would have been a shim for a caller that does not exist.
2026-08-30 16:16:57 +02:00
Marc-André Bombeck 624432b3fe Merge pull request #855 from TimonBed/fix/withings-dev-redirect-uri
Shows warning for misconfigured callback urls
2026-08-30 15:59:17 +02:00
Marc-André Bombeck 88750e0048 fix: give the geometry check a browser and stop it skipping in CI
The hero-geometry check has never measured anything in CI. It launches
Chromium in a hook, catches the launch failure, and every case then
returns early — green. The quality job installs no browsers, so every
run of it since the file landed printed

  [hero geometry] SKIPPED — no Chromium build available (Error:
  browserType.launch: Executable doesn't exist at
  /home/runner/.cache/ms-playwright/chromium_headless_shell-1234/ch)

and passed. The file's own header warned about exactly this trap and
then fell into it.

Both ends move. The quality job installs the headless shell before the
unit suite — `--only-shell chromium`, because that is the build
`chromium.launch()` resolves to and the one the failing runs named, with
a cache on the lockfile hash so the download is paid once. And the check
now refuses to be optional: with CI set, a launch failure throws out of
the hook and fails the suite with the step to restore. Without CI it
still skips, through the test context so the skip and its reason land in
the report rather than in a console line nobody reads.

No panel number changed. The measurements the check reads back are the
same ones the reserve was set against: panels of 400 / 428 / 456 / 484
px for three to six rows, 420 px for three rows plus the basis line,
against a 448 px reserve.
2026-08-30 15:55:46 +02:00
Marc-André Bombeck 6c4fa2f484 i18n: translate the callback mismatch notice into the remaining five locales
The key shipped with the English sentence in es, fr, it, pl and ko, which
the English-leak guard catches by design: a value byte-identical to the
English one for a multi-word string is a forgotten translation, and that
guard exists because this project has shipped exactly that before.

Nobody sending a two-line fix should have to produce seven languages.
2026-08-30 15:41:45 +02:00
Marc-André Bombeck 319a75b02f Merge pull request #856 from MBombeck/feat/health-score-basis-surfaces
feat: the score says how much of the record it rests on
2026-08-30 15:40:09 +02:00
Marc-André Bombeck 59ccf5be2a feat: say how much of the record the score rests on
Two areas of health score now, and one does. The arithmetic is the same
at every breadth, so nothing on the web surfaces distinguished a number
resting on blood pressure alone from one resting on five areas. The
panel now states its scope.

The basis line. Below the recommended breadth the card renders "Based on
{n} of 3 areas of health" under the band sentence, in the same weight,
and stops there. It stands where the learning gate used to stand for
those accounts, which is what the gate was for before the refusal moved.
The number keeps its size and its band colour at every tier, there is no
warning glyph, no second colour, no apology: the coverage meter and the
confidence band underneath already do the quantitative caveat work, and
the composition list names the areas one tap away. At full breadth the
line says nothing, because a fraction that reads "3 of 3" (or "4 of 3" —
the block counts domains, the recommendation caps at three) is not a
label. The daily hero carries the same sentence beside its ring, in the
hero's quiet tier, because the ring shows a number and nothing else.

The gate survives for the one case that is still a refusal: not a single
pillar readable. Its copy stopped claiming the score needs three areas
and stopped counting them — above zero there is a score now, and the
meter below renders the fraction anyway.

The coverage axis. "Covers the three areas the score needs" was false
the moment three stopped being needed, and the branch that chose it was
worse: it asked whether a score exists, so a two-area account would have
been told it covers the three areas the score recommends — the old lie
one floor up. The branch is the breadth tier now. Full breadth states
the recommendation; everything narrower shows the fraction, which since
this release is a real moving number rather than a floor every scored
account cleared by definition. The key was renamed off "minimumMet"
because there is no minimum left to name.

Settings names the recommendation rather than a requirement: three areas
is what the score recommends, a selection with one pillar saves, and a
narrower score is worked out the same way.

Copy lands in all seven catalogues.

Tests: the axis guard gains a third claim, rendered rather than read out
of the source — the real panel at each tier, including the two-area arm
that was unreachable for a scored account until now. The card gains a
partial-score block comparing the headline number's markup byte for byte
against a full-breadth render, so "renders the same" is asserted where
it can actually break, plus the counter-case that a refusal still gets
the gate and nothing else. The hero strip proves the sentence reaches
the band, not only the component. The geometry reserve was re-measured
with a browser rather than widened: a three-row panel carrying the basis
line lands at 420px, inside the 400-484px range the reserve brackets, so
the declared minimum is unchanged and the narrow shape is now measured.
2026-08-30 15:21:39 +02:00
Timon_bed 8bec82b551 placeholders 2026-08-30 15:10:48 +02:00
Timon_bed 3453bfe101 fix: warn about mismatched OAuth callback URLs 2026-08-30 15:00:24 +02:00
Marc-André Bombeck 320788a984 Merge pull request #854 from MBombeck/feat/health-score-adaptive-eligibility
feat: the health score adapts to the data a person actually has
2026-08-30 14:59:29 +02:00
Marc-André Bombeck 9306fa3a21 test: the two-domain case grades instead of going dark
This integration test pinned the three-domain floor from the other side
of the wire: two graded pillars in two areas, composite insufficient.
That is the defect the milestone removes, so the assertion inverts and
now reads the partial tier and its basis out of the serialised response,
which is the only place a client would ever see it.

It survived the unit suite because integration tests run under their own
command; the model change was green everywhere the model is unit-tested
and red at the one place that exercises the route end to end.
2026-08-30 14:40:43 +02:00
Marc-André Bombeck 61110b635c test(score): turn the eligibility pins from a floor into a tier
Six suites pinned the old rule as the rule. Each inversion, and why it is
one:

`breadth.test.ts` — the case table asserted a refusal reason per set; it
asserts a tier and a `physiological` flag now. Every row in it except the
empty set used to be a refusal, and each is a number somebody gets to see.
Adds the tier boundaries (one pillar, two areas, physiological-absent), a
case proving the same pillars produce the same number at `partial` and at
`full`, and a block whose only job is the counter-case: the empty verdict
still carries a reason and no tier, and a composite whose selected pillars
all came back short still refuses with `no_usable_data`. A rule that has
stopped refusing anything is a deleted rule, not a graded one.

`composite.test.ts` — "requires three domains and one measured
physiological domain" asserted the refusal that no longer happens; it now
asserts the score and the basis block on the same fixture. The coverage
case keeps its fixture and its arithmetic and flips its outcome: two of
three used to be a refusal and is a scored account with a real coverage
fraction. Adds the one-area case and the zero-pillar counter-case, and the
`SCORE_VERSION` floor moves 2 -> 3 because widening who gets a score is
exactly the kind of change that must not ship without a version bump.

`record.test.ts` — "records nothing when the composite did not resolve"
used a two-pillar fixture to prove a below-the-floor day stored nothing.
That day has a number now and the table has to keep it, or an account that
starts narrow and widens later has a hole where its early days were. The
assertion is now that a one-pillar day builds a draft AND reaches the
database; the absence case survives on the fixture that genuinely produces
no score.

`composition-source.test.ts` — three recipes asserted as refused at read
time. Two of them score. What the block proves is unchanged — the reader
publishes the shared rule's verdict on the reader's own resolved set, so a
second copy of the rule would still surface here — but the agreement is
over a tier rather than over a refusal.

`route.test.ts` (score config) — the two too-narrow refusals become
acceptances, because a write that refuses what the read is willing to serve
is the two layers disagreeing. The empty selection keeps its 422 and gains
the assertions the old cases carried: errorCode, reason, and the sentence.
The errorCode driver loses the two selections that no longer 422.

`score-refusal-consumer-guard.test.ts` — its non-zero control anchored on
`three_domains_required`; it anchors on `no_pillars_selected`.

New: `health-score-basis-additive-contract.test.ts` pins that `scoreBasis`
is published, is optional on all three carriers, and points at the one
shared component — a required field on a cached surface would invalidate
every cached payload with nothing failing anywhere. It also pins that the
walk does not confuse the composite's basis with the older per-pillar
`scoreBasis` that blood pressure uses for its axis, since they share a key.

Fixtures: the notice-key assertions derive the method half from
`SCORE_VERSION` rather than restating 3. Three fixtures that named
`three_domains_required` now name `no_usable_data`, a reason the server can
still emit. The settings e2e drove its refusal through a two-pillar
selection that now succeeds; it deselects every pillar instead.
2026-08-30 14:16:33 +02:00
Marc-André Bombeck aadc3a8e89 feat(api): carry the score's basis on every surface that carries the score
`scoreBasis` rides the composite, the dashboard snapshot's flattened hero
block and the daily digest's score. It says how many distinct areas of
health the number counted, how many the method recommends, which tier that
lands in, and whether any counted pillar was a physiological measurement.

Optional everywhere, because two of the three surfaces are served out of a
cache and a payload written before this release cannot grow a field. The
snapshot and digest blocks have taken six additive fields this way already;
this is the seventh.

Resolved on the server for the same reason `configured` is. Counting
`composition` client-side would get it wrong more often than right — three
of the seven pillars share the cardiometabolic area, so a three-pillar
score can rest on one.

One shared component, `HealthScoreBasis`, declared once in the insights
schema module and referenced from the other two registry modules, rather
than three inline copies that drift the first time the block gains a field.
Declared through the assigning `.meta()` form: a bare `.meta()` statement
registers an instance nothing references, and the id then never becomes a
component.

The composite's `insufficient` reason narrows to the single value
`no_usable_data` and says so in the published description. That field is an
open string in the document, so the change is additive on the wire even
though the value space shrank.

The score-config 422 description drops the two retired reasons and states
plainly that the empty selection is now the only refusal, so a client does
not keep a three-area rule of its own in front of a write that no longer
has one.
2026-08-30 14:16:06 +02:00
Marc-André Bombeck 4ad00406d3 feat(score): compute a health score from the data a person actually has
Three distinct areas of health stops being the price of admission and
becomes what it always described: a recommendation. `evaluateScoreBreadth`
returns a tier instead of a pass/fail — `full` at three areas or more,
`partial` at two, `minimal` at one — and refuses only when not one pillar
came back usable, with the reason `no_usable_data`.

The arithmetic does not change with the tier. Same mean, same worst-pillar
band drag, same noise floor. A one-area score of 82 is an honest 82 that
rests on one area, and discounting it for the pillars somebody does not
track would have been a new invented target, which is the thing this score
spent two releases removing.

The physiological requirement becomes a labelling fact rather than a veto.
An account whose only readable pillar is activity or wellbeing gets its
number with `physiological: false` on the basis block; the old refusal told
that person nothing they could not already see.

`SCORE_MIN_ELIGIBLE_DOMAINS` is now `SCORE_RECOMMENDED_DOMAINS` and still
feeds `deriveCoverage`, so the coverage fraction and the confidence blend
keep telling the truth with no new machinery: a one-area score lands at low
confidence through the path that was already there. The fraction used to be
a floor every scored account had cleared; it is a real moving number now.

`SCORE_VERSION` 3 -> 4 and `SCORE_ALGORITHM_CHANGED_AT` moves to the
release date. Both are method-identity duties: deltas suppress as
`algorithm_changed` across the straddle window, the notice key rotates so
each account is told once, and stored days stamp 4. No v3 row is rewritten
and no v3 number changes meaning.

The settings write follows the same rule rather than a stricter one. It
refused two-area and non-physiological selections on the ground that they
could not produce a score; they can, so refusing the write would be the two
layers disagreeing about the one question they share. The empty selection
is still refused, under a single reason `no_pillars_selected`, and the seven
message catalogues trade the two old refusal sentences for one.

Also fixes the stale `./series.ts` reference in the config header — that
module was deleted as dead in v1.35; the columns the sentence describes are
still written by `./record.ts`.
2026-08-30 14:15:47 +02:00
Marc-André Bombeck f0ccd9db38 Merge pull request #853 from MBombeck/release/v1.37.33
chore(release): v1.37.33 — a community day
2026-08-29 20:03:54 +02:00
Marc-André Bombeck 921e0bc81f chore(release): v1.37.33 — a community day
A contributor's first code fix, a self-hoster's Tailscale recipe turned
into documentation on both doc sites, the repeating admin geo notice
anchored to configuration state, the notification HTML stripper made
structural, and the code-scanning backlog triaged to zero untreated
findings.
2026-08-29 19:46:56 +02:00
Marc-André Bombeck b908d53b5f Merge pull request #852 from MBombeck/fix/scanning-triage-and-geo-notice
fix: scanning triage follow-ups and the repeating geo notice
2026-08-29 19:44:49 +02:00
Marc-André Bombeck ba3cf30035 Override flatted, js-yaml and minimatch past their advisories
- flatted 3.3.3 → 3.4.4: prototype pollution and unbounded recursion in
  parse(), fixed in 3.4.2 / 3.4.0.
- js-yaml 4.1.1 → 4.3.1: quadratic CPU on merge-key chains and !!omap
  resolution. The override is bounded to >=4.0.0 so a hypothetical 3.x
  consumer is never dragged onto a new major.
- minimatch 3.1.3 → 3.1.5: ReDoS via nested extglobs. The scanner
  suggested 10.x, but the fix is backported — only <3.1.4 is vulnerable —
  so the 3.x line stays where its consumers (eslint) expect it. The 5.x,
  9.x and 10.x copies in the tree were never affected.

The refreshed lockfile also carries brace-expansion 1.1.12 → 1.1.18
transitively, which clears that package's DoS advisories. pnpm audit
reports none of these packages afterwards.
2026-08-29 19:21:00 +02:00
Marc-André Bombeck bed7278e78 Pin the Prisma CLI install to exact versions
The /opt/prisma-cli npm install named prisma@7.8 and @prisma/engines@7.8
while its neighbours (tsx, dotenv) were exact — the one unpinned spot the
Scorecard pinned-dependencies probe flagged. Both ranges resolve to 7.8.0
today, so the exact pin changes nothing in the built image; it only stops
a future 7.8.x from arriving unreviewed.

Resolves Scorecard alert 63.
2026-08-29 19:20:59 +02:00
Marc-André Bombeck dd46bbbd60 Make the spacing-scale modifier-chain regexes linear
Both class-string regexes carried (?:[^\s"']*:)* for the optional
modifier prefix chain. The inner class includes the colon, so the star
could carve the same prefix into chunks many ways, and a long
non-matching string made the engine try them all — exponential
backtracking (CodeQL alert 44, js/redos). Excluding the colon from the
chunk class accepts exactly the same strings with one parse each. The
rule's 35 tests pass unchanged.

Resolves CodeQL alert 44.
2026-08-29 19:20:58 +02:00
Marc-André Bombeck 347e14d26b Centralise notification HTML stripping behind one hardened helper
Five senders (APNs, Web Push, webhook, ntfy, email) each carried their
own single-pass replace(/<[^>]*>/g, "") — the shape CodeQL flags as
incomplete multi-character sanitization, because a removal can re-form
the pattern it removed. Whether one particular regex happens to be
idempotent is an argument about that regex; five copies of the argument
is how the next edit quietly breaks one of them.

The shared stripHtml re-applies the strip until the string stops
changing, with an iteration cap and a bracket-dropping fallback so no
tag-shaped sequence can survive any input. Plain text passes through
unchanged, same as before. Unit tests pin the nested-tag bypass shapes
and the no-surviving-tag invariant.

Resolves CodeQL alerts 38-42.
2026-08-29 19:20:42 +02:00
Marc-André Bombeck 511ddf5de1 Send the offline-geo admin notice once per configuration state
The sent-latch was a module-level boolean, so every worker boot re-sent
the same notice while the host's configuration never changed (#851).

Anchor the notice in the notification_events ledger instead, through the
same claimNotificationEvent helper the reminder schedulers use. The
anchor is unwindowed: entering the unconfigured state sends once per
admin, staying in it is silent across any number of restarts, and the
anchor is released when the state exits — databases configured, or
IP_GEO_LOOKUP_DISABLED set — so a genuine re-entry notifies again.

Three consequences worth naming:

- A host with lookups disabled is no longer notified at all. With no
  egress there is nothing the notice warns about, and the disabled state
  counts as an exit, matching the notice's own remediation advice.
- The evaluation now keys on offlineGeoReady() rather than the ASN
  reader, so a host with only the ASN database mounted (city lookups
  still egress) hears about it, where before it stayed silent.
- The retention prune excludes the new ADMIN_CONFIG_NOTICE event type:
  a state-scoped anchor has a reader for as long as the state holds, and
  the 90-day horizon delete would have re-opened the repeat on a slower
  clock.

Refs #851
2026-08-29 19:20:33 +02:00
Marc-André Bombeck 8c7ae08fe4 Merge pull request #850 from MBombeck/docs/tailscale
docs: add Tailscale serve and funnel as a reverse-proxy option
2026-08-29 19:02:39 +02:00
Marc-André Bombeck 0263540ac1 Merge pull request #848 from TimonBed/fix/password-strength-error-color
fix: show short password labels as invalid
2026-08-29 18:49:22 +02:00
Marc-André Bombeck 1bb1ee0e55 docs: the compose whitelist now carries TRUST_PROXY_HOPS
The note predates the whitelist fix that landed alongside the restore
permission change; keep the manual-edit instruction as a version note
for older compose files.
2026-08-29 18:23:10 +02:00
Marc-André Bombeck d10bc099c8 docs: add Tailscale serve and funnel as a reverse-proxy option 2026-08-29 18:21:14 +02:00
Marc-André Bombeck 5196aff766 Merge pull request #846 from MBombeck/fix/restore-perms-trust-proxy
fix: write restored PHI 0o600 and let TRUST_PROXY_HOPS reach the container
2026-08-29 18:15:06 +02:00
Marc-André Bombeck 9b3c7f088f Merge pull request #845 from MBombeck/docs/truth-audit
docs: truth audit against the current code — correct and prune the operator docs
2026-08-29 18:15:03 +02:00
Marc-André Bombeck 05732c6632 Merge pull request #849 from MBombeck/feat/korean-locale
feat: Korean locale (#839, @aucun6352) — the seventh interface language
2026-08-28 22:35:39 +02:00
Marc-André Bombeck 4f77abc157 chore(release): v1.37.32 — Korean joins as a seventh interface language
Integrates @aucun6352's Korean locale (PR #839): the full catalog, the
NFC recompose in the shared fold, the Hangul lab-name normaliser, the
tilde range separator, and the officially published Korean PHQ-9, GAD-7
and WHO-5 wording. Resolves the CHANGELOG and OpenAPI conflicts against
the current trunk and regenerates the spec. Raises the aggregate bundle
budget to 3700 KB gz for the seventh message catalog, with the reasoning
recorded next to the value.

The contributor's three commits are preserved with their authorship.
2026-08-28 22:09:26 +02:00
Marc-André Bombeck 6ff81b2717 Merge branch 'pr839tmp' into feat/korean-locale
# Conflicts:
#	CHANGELOG.md
2026-08-28 21:59:36 +02:00
Timon_bedandCursor d621699ca4 fix: show short password labels as invalid
Ensure minimum-length failures use the destructive token even when the password's entropy score is strong.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 17:27:50 +02:00
Marc-André Bombeck 0037cc1bcd Write restored PHI 0o600 and let TRUST_PROXY_HOPS reach the container
Two findings from the docs truth audit, both operator-facing.

scripts/restore-backup.ts wrote the decrypted backup, which is health
data in plaintext, with the process default file mode, leaving it
world-readable on the operator's disk while it sat there. It is now
written 0o600.

TRUST_PROXY_HOPS is read from the environment to size the trusted
X-Forwarded-For chain, but it was absent from the compose environment
whitelist, so an operator value in .env never reached the container and
was silently ignored. It now rides all four surfaces: the compose
whitelist, both env examples, and the manifest that pnpm check-env
reads.
2026-08-27 15:21:50 +02:00
Marc-André Bombeck e680c8a884 Reflow the two touched tables through prettier 2026-08-27 12:28:24 +02:00
Marc-André Bombeck 6f514bfc7d Describe the API spec as generated and complete the MCP catalogue
- api/README: the YAML is emitted from the Zod registry by
  pnpm openapi:generate with a CI drift check; document the real
  servers, tags, and coverage (client-facing REST, most admin routes
  and the OAuth/webhook surfaces excluded) and replace the hand-edit
  workflow with the generator workflow
- mcp-capabilities: add the registered get_intraday_pulse,
  get_ecg_recordings and get_nutrients tools and the
  nutrient/{code} resource template to the tables
2026-08-27 12:28:05 +02:00
Marc-André Bombeck b2ee7f11d1 True up the integration references
- ai-providers: /api/ai/test returns provider type, model, token usage
  and a sample with a reasonCode on failure; drop drifted line numbers
- apple-health: source-priority overrides moved to /settings/sources;
  cite the constant instead of line numbers
- data-import: four import paths (medication dose history added); ECG
  and metric-typed clinical records are imported; measurement
  externalId documented; CSV re-uploads dedupe on the natural key;
  mood loggedAt defaults to the start of the given date; the type
  table is a curated subset with /api/meta/capabilities authoritative
- fitbit: the source-priority ladder ships, FITBIT is ranked in every
  default ladder
- google-health: Sources is its own settings section, not nested under
  Integrations
- withings: disconnect unsubscribes the webhook and deletes stored
  tokens without revoking the Withings-side grant; the connection test
  is self-serve, not admin-only; the safety-net cron is hourly;
  refresh stale references
2026-08-27 12:26:08 +02:00
Marc-André Bombeck 123fcc4ec3 Refresh the docs index and reference pages
- docs/README.md: drop the doctor-report.md and audit/ entries (neither
  exists), broaden the ops/ description, list the real subdirectories,
  and stop promising release-by-release migration notes
- migration/v1.3-to-v1.4: note which v1.4 routes have since moved or
  gone; rotation runs via pnpm dlx tsx
- ui-guidelines: six locales with guard tests, settings sections point
  at the registry instead of an eight-item list, /settings redirect is
  a 308
- apple-store-connect-checklist: drop the unsourced 40% rejection-rate
  figure
- codex-protocol-spec: the slug chain rotated on 2026-06-02; default is
  gpt-5.5, the shipped constant is authoritative
2026-08-27 12:23:37 +02:00
Marc-André Bombeck fa7e1ee739 Bring the self-hosting guides in line with the shipped code
- geolite2: quote the real commented compose mount (./geolite2 to
  /opt/geolite2, the GEOLITE2_DIR default, so no env var is needed for
  the default path)
- getting-started: healthcheck probes /api/health, not /api/version;
  the environment module reaches archive-api and geocoding-api
  .open-meteo.com, relevant for egress allowlists
- mcp: the module is opt-in and off by default, but no longer the only
  such module
- reverse-proxy: the Coach stream is SSE over plain HTTP, not
  WebSockets; note that TRUST_PROXY_HOPS is not on the bundled compose
  whitelist and must be added by hand
- scaling: /api/health healthcheck; worker liveness is in-memory and
  invisible across a web/worker split; pool sizing now goes through
  getConnectionBudget with DB_CONNECTION_LIMIT as the compose knob and
  a 2-connection pg-boss share
- sso: the native SSO handoff shipped, OIDC_ONLY works with app builds
  that carry it
- unraid: geo databases are baked in only when the build had a licence
  key, or mounted; replaceable either way
2026-08-27 12:21:27 +02:00
Marc-André Bombeck c986efab30 Correct operator runbooks against the current code
- attempt-number-semantics: name the real bucket column
  (consecutiveFailuresByKind) and drop a drifted line citation
- backup-restore: show the smoke-test response inside the standard
  { data, error } envelope
- deploy: the manual migration step now uses the bundled Prisma CLI
  via node (the image strips pnpm); WHOOP vars are already on the
  shipped compose whitelist
- encryption-key-rotation: point at the encrypted-column registry
  instead of a five-model list several releases behind
- env-check: the CI gate shipped (env-check.yml); the partial-APNs
  example now shows the synthetic all-or-none row and the non-zero exit
- password-reset: the admin API reset route exists; only the
  self-service route does not
- tls-cert-pin: stop asserting client-repo pin-set details that cannot
  be audited from this repository
- drop v141-followup-issues.md: a v1.4.1 punch list whose items are
  fixed, removed, or superseded; keeping it under docs/ops invites
  re-fixing shipped work
2026-08-27 12:18:34 +02:00
Marc-André Bombeck 7f407797f4 Merge pull request #844 from MBombeck/release/v1.37.31
release: v1.37.31
2026-08-27 11:45:07 +02:00
Marc-André Bombeck a0bbf0bf46 chore(release): v1.37.31 — the retry ledger gets an operator's window 2026-08-27 11:27:07 +02:00
Marc-André Bombeck 6c4682acfe Give the operator a provider-health readout
The per-user retry ledger has recorded every AI delivery outcome for a
long time, but no surface ever read it for the operator: a central
provider could fail on every call for weeks and the admin console said
nothing. The AI settings section now carries a health card, backed by a
new admin-only endpoint that folds the ledger into one row per provider
type: users tracked, users currently failing, the worst uninterrupted
failure run, and the last success and failure instants. Operator-managed
types sort first because their failure takes the shared fallback down
for everyone whose chain relies on it. Counts and timestamps only; the
response never names a user.
2026-08-27 11:26:40 +02:00
aucun6352 31eb50e3e2 fix(i18n): give the Korean instruments their published source texts
The Korean questionnaire wording was translated freshly from English, so
a score built from it was comparable to nothing in the literature. Each
instrument now carries the text its own publisher put out, or no Korean
at all.

PHQ-9 and GAD-7 come verbatim from the instrument owner's distribution —
Pfizer's `PHQ9_Korean for Korea.pdf` (2010-06-15) and `GAD7_Korean for
Korea.pdf` (2010-05-18), the latter being the file Ahn/Kim/Choi 2019
names as what it validated. The sheets grant reproduction, translation,
display and distribution without permission. Verbatim means verbatim:
the spacing in "7 일 이상 방해 받았다" and the sheet's "안절부절 못하거나"
against the GAD-7 sheet's "안절부절못해서" are reproduced as printed.

WHO-5 has no official Korean arm. Neither the WHO's 2024 distribution
(26 languages) nor the Psychiatric Research Unit folder it inherited
from (31 languages) has ever carried one, and ePROVIDE lists the same
31. Korean therefore carries the published forward/back-translation
from Kim HJ et al., J Korean Geriatr Psychiatry 2010;14(2):90-96, which
is CC BY-NC and so redistributable; the attribution line names it. Its
validation sample was community-dwelling elderly rather than general
adults, which the definition says out loud.

The Sleep Condition Indicator reverts to English. It is validated in
English only, its cut-off was derived from those words, and no openly
redistributable Korean exists — so `ko` now matches de/es/fr/it/pl:
items, section stems and response anchors byte-identical to en.json,
under the localized "validated in English" note.

`ALL_APP_LOCALES` grows to seven, which is what stops the check-in
wizard claiming English wording over Korean items on every Korean
check-in.

One gap is deliberate and not yet resolved. The official Korean PHQ-9
and GAD-7 sheets disagree on anchor 2 — "7 일 이상 방해 받았다" against
"2 주 중 절반 이상 방해 받았다" — but both instruments read one shared
`mentalHealth.options` set, which holds for the other six locales
because their two sheets agree word for word. Korean takes the PHQ-9
wording for both here. GAD-7's anchors are therefore validated in
substance but not verbatim; splitting them into a `gad7Options`
namespace is the fix, and is left for the maintainer to weigh against
the 24 duplicated keys it would add across the other locales.

The functional-impairment item and its four anchors come from the same
PHQ-9 sheet. They are not scored and not covered by the
`validatedItemLocales` contract.
2026-08-27 17:37:26 +09:00
Marc-André Bombeck 1d7bd82ca8 Merge pull request #843 from MBombeck/release/v1.37.30
release: v1.37.30
2026-08-27 09:15:44 +02:00
Marc-André Bombeck 7aecae863d Teach the pin inventory the conditional openai-client shape
The SSRF pin inventory asserted a literal unconditional pin in the
openai-client; the previous commit made that pin conditional for the
two person-typed base-URL tags. The guard now asserts the exact
ternary — allowlist helper for gateway/admin-key, literal true as the
floor — so neither the floor nor the condition can drift silently.
2026-08-27 08:56:53 +02:00
Marc-André Bombeck 96d6f64ee6 chore(release): v1.37.30 — the operator provider may cross into its own network 2026-08-27 08:49:49 +02:00
Marc-André Bombeck fb82954077 Let the operator provider reach an allowlisted private host
The global admin provider's base URL is operator-typed in the admin
settings, but the client pinned requirePublicHost unconditionally for
its tag — so an operator pointing it at a private OpenAI-compatible
proxy (an OAuth sidecar on the instance's own Docker network) got a
safeFetch refusal on every call, indistinguishable from an outage. The
admin-key tag now consults the same ALLOW_LOCAL_AI_PRIVATE_HOSTS
policy as the user-configured gateway: a public URL never consults the
allowlist, a private host without an entry is refused exactly as
before, and both ends of the grant are the operator's own. The codex
tag stays hard-pinned; its base URL is a repository constant. Every
non-operator admin-key construction pins the public api.openai.com
constant, so the personal-key posture is unchanged.

The test asserting the old blanket pin is split into the three cases
that actually differ: allowlisted private host passes, unlisted
private host still refuses, codex refuses even a blanket allowlist.
2026-08-27 08:48:00 +02:00
Marc-André Bombeck d5d9793586 Write down the client-development contract
A second native client is starting, and the rules that keep the first
one aligned with the server lived in issue threads and habit. They are
now docs/CONTRIBUTING-CLIENTS.md: where the contract truth lives, the
response envelope, auth from a client's point of view, sync semantics,
the server-authoritative-values rule, and how cross-repo coordination
works in practice.

CONTRIBUTING-AI.md was a snapshot of an old conventions document and
had drifted well away from the codebase it describes (it still spoke
of 26 Prisma models and in-memory rate limits). It now points at the
living sources instead of carrying an aging copy.
2026-08-26 21:08:14 +02:00
Marc-André Bombeck 15fe030784 Record the openssl patch under v1.37.29 2026-08-26 20:27:52 +02:00
Marc-André Bombeck d489d29cab Merge pull request #842 from MBombeck/fix/openssl-cve-2026-14456
Patch OS packages in the runtime image at build time
2026-08-26 19:56:35 +02:00
Marc-André Bombeck 4ce0e6c5ce Patch OS packages in the runtime image at build time
Trivy flags CVE-2026-14456 (openssl denial of service via unbounded
memory growth in the QUIC server) in the runner stage: the pinned
node:22-alpine digest ships libssl3/libcrypto3 3.5.7-r0 and the fix is
published as 3.5.8-r0 in the Alpine repo. An apk upgrade in the runner
stage picks up published OS security fixes without giving up the digest
pin, closing the window between a CVE landing in the secdb and the next
base-image rebuild.
2026-08-26 19:39:51 +02:00
Marc-André Bombeck 898a5a95f3 Merge pull request #840 from MBombeck/release/v1.37.29
release: v1.37.29
2026-08-26 19:18:37 +02:00
Marc-André Bombeck e7395398ca Anchor the a11y weight fixture on now
The a11y matrix feeds the weight sub-page chart ten rows with absolute
July dates. The range tabs are calendar-day windows anchored on now, so
those rows aged out of the default window, the page rendered its empty
state, and the .recharts-wrapper painted gate timed out on every shard
and theme. Relative dates keep the fixture inside the window on any
date, same as the charts-mobile spec already does.
2026-08-26 18:49:59 +02:00
Marc-André Bombeck 0e6fcaa2fc Smooth a parenthetical in the release notes 2026-08-26 18:01:08 +02:00
Marc-André Bombeck 14b8b5ac27 chore(release): v1.37.29 — the range tabs say days because they are days 2026-08-26 18:00:12 +02:00
Marc-André Bombeck 240c15ff15 Label the chart range tabs as the day windows they are
The range selector said points — 7 pts, Last 7 data points — while the
fetch has always treated the value as a calendar-day window. Someone
who weighs in twice a week picked 7 pts and saw two, and read that as
a broken chart; the labels were the broken part. The tabs now say 7d /
30d / 90d / All across all six locales.

Behaviour is unified on the same reading everywhere. The measurement
chart's visible slice becomes a real day-window filter — the old
slice(-N) was a no-op on the self-fetched path but silently meant
last N readings on the dashboard's preloaded batch slice, so the same
tab meant two different things depending on the mount path. The mood
chart sliced the last N logged days out of the whole history and now
windows by days like its siblings. The header chip reads the same
grain decision the chart and the data table use instead of re-deriving
it in a second memo.

Component fixtures move to now-anchored dates: the windows are anchored
on now, so absolute-dated fixtures age out of the window and would have
exercised only the empty states. The span-dependent cases (weekly chip,
bucketed-caption table) mount the All range, which is now the only
range that can span past 90 days.
2026-08-26 17:55:56 +02:00
Marc-André Bombeck 0823a4e222 Refine the tiered rollup read by the actual data span
The tier for a chart series keyed off the requested window width. The
All range always requests ~3650 days, so every account got MONTH
buckets regardless of how much history exists — a record spanning four
months came back as four monthly means, and the chart captioned them
from the real span as a weekly average. The reader now re-reads at the
tier the returned rows' span calls for; a coverage miss on the finer
tier keeps the coarser rows.

The ladder comment claimed to mirror the client's pickBucket
thresholds and misquoted them. The two ladders are deliberately not
identical; a test now pins the direction that keeps the caption honest
(server never coarser than the client captions) for every span up to
ten years.
2026-08-26 17:55:43 +02:00
aucun6352 f7cc47850a fix(i18n): make the Korean locale actually work end to end
Registering `ko` in the `Locale` union left seven locale-keyed tables
without an entry, so the build could not type-check and the safety
screens, the citation-coverage grader and the reference-range parser
read nothing at all for a Korean reader.

Three failures were not missing keys but wrong assumptions:

- The shared fold decomposes with NFD and strips U+0300-U+036F. Latin
  accents become plain letters, but Hangul decomposes into jamo, which
  are not in that range and survived — so folded Korean text was a jamo
  sequence no precomposed table entry could ever match. It recomposes to
  NFC now; every Latin, Polish and German fold is byte-identical.
- `normaliseLabKey` kept `[a-z0-9]`, which reduced every Korean analyte
  name to the empty string, so the derived index held none of them and a
  Korean cholesterol result reached a FHIR export uncoded.
- The reference-range parser had the hyphen and the dashes but not the
  tilde a Korean lab actually prints (`3.5~5.0`).

The Korean safety banks carry no `\b` next to a Hangul token — `\b` is
an ASCII `\w` boundary and Hangul is not `\w`, so `/\b증량/` matches
nothing — and the clause order is the mirror of the Latin banks, since
Korean closes with the verb. The dose patterns require a target-marking
particle for the same reason the Latin banks require "to"/"by": without
it the permitted restatement "7.5mg을 복용 중이고, 체중은 내려가고
있어요" tripped the lowering pattern.

The Coach and Insights prompts route `ko` down the reviewed English body
plus a Korean reply directive; there is no `safety-contracts.ko.yaml`, so
the native builder has no Korean ground rules to compose from.
2026-08-26 20:00:44 +09:00
aucun6352 f1b0420479 feat(i18n): add Korean as a seventh end-to-end locale
Register `ko` in the locale list, language names, and labels, and ship
messages/ko.json so the whole UI — dashboard, settings, share views,
clinician PDF, notifications, and AI prompts — renders in Korean.

Extend the locale-parity, English-leak, plural-completeness, and copy
guard tests to cover the new locale, and update README/CONTRIBUTING to
list Korean among the supported languages.
2026-08-26 16:42:45 +09:00
Marc-André Bombeck 3ce5411d19 Merge pull request #838 from MBombeck/release/v1.37.28
v1.37.28 — the parts of a shared record nobody could see
2026-08-24 03:27:56 +02:00
Marc-André Bombeck 7a4e09bb4c chore(release): v1.37.28 — the parts of a shared record nobody could see 2026-08-24 02:58:23 +02:00
Marc-André Bombeck 5808f8f91a Merge branch 'fix/share-viewer-leaves' into release/v1.37.28 2026-08-24 02:57:12 +02:00
Marc-André Bombeck e417376d29 Merge branch 'feat/derived-window-days' into release/v1.37.28 2026-08-24 02:57:12 +02:00
Marc-André Bombeck d7d8e437ee feat(insights): let a caller choose the derived-metric window
`GET /api/insights/derived` accepts `windowDays`, bounded to 1..90, and
threads it to the dispatcher. Omitting it changes nothing: every engine
keeps its own default, so a caller that asks for nothing reads exactly
what it read before.

Ninety is where the tier this route promises runs out. The rollup router
opens its WEEK floor at 91 days, and the baseline engines cannot compose
a spread from WEEK buckets, so a 91-day request falls through to a raw
`measurement.findMany` with no row cap — for a densely sampled type that
is a full history scan, and the analytics-read budget allows 120 of them
a minute per account. The trailing `series` is capped at 30 points
regardless, so past the ceiling a wider window would only broaden the
mean behind the value. Out of range is a 422 rather than a clamp.

An unhonoured window is visible rather than silent. `provenance.windowDays`
is the window the engine actually used and `coverage.historyDays` the days
that actually backed it, so a three-week record answering a thirty-day
request reports both numbers instead of implying coverage it does not
have. `HEALTH_SCORE` composes fixed per-pillar windows and reports the
widest; a new suite freezes that it is the only metric that does, so an
arm added later cannot quietly drop the parameter.

Recovery keeps its canonical resolution under the wider window. A worn
band stamps the wake morning and the computed proxy the night before, and
only `resolveCanonicalRecovery` pairs them; a test seeds forty such
nights, asks for sixty days, and holds the answer to forty nights with a
flat trend — a bypass leaves eighty rows and a false climb.

Contract: model `WellnessScoreValue` field for field and publish it. The
envelope's `value` has to stay an open record because one route serves
eighteen differently-shaped metrics, so nothing can `$ref` the shape and
it went out undocumented — `series`, `daysInWindow` and `asOf` were on
the wire with no way to find them short of inspecting a live response. It
is registered in the forced-components slot instead, held against the
runtime interface by a test, and the fields it does not cover are named
in the schema comment so the remaining gap is known rather than invisible.
2026-08-24 02:00:55 +02:00
Marc-André Bombeck 96bcf843fe test(share): render the clinician view in all six locales
Most labels on this page are resolved from a runtime value, not written
as a literal: an illness type, a lifecycle, a visit kind, a vaccine slug,
a blood-type constant, a cycle phase, a GLP-1 side-effect tag. The
call-site guard cannot see any of them, and the enum-derived guard can
only cover a space whose members it can enumerate from a source. A key
that does not exist therefore renders as its own dot notation, in front
of a doctor, with every other guard green — which is exactly how
`encounters.kind.ROUTINE` reached three surfaces.

One fixture with every section populated, six renders, one assertion:
nothing in the reader-visible text may look like a dotted key path.

Break-proof: put the interpolated visit-kind key back and all six go red
naming it.
2026-08-24 01:34:32 +02:00
Marc-André Bombeck a7452c7a6c feat(share): name both reference windows on a diverging lab row
A reading judged against the window its own report printed, beside a
saved band that states different limits, is two answers about one
number. The PDF names both — the range in the column, the saved band in
a footnote under the table — and says in as many words that showing one
of them is a partial answer. The page carried only the first.

Both fit on the value line here, so there is no footnote to place.
Break-proof: force the divergence branch off and the case goes red.
2026-08-24 01:31:05 +02:00
Marc-André Bombeck b59a78155b docs(api): publish the share link's PDF and FHIR downloads
Both routes were exempt from the contract as `shareLink` — "authenticated
by the URL credential, for a recipient with no account". That reason
holds for the page a person opens. It does not hold for two routes whose
whole purpose is to hand a practice a file it files into another system,
which is exactly the audience a contract has. `/c/{token}/d/{id}` was
published all along, one route away in the same tree.

Each entry states the gate it shares with the page, the frozen selection
it can never exceed, the flat 404 that covers every miss class including
a documents-only link, and the 20/h per-link bucket. The FHIR entry says
plainly that it is a download and not a REST face, and names the two
resource families the bundle deliberately omits.

The create-request description claimed "there is no FHIR or other
machine-readable face behind a share token", which stopped being true
when these routes landed. It now describes what a link actually serves
and records that the insurance leaf is refused outright.

The coverage guard gains the other half of its staleness check. It caught
an exemption for a route that had disappeared, and never the reverse — an
exemption left behind after the route was published, which is how these
two would have stayed on the list while the contract already carried
them. Break-proof: re-add either entry and it goes red naming it.
2026-08-24 01:10:24 +02:00
Marc-André Bombeck ac6fd187d6 test(share): pin every catalogue leaf to a clinician-view renderer
Eleven leaves stayed invisible for eleven releases because nothing
connected the two lists. The picker-to-aggregator guard was satisfied and
kept being satisfied; the page was not on either end of it.

`DISPOSITIONS` is `Record<StructuredLeafId, …>`, so an eighteenth
structured leaf fails `pnpm typecheck` until someone writes down whether
it renders or why it cannot. Per leaf the suite then renders the real
view over a real fixture and asserts the marker appears; re-renders with
that leaf alone removed from the frozen selection, payload untouched, and
asserts it is gone; and for a refusal, reads the list that enforces it
rather than trusting the note.

Once over the whole set: a carried leaf with nothing behind it says so, a
leaf whose module is off says something else, and a leaf the link never
carried says nothing at all.

The `share-downloads` row is asserted here too. Its test id had zero
references anywhere in the tree, so the two buttons a practice clicks
could have lost a link, pointed at the wrong path, or vanished from a
documents-only share unnoticed.

Break-proofs, each confirmed red then restored: drop a section element
(that leaf's render case); gate `LeafSection` on data instead of scope
(thirteen withholding cases); collapse the switched-off arm (the
distinction case); empty `SHARE_LINK_FORBIDDEN_LEAVES` (the refusal
case); add an eighteenth leaf (typecheck).
2026-08-24 01:07:14 +02:00
Marc-André Bombeck 7a9aa141a6 feat(share): render the record sections the clinician view withheld
Someone ticks "Lab values" in the selection, sends the link, and the
doctor opens a page that says nothing about lab values — while the PDF
download from the same link prints them. Eleven of the seventeen
structured leaves were like that: the control existed, the data reached
the page object, and no component read it. The person had every reason
to believe they had shared something they had not.

Rendered, in catalogue-group order, which is also the PDF's:

  - emergency information, framed and first, as it is page one there;
  - personal details (name, date of birth, gender, height);
  - lab values, with the reference window each reading was judged
    against, printed as the source report printed it;
  - GLP-1 therapy and the logged-dose ledger;
  - conditions and illnesses, visits, immunizations;
  - family history, mood, the menstrual cycle.

What each shows follows the PDF, which has already settled what belongs
in a section and in what order. The layout does not: a six-column table
becomes a labelled block, a four-column one becomes a row with its
detail composed onto the value side.

Absence is stated, never implied. A leaf the link does not carry renders
nothing at all — the recipient was never promised it. A leaf on the link
with nothing behind it renders its heading and says so, and one whose
domain is switched off on the owner's account says that instead. This
extends what the health-profile section has always done per fact to the
section level, and the glucose, medication and allergy cards adopt it
too; the measurement groups deliberately stay silent, because a group
card stands for up to seventeen leaves and twelve empty ones is noise.

Every card now asks the frozen selection directly through `LeafScope`
rather than inferring consent from the presence of data. The aggregator
already applies the selection, but a section that reads only "is there
data" trusts a gate it cannot see.

Three rows on the emergency card are composed from other leaves — severe
allergies, the drug list, chronic conditions. Each appears only when its
own leaf is on the link: printing "Not recorded" for a leaf the owner
withheld states an absence in the record where the truth is an absence
in the share, and on that card it is the dangerous direction to get
wrong.

The glucose card's heading was "Lab values", which was the wrong name
for it even before the actual lab results arrived; it is the glucose
group's own label now.

`INSURANCE` gets no renderer and must not get one: the create route
refuses the leaf outright, so no link can carry it.
2026-08-24 01:02:50 +02:00
Marc-André Bombeck fbe2081506 feat(share): carry the owner's module verdict beside the payload
A leaf on a share link can be absent from the payload for two reasons
that look identical downstream: the owner shared it and recorded
nothing, or they shared it and the domain is switched off on their
account. The aggregator ANDs the selection and the module map and
returns the same null either way, so the recipient could not tell an
empty section from one that never had a chance to carry anything.

`loadShareViewData` now resolves the whole module map — it needed the
`doctorReport` key from it anyway — and returns `unavailableLeaves`: the
leaves the link DOES carry whose owning module is off. Only selected
leaves appear, because a withheld leaf's module state is not the
recipient's business in any direction.

The map is deliberately NOT handed to the aggregator. The third argument
is the frozen selection and there is no fourth, which is what keeps this
surface from growing an options object that widens what it asks for; the
resolver memoises its reads per request, so the aggregator resolving its
own map again costs no round-trip.

The module-gate suite moves off `isModuleEnabled` with it, and gains
three cases for the new verdict, including the one that proves an
unshared leaf is never named.
2026-08-24 01:02:33 +02:00
Marc-André Bombeck 29ab274775 fix(i18n): name a visit kind instead of printing its enum
Three surfaces built the label key by interpolation — the doctor-report
PDF's visit table, the daily digest's upcoming-visit line and the
clinician share view. `EncounterKind` is `ROUTINE` and the bundle leaf is
`routine`, so all three rendered `encounters.kind.ROUTINE` verbatim: into
a document a practice files, onto a lock screen, and onto the page.

Route them through `encounterKindLabelKey`, a literal switch beside the
existing `encounterKindLabel`, so the mapping is written down once.

The enum-derived i18n guard could not have caught this: it only knows
key spaces of the form `prefix + member`, and this one is not. It gains a
second arm for spaces whose mapping is a function, with `encounters.kind`
as its first entry. Break-proof: point one arm of the resolver back at
the uppercase key and six locale cases go red.
2026-08-24 01:02:20 +02:00
Marc-André Bombeck d290422923 Merge pull request #837 from MBombeck/release/v1.37.27
v1.37.27 — the checks that were green because they were not checking
2026-08-23 21:17:51 +02:00
Marc-André Bombeck 7f708a4bcb docs(changelog): record the shell's eager settings-schema import 2026-08-23 21:00:00 +02:00
Marc-André Bombeck 92b8040796 perf(shell): import the settings-destination predicate from its leaf
The authenticated shell wraps every route and read one destination
predicate off the `@/lib/record-settings` barrel. That barrel also
re-exports the managed settings-patch schemas, so Zod, the module
registry and three validation modules rode into the eager client
bundle of every authenticated page for a function that inspects a URL
slug. The shell imports `record-settings/classification` now; the
barrel loses the re-export nobody else used.

Measured over all 585 client-rendered routes: none grew, 100 fell, by
4.7 KB gz at the median and 8.1 KB at the most. /insights had been
sitting on its 445 KB ceiling for three releases and went over it on
this branch's CI run; it measures 437 now, /measurements 435, / 450,
/insights/mood 450.

The whole-build sum moved the other way, 3451 to 3476, because the
aggregate counts each emitted chunk once: a graph that leaves the
chunk group every route shares gets counted again wherever it lands,
here inside the deferred settings chunks that use it. Bytes on disk
rose, bytes a reader downloads only fell. The aggregate cap moves to
3500 with the same 24 KB headroom the four earlier re-measurements
kept, and the reasoning sits next to the number.
2026-08-23 20:56:13 +02:00
Marc-André Bombeck 5803d16e7d chore(release): v1.37.27 — the checks that were green because they were not checking 2026-08-23 19:44:01 +02:00
Marc-André Bombeck 1d733ef192 Let a German verdict reach the classifier the merge gave it
The two halves of the ECG fix were built apart. One taught the parser
Apple's full English verdict set; the other taught it the metadata keys and
verdict wording a German watch writes. Each was correct alone, and each
left "Sinusrhythmus" unresolved for a different reason.

Together they meet: the alias table translates the wording onto Apple's
own English, and the classifier decides what it means. One place still
owns the meaning, which is what stops a per-language verdict table from
drifting the first time Apple adds a case.

The test that expected null was pinning the gap between the branches
rather than a decision about German. It now expects NOT_DETECTED, and a
French verdict takes over the null case, because four of the six
languages genuinely have no observed key map yet.
2026-08-23 19:42:45 +02:00
Marc-André Bombeck f4695457b1 Merge branch 'fix/ecg-csv-real-exports' into release/v1.37.27
# Conflicts:
#	src/lib/apple-health/ecg-csv.ts
2026-08-23 19:39:36 +02:00
Marc-André Bombeck b154ec52cb Merge branch 'fix/language-matchers-rest' into release/v1.37.27 2026-08-23 19:38:45 +02:00
Marc-André Bombeck 31991924f0 Merge branch 'chore/knip-dead-exports' into release/v1.37.27 2026-08-23 19:38:45 +02:00
Marc-André Bombeck b0d7705491 Merge branch 'fix/data-envelope' into release/v1.37.27 2026-08-23 19:38:44 +02:00
Marc-André Bombeck dbee6b7429 Merge branch 'fix/discovery-matrix' into release/v1.37.27 2026-08-23 19:38:44 +02:00
Marc-André Bombeck 8bf3c53d7d fix(apple-health): read an ECG export whose metadata keys are translated
The CSV is written in the device's language, and the keys are translated
along with the values: a German watch writes `Aufzeichnungsdatum` and
`Klassifizierung`, not `Recorded Date` and `Classification`. Indexing on
the English keys found none of them, so the parser never located the
waveform and rejected the recording outright — a lost import, not a
missing field.

Two alias maps close it, both taken from real exports rather than from a
dictionary: nine metadata keys and two verdicts, consistent across every
German file observed. Adding a language is a data addition to those maps
and nothing else.

The verdict map is an indirection onto the English wording rather than a
second verdict-to-enum table, so there stays exactly one place that
decides what a verdict means.

The other four shipped languages are absent on purpose. A wrong key
silently mis-files a value and a wrong clinical verdict is worse than
none, so an export this parser cannot place is refused — which an operator
can see — rather than read into the wrong column, which they cannot. Two
gaps are written down at the map: no observed file carries an
average-heart-rate row in any language, and the paired layout's column
header has only ever been seen in English.
2026-08-23 19:17:02 +02:00
Marc-André Bombeck 29bad0a2b8 fix(apple-health): read the sampling rate as real exports spell it
The rate matcher demanded "Hz". Observed exports spell the unit out and
lower-case it — "511,422 hertz" — and the German ones separate it from the
number with a no-break space. The fixtures had only ever used "512 Hz", so
the mismatch never showed.

Rate and heart rate now split into a magnitude and a unit word, with the
magnitude read through the same decimal helper the waveform uses. "512 Hz",
"512 hertz" and "511,562 Hertz" all resolve; a missing unit, the wrong
unit, a grouped number and a rate past the bound are all still refused.

The unit word is matched loosely and the magnitude strictly. That is the
right way round: the unit is presentation and varies by region, while the
number is the measurement.
2026-08-23 19:17:02 +02:00
Marc-André Bombeck a85c6681bb fix(apple-health): read an ECG waveform written with decimal commas
A watch set to a comma-decimal region writes its samples as "-180,596".
The single-column reader rejected any row containing a comma outright, so
every one of those files failed on its first sample row.

The two waveform layouts disagree about what a comma means, which is why
this cannot be decided per line. The parser now names the section it is in
— header, single-column, paired — and both crossings are commented at the
point they happen: the paired layout announces itself with a `Lead,Voltage`
column header, while the single-column one begins at the first blank line
AFTER Lead and Unit have been declared, because real exports also carry
blank lines mid-header.

Scalars in both waveforms now read either dialect through one helper, so
"-180.596" and "-180,596" give the same microvolts and neither is
privileged. A number carrying thousands grouping is refused rather than
guessed at, since resolving it needs the file's region and the file never
states it. The one genuinely ambiguous shape is a separator followed by
exactly three digits; it is read as a decimal, because observed waveforms
put two- and three-digit fractions in the same file and grouping is always
three, and because a machine writing one bare value per row has no reason
to group at all.
2026-08-23 19:17:02 +02:00
Marc-André Bombeck 19699ce8ce fix(apple-health): accept the valueless header row an ECG export opens with
Every real export begins with a bare `Name` when the name field is blank —
Apple omits the trailing comma rather than writing an empty value. The
parser required a comma on every header row, so it rejected the file on
line 1, before it had read anything.

A valueless header row is now skipped. It contributes no metadata entry
rather than an empty-string one, because `Lead` and `Unit` presence is what
switches the parser into the single-column waveform mode and a key with no
value must not be able to trip that switch.

The relaxation is confined to the header. Inside the single-column
waveform a comma-less row is a sample and is read as one; inside the
paired waveform every row is lead and voltage, so a missing comma there is
still malformed.
2026-08-23 19:17:02 +02:00
Marc-André Bombeck 03293bc2eb Record what the dead-code gate was blind to before knip 6.28.0
ignoreExportsUsedInFile did not only exempt exports used inside their own
module; until 6.28.0 it also marked every re-export as referenced in its
own file, so a barrel line nothing imported was never reported. The
upgrade took this repo from 0 findings to 206 on unchanged code. Write it
down next to the setting, because a green gate on any earlier knip proved
nothing about re-exports.

Also correct the production-pass file count, which had drifted to 21.
2026-08-23 19:11:12 +02:00
Marc-André Bombeck 949677008f Drop the type imports left behind by the extract-prompt re-export
CadenceKind and WeekdayToken were imported only to be re-exported. The
re-export went in the previous commit but the import survived, because
the doc comment above it still named both types at the time.
2026-08-23 19:11:12 +02:00
Marc-André Bombeck fb344c4f78 Remove two dead alias constants
SENSITIVE_LEAVES and COACH_SUGGESTED_ACTION_TYPES each aliased a
constant defined elsewhere and were never imported. Neither is a
re-export the way the barrel lines were — the definition itself is the
dead thing, and both doc comments describe a consumer that does not
exist: the purity guard reads SENSITIVE_LEAF_IDS from ./catalogue
directly, and nothing mirrors the suggested-action allowlist.

The imports that fed them go with them.
2026-08-23 19:11:12 +02:00
Marc-André Bombeck 0e9c5f1a00 Drop unimported re-exports outside the barrels
Eighteen modules carried a convenience re-export of a symbol defined
elsewhere. In each case the callers the comment describes now import the
concrete module directly, so the line had no importer left. Where the
whole re-export block went, the comment explaining it went with it —
doctor-report-pdf-core, trend-card and medication-extract-prompt each
claimed to be a single import surface that nothing was using.

Definitions are untouched; imports that existed only to feed a removed
re-export go too.
2026-08-23 19:11:12 +02:00
Marc-André Bombeck 244a939d05 Drop unimported re-exports from the remaining barrels
Same shape as the derived and MCP barrels: the line in the barrel had no
importer because the consumer imports the concrete module. Affected:
cycle (15), coach tools (9), record-settings (8), links (4), data-list,
workout-detail and analytics/score (1 each).

analytics/score also carried CompositeValue on an explicit export line
above an export * of the same module, so the name stays exported either
way.

Definitions are untouched.
2026-08-23 19:11:12 +02:00
Marc-André Bombeck c00904068b Drop unimported re-exports from the MCP barrel
The barrel mirrored the tool, resource, prompt, write and scope registries;
its only consumer is the /mcp transport route, which needs three of them.
The registries are imported from their concrete module by ./server and by
their own tests, so the other 31 lines had no importer.
2026-08-23 19:11:12 +02:00
Marc-André Bombeck 7e1c63cec3 Drop unimported re-exports from the derived-metrics barrel
The barrel mirrored every export under src/lib/insights/derived. Of the
124 lines, 101 had no importer: consumers and per-metric tests reach for
the concrete module (./sleep-score, ./trajectory, …) directly. Keep the
cross-cutting surface — registry, dispatcher, baseline loader, and the
value shapes outside consumers read — and say in the header that the
barrel is not a mirror, so the next addition needs a consumer first.

Definitions are untouched; only the re-export lines go.
2026-08-23 19:11:12 +02:00
Marc-André Bombeck b9fe29c066 Bump knip from 6.16.1 to 6.32.2
The newer resolver tracks each re-export as its own reference site, so a
barrel line that nothing imports is now reported instead of being counted
as used whenever the underlying symbol was used anywhere. The gate goes
from zero findings to 206 on unchanged code.
2026-08-23 19:11:12 +02:00
dependabot[bot] 8ecf7e5595 Bump @napi-rs/canvas from 1.0.2 to 1.0.7 (#836)
Bumps [@napi-rs/canvas](https://github.com/Brooooooklyn/canvas) from 1.0.2 to 1.0.7.
- [Release notes](https://github.com/Brooooooklyn/canvas/releases)
- [Changelog](https://github.com/Brooooooklyn/canvas/blob/main/CHANGELOG.md)
- [Commits](https://github.com/Brooooooklyn/canvas/compare/v1.0.2...v1.0.7)

---
updated-dependencies:
- dependency-name: "@napi-rs/canvas"
  dependency-version: 1.0.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-23 18:55:24 +02:00
Marc-André Bombeck b15bf4da19 fix(apple-health): record the ECG verdicts the parser was dropping
The classification map held three values. Apple's set is larger, so a real
verdict was being thrown away on English devices: "Heart Rate Over 120"
and "Heart Rate Under 50" both became null, and the column cannot tell
that apart from a recording that carries no classification at all.

The wordings are observed rather than remembered. The CSV writes a display
string and it does not match the framework's case names — the case
documented as InconclusiveHighHeartRate reaches the file as "Heart Rate
Over 120". Across a corpus of 128 real exports the field held five
distinct values; three of them mapped and two were dropped. The threshold
belongs to the watch generation, so the two heart-rate arms match the
number instead of pinning it, and the rest of the map takes its wording
from Apple's ECG instructions for use.

Classification is now split from the column write so the parser can tell a
verdict it has never heard of from one it knows it cannot represent.
Unrecognized is the second kind: the device did not fail to classify the
waveform, it received a verdict it does not know, so recording it as
"could not classify" would assert something Apple never said. Both still
store null, because that is the column's whole vocabulary, and no column
is added for a distinction nothing reads yet.

The old table pinned one row for "Localized or unknown verdict". That
assertion is still true, but it fused three different facts — a localised
verdict, an unknown one, and the two documented verdicts being silently
dropped beside them — and it read as "everything else is unknown" when two
of those were verdicts Apple documents. It is split into the four outcomes.

The language half stays open and is now named at the mapping. A German
export writes the KEY in German too, so a non-English verdict never
reaches this function; it fails the parse earlier.
2026-08-23 18:39:19 +02:00
dependabot[bot] b217bb2618 Bump @next/bundle-analyzer from 16.2.12 to 16.3.1 (#834)
Bumps [@next/bundle-analyzer](https://github.com/vercel/next.js/tree/HEAD/packages/next-bundle-analyzer) from 16.2.12 to 16.3.1.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/commits/v16.3.1/packages/next-bundle-analyzer)

---
updated-dependencies:
- dependency-name: "@next/bundle-analyzer"
  dependency-version: 16.3.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-23 18:36:00 +02:00
dependabot[bot] ff133eacdf Bump @tailwindcss/postcss from 4.3.0 to 4.3.3 (#835)
Bumps [@tailwindcss/postcss](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/@tailwindcss-postcss) from 4.3.0 to 4.3.3.
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.3/packages/@tailwindcss-postcss)

---
updated-dependencies:
- dependency-name: "@tailwindcss/postcss"
  dependency-version: 4.3.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-23 18:35:09 +02:00
dependabot[bot] ece7253a42 Bump @modelcontextprotocol/sdk from 1.29.0 to 1.30.0 (#831)
Bumps [@modelcontextprotocol/sdk](https://github.com/modelcontextprotocol/typescript-sdk) from 1.29.0 to 1.30.0.
- [Release notes](https://github.com/modelcontextprotocol/typescript-sdk/releases)
- [Commits](https://github.com/modelcontextprotocol/typescript-sdk/compare/v1.29.0...1.30.0)

---
updated-dependencies:
- dependency-name: "@modelcontextprotocol/sdk"
  dependency-version: 1.30.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-23 18:29:10 +02:00
dependabot[bot] fb1a0564d2 Bump docker/setup-buildx-action from 4.2.0 to 4.3.0 (#832)
Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 4.2.0 to 4.3.0.
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/bb05f3f5519dd87d3ba754cc423b652a5edd6d2c...37fe631027851001ddb9b187196cc803df7f5f0e)

---
updated-dependencies:
- dependency-name: docker/setup-buildx-action
  dependency-version: 4.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-23 18:28:46 +02:00
Marc-André Bombeck 3744073a01 fix(coach): tokenize prose numbers in the language the reply was written in
The grounding tokenizer read English unit words and English or German
month names, while the reply is written in the reader's language. Two
silent failures came out of that, pointing in opposite directions.

A missing unit loosens the guard. "7,4 Stunden", "45 minuti" and "8000
pasos" came back unkinded, and an unkinded token clears the kind gate
against every ledger entry, so a fabricated night's sleep could ground
itself on a glucose reading that happened to share its magnitude. Kind
scoping is the thing that stops a weight grounding a blood-pressure claim;
for five languages it was not running.

A missing month corrupts correct prose. "Le 21 juillet" left the day
untyped, the plain-magnitude pass graded it, nothing matched, and the
soft-strip replaced it — the reader was shown "Le […] juillet". Spanish
and Italian also put a particle between day and month, so the pass admits
one.

The unit vocabulary had been written out three times and the copies had
already drifted; only one of them knew about "%". One list now feeds the
classifier, the range pass and the measurement pass. Polish months are
listed in the genitive, which is what a date uses and also the only form a
trailing word boundary can match, since that boundary is defined over
ASCII and "ń" is not part of it.
2026-08-23 18:15:16 +02:00
Marc-André Bombeck fb41df49e9 fix(mood): search the icon picker with the headers it just rendered
The grid draws its group headers in the reader's language and then
searched only the English Lucide names and the English keyword aids. A
German reader who typed back the header they had just read — "Gesundheit"
— got an empty grid and "no icons found", with nothing to say the query
was fine and the language was not.

The filter now also matches the group header the picker is currently
rendering, folded on both sides so an accent or a capital cannot make
someone miss a word they can see. The labels come from the bundle at the
call site, so a seventh language needs no edit here.

This is a partial close and the test says so. The per-icon aids stay
English, so "Herz" and "kawa" still find nothing; translating roughly
eighty icons times three aids times six languages is a content decision,
not a filter one.
2026-08-23 18:09:35 +02:00
Marc-André Bombeck 2d26a6fdfe fix(telegram): answer someone who asks for help in their own language
The bot's real commands are slash commands, and `telegram.helpBody`
documents exactly those in all six bundles, so nothing a user is TOLD to
type depended on their language. The undocumented courtesies did: the bare
word "help" and "hilfe" opened the help text and five greetings were
answered, everything else fell through to the intake keyword, failed it,
and returned without sending anything. Someone typing "aide" or "pomoc"
got silence, which is the worst possible answer to a request for help.

Both lists now cover the six shipped languages and are compared against
the folded message, so "cześć" and "czesc" are one entry and a capital
cannot miss. The match stays anchored to the whole message: "help me log
my weight" is prose the later paths should still see.

These are ordinary words rather than app labels, so there is nothing in
the bundles to derive them from.
2026-08-23 18:06:58 +02:00
Marc-André Bombeck 4d77fe2a43 fix(coach): let the off-topic gate read the four languages it could not
The gate is "looks off-topic AND does not look health", and both halves
were English/German word lists. Two things followed. An off-topic ask in
French, Spanish, Italian or Polish was never recognised. And a genuine
health question in those languages that happened to brush an English deny
word was refused outright: "Ho una serie di misurazioni strane" trips
"serie", and nothing on the allow side knew "misurazioni", so a question
about the reader's own data came back as a refusal.

The allow side is no longer transcribed. Every metric label key and the
health nav labels already name these concepts in all six bundles, and
those labels are the nouns people type, so the vocabulary is read from
`messages/<locale>.json` and a seventh language is understood the day its
bundle lands. Matching is whole-word over a shared fold applied to both
sides. A subtractive list keeps label scaffolding out; French "bien-être"
alone would have contributed "bien" and "etre" and marked nearly every
French sentence as health.

The deny side stays hand-written — these are not app labels — and its new
arms match the folded message. A pattern anchored with \b cannot match a
word starting with "ż", because neither the preceding space nor the letter
is an ASCII word character, so there is no boundary between them.

The prompt-injection bank is untouched. It reads the person's own message
and the foreign-text path is fenced elsewhere; this is defence in depth,
not an open door.
2026-08-23 18:03:28 +02:00
Marc-André Bombeck 267497dd3a fix(insights): measure citation coverage in the language the answer was written in
The normative-claim bank held English and German words. Insight
recommendations are generated in the reader's locale, so for French,
Spanish, Italian and Polish every recommendation scored non-normative:
the annotation reported zero normative claims and zero uncited ones, and
the admin quality dashboard read that as full coverage rather than as no
measurement at all. A check that cannot fail is indistinguishable from a
check that passes.

The bank now has one arm per shipped locale and the caller passes the
generation locale; the reader's arm and the English one both run, because
a fallback provider answers a non-English reader in English. Matching
folds both sides through the shared label fold and anchors the leading
word boundary, so inflections still hit while the everyday Italian
"soprattutto" no longer counts as a comparative.

These words are the model's prose, not app labels, so they are not in the
message bundles and cannot be derived from them. The structural test
refuses an empty arm instead: a seventh language fails the suite rather
than quietly scoring nothing. An empty arm also used to compile to an
alternation that matched every string, which would have flipped the same
blindness to the opposite extreme.
2026-08-23 17:55:45 +02:00
Marc-André Bombeck 4e182862c5 Let a passkey satisfy the passkey-removal step-up
The gate landed with a softer mode for accounts holding no second factor,
on the premise that they could not clear it. That premise was wrong. A
passkey is a possession factor here and the codebase already says so in
three places: a primary passkey login stamps Session.mfaVerifiedAt,
passkey sits in FRESH_FACTOR_METHODS so a passkey-proved elevation reaches
the fresh-factor routes, and the enrolment policy counts a primary passkey
as satisfying it outright. The only thing refusing such an account was the
reachability pre-check inside requireFreshMfa, which counts second factors
and nothing else.

So the mode is gone and the route asks for a full freshFactor: true with
proofSource: "any-possession" — a second knob that widens which credentials
count as "could ever prove this", and changes nothing about the gate. A
passkey-only account now gets a real gate with the re-provable
auth.stepup.required rather than no gate at all, and the dead-end
auth.stepup.mfa_not_enrolled is reserved for an account holding nothing.

hasSecondFactorEnrolled is deliberately NOT widened. It answers a different
question, and requireFreshMfaIfEnrolled asks it before deciding whether
account deletion, the data reset, the password change, the encrypted export
and key rotation gate at all — counting a passkey there would change five
destructive actions in passing. The two predicates sit beside each other
with docblocks saying why they differ, and collapsing them turns eight
existing tests red across three files.

Recovery is named rather than assumed. On Bearer: mint an elevation with
method "passkey". On the web: sign in again, which is what stamps the
session — there is no in-page re-proof for a cookie session because the
mint endpoint is Bearer-only by design. That limit is written into the
route docblock instead of left to be discovered, and the removal's refusal
now renders its own sentence in all six locales rather than the server's
English "second-factor" prose, which was wrong for the account this card
mostly serves.
2026-08-23 17:44:13 +02:00
Marc-André Bombeck 8ffa9cd87a fix(insights): scan one discovery matrix from every correlation surface
Four surfaces assembled the correlation-discovery matrix and three carried a
different channel set. The Coach `get_correlations` tool had neither the
environmental-exposure channels nor the custom-metric ones, so asking it
whether air pressure relates to your sleep met a matrix the pair had never
been in. Its own file header said the opposite - "the SAME full-matrix scan
the route runs" - and had said it since the weather channels arrived in
v1.25. The period narrative was missing those two families and the
compliance / symptom pair on top.

`src/lib/insights/discovery-matrix.ts` is now the one place a matrix is
built. v1.30.3 hoisted the fetch discipline into a shared module for exactly
this reason and left the assembly duplicated behind; this finishes it. The
route, the per-metric card, the Coach tool and the period narrative all call
`assembleDiscoveryMatrix` and get the same families. What still differs is
declared as an option with its reason at the declaration: the measurement
read mode (a read-cost choice, left per surface), the extra metric types the
narrative's delta beat needs, and the RATED mood factors.

Mood factors stay on the narrative alone. That capture kind is frozen, the
two surfaces that persist a discovered pair write its channel key into a
plaintext column, and a custom factor's key is an opaque id - so admitting
them elsewhere is a decision about what to ask, not a parity fix.

Restore the per-metric filter on the assessment card's relations. It was
written in place of the pattern-dismissal filter rather than chained with it,
so a weight card's prompt had been receiving every surviving pair in the
record while the function name, the docstring and the early-return guard all
still said one metric.

`discovery-matrix-guard.test.ts` freezes who may fetch a channel, who may
construct one, and who may scan. Each matcher asserts a non-zero match count,
so a matcher that has stopped matching fails rather than agreeing with the
allowlist.

The statistics are untouched - same Pearson, same exact p-value, same
Benjamini-Hochberg, same floors. The Coach's family is larger now, which is
the point: it is corrected over the same family the insights page is.
2026-08-23 17:38:14 +02:00
Marc-André Bombeck 283699db63 Refuse a backup that claims a section it does not carry (#237)
A restore's first act is to delete the class of records it is about to
rebuild, so a payload whose documents section is simply absent did not
"restore everything else". It emptied the vault, reported success, and left
the operator to find the hole later.

The whole file is refused instead, above the transaction that wipes the
account, and the refusal names the section and says nothing was changed —
an operator holding the only copy of an account cannot act on "restore
failed". The sections ride the error envelope as meta.errorCode
backup.section.missing, and the admin console holds them in a panel beside
the skip report rather than a toast that outlives nothing.

The manifest is the discriminator, and only the manifest. A portable export
leaves the mental-health screeners and the consent receipts out on purpose
and declares both as omitted; those files still restore. So does a file
whose section is present and empty, which is what an account with no
documents honestly writes, and so does every backup written before the
manifest existed. The integration test proves the distinction with the same
builder and the same deleted keys, differing only in what the manifest said.

The route is deliberately outside the published contract — requireAdmin is
cookie-only — so the OpenAPI document is unchanged.
2026-08-23 16:55:59 +02:00
Marc-André Bombeck e3be71f0e5 Gate passkey removal on the same step-up as second-factor removal
DELETE /api/auth/passkeys/{id} took a plain cookie session or a wildcard
Bearer, while DELETE /api/auth/me/mfa/webauthn/{id} beside it demanded a
fresh factor proof. The softer gate sat on the primary sign-in credential:
the last-method check stops an account locking itself out, but nothing
stopped a hijacked session stripping the credentials the owner signs in
with.

The route now goes through requireMfaManagementAuth, the same gate the
security-key removal uses, in a new "if-enrolled" mode. An account with a
second factor pays the full price on either transport — a freshly verified
cookie session, or a factor-proved X-Step-Up elevation on Bearer, so the
native client keeps the capability rather than being sent to the website.
An account with no second factor keeps the contract it had, because a gate
it can never satisfy is not a safeguard but a locked door in front of its
own credential list.

The elevation is spent immediately before the delete, so a foreign id or a
refused last credential does not burn a proof that then has to be minted
again. The route is added to the elevation allowlist with its reason, and
the either-factor enrolment test that was written out three times in the
API kit is now one function.
2026-08-23 16:55:59 +02:00
Marc-André Bombeck fffdc83ca4 Make the reset-every-threshold delete ask first
DELETE /api/user/thresholds without ?metric= erased the account's whole
override set on an omitted query parameter alone: no confirmation, no dry
run, and no rate limit of its own while the PUT beside it had one.

The wide form now wants { "confirm": "RESET_THRESHOLDS" } in the body — the
same typed-confirmation shape /api/settings/account and /api/settings/data
already use — and refuses 422 without writing anything. The ?metric= form
is untouched: it resets one band the person can retype, and the targets
sheet fires it in a loop. Both forms now run the PUT's 30 / 5 min limit.

The settings card's "reset all" control already opened a confirm dialog;
it now sends that answer to the server too. Its token is compared against
the route's declaration in the tests, so the two ends cannot drift apart
into a permanent 422.
2026-08-23 16:55:59 +02:00
Marc-André Bombeck c4544556f7 Merge pull request #830 from MBombeck/fix/stale-repo-truths
Point the doctor-report references at the route that exists
2026-08-23 16:49:25 +02:00
Marc-André Bombeck 01b3221c33 Point the doctor-report references at the route that exists
Both named /api/doctor-report, a family removed some releases ago. The
contributor doc sent a reader to a POST endpoint that answers nothing,
and the renderer's own header described itself as serving an endpoint
that is gone.

Found by the sweep behind the retired-route registry, which asks what
this repository still references rather than what a client calls. Two
hits, both prose, neither a call.
2026-08-23 16:15:11 +02:00
Marc-André Bombeck 46191337fc Merge pull request #829 from MBombeck/release/v1.37.26
v1.37.26 — the app reads what you wrote, in every language it offers
2026-08-23 15:54:16 +02:00
Marc-André Bombeck fed37829e2 chore(release): v1.37.26 — the app reads what you wrote, in every language it offers 2026-08-23 15:35:33 +02:00
Marc-André Bombeck 1ae21b5971 Merge pull request #828 from MBombeck/feat/retired-routes
Answer a retired route with 410 rather than a bare 404
2026-08-23 15:29:10 +02:00
Marc-André Bombeck b52262e27f Merge pull request #827 from MBombeck/fix/locale-matching
Match user-written text in every language the app ships
2026-08-23 15:28:41 +02:00
Marc-André Bombeck 4f2c90b66c Fold the side-effect tag through the shared helper
The three locale matchers were built in parallel and each grew its own
fold. Two of them are the same function: the side-effect tag fold and
foldForMatch agree character for character, so one now calls the other.

The third stays. foldLabel decomposes with NFKD, maps sharp s to ss and
joins with underscores; foldForMatch decomposes with NFD, leaves sharp s
alone and joins with spaces. That is a disagreement about who typed the
text, not an accident: one side of a lab comparison is a shipped label
retyped or prose a lab printed, where tolerating a different spelling
claims more than the fold can prove, while someone naming a metric to an
assistant is composing rather than reproducing. Both docblocks now say
so and name the other.
2026-08-23 14:58:51 +02:00
Marc-André Bombeck 5f8af25815 Merge branch 'fix/mcp-locale-aliases' into fix/locale-matching 2026-08-23 14:47:21 +02:00
Marc-André Bombeck 19d534432e Merge branch 'fix/lab-locale-parsing' into fix/locale-matching 2026-08-23 14:47:06 +02:00
Marc-André Bombeck bec4cb3dfb fix(mcp): let five of the six shipped languages name a metric
Three resolvers turned a user-authored word into an internal code by
comparing it against a hand-typed English list. The app ships six
languages, so five of them resolved nothing: `Fer` and `Żelazo` came back
as `unknown_nutrient` while the settings card rendered exactly those
words, and `poids` and `sommeil` reached no series at all.

Stop transcribing. `nutrients.names.*` and `measurements.type*` already
label these concepts in every bundle, so the match index is derived from
`locales` instead — a seventh language works the day its bundle lands,
with no edit at any call site. The nutrient tool's English labels now come
out of `messages/en.json` too, so the wire wording cannot drift from the
screen.

The MCP contract is unchanged in shape and stays protocol-level English.
What moves is which words are understood: `unknown_nutrient` /
`unknown_metric` still mean "could not place this word", distinct from a
placed name answering `no_data`. Nothing turns absence into data.

Two findings the sweep did not predict:

- `Puls` resolved to pulse-wave velocity, because the English
  display-name pass matches substrings and "pulse-wave velocity" contains
  it. An exact name now beats a loose English fragment.
- French and Italian use one phrase for body fat and fat mass, and three
  bundles use one for fat-free mass and lean body mass. A word two
  metrics claim resolves to neither; answering kilograms to someone who
  asked for a percentage is worse than saying the word was not
  recognised. The known set is pinned so a new collision surfaces.

The medication needles are the exception: they are drug names, with no
bundle to derive from. They fold to a normalised INN stem rather than to
a language, so `Metformin`, `Metformine`, `Metformina` and `Metforminum`
are one entry, and `Semaglutyd` and `Atorwastatyna` cost nothing to add.
A guard asserts no two molecules collapse onto one stem. Iron is the one
class with no stem to fold to — it is named for the element — so its word
list is hand-tabulated and says so.

Every English resolution that worked before returns the same answer.
2026-08-23 14:46:10 +02:00
Marc-André Bombeck 154b609768 refactor(documents): attach the derived analyte names to their signal class by identity
The derived names extended the analyte class by list index. Reordering the
signal list would have re-pointed them at the units or the report header with
nothing to notice, so the class is a named constant and the check compares
against it.
2026-08-23 14:44:23 +02:00
Marc-André Bombeck b06d7dbd92 fix(documents): recognise a lab report printed outside English and German
The gate that decides whether a transcribed document is worth an extraction
call scored four classes of evidence and needed two. Three of them — the
reference-range label, the analyte names, the report header — were written in
English and German, so a French, Spanish, Italian or Polish report scored at
most one: the units, which are the same everywhere. Auto-staging never fired
for it. The document was lost from the flow silently, because the manual
extract button stays available and nothing reads as broken.

The text is folded once — lower case, accents dropped — and every pattern is
matched against that, which on its own recovers a good deal: "Cholestérol",
"Créatinine" and "Emoglobina" reach the existing stems as soon as the accents
are out of the way. The reference-range labels and report headers of the four
locales are added by hand, because they are prose a lab printed and the app
owns no string for them.

The analyte names ARE derived, from `labs.catalog.<slug>` across every shipped
bundle: those are names the app itself displays, and a new locale should not
need an edit here to be recognised. Names under four folded characters are
dropped — "ALT" is German for "old", and a three-letter alternative in a gate
this cheap would make every German letter a lab report. The acronyms worth
having are in the hand-written half, where each was considered on its own.

Which way this errs, stated at the code: a false negative loses a whole
document from auto-staging, while a false positive costs one extraction call
and stages facts a person then declines — nothing commits either way. So the
vocabulary is widened, and the two-distinct-class rule holds the other side.
The derived names extend the analyte class rather than forming a fifth one, so
a document naming one analyte in two languages still scores one. Tests pin
each addition on a case that fails the gate without it, and pin the prose that
must keep failing it.
2026-08-23 14:28:53 +02:00
Marc-André Bombeck c5a01767aa fix(fhir): code a qualitative lab result recorded in any shipped locale
The lab form offers "negative" and "positive" as quick picks and writes the
label it rendered, so the column holds the bundle's own string in the language
the reading was recorded in. The SNOMED mapper matched that string against a
list transcribed in English and German, so "négatif", "negativo", "ujemny",
"positif" and "dodatni" all exported without a code — text-only on the one
document meant to be machine-readable.

The negative and positive arms read `labs.form.qualNegative` and
`labs.form.qualPositive` out of every bundle now. The form writes those exact
keys, so the write side and the read side cannot drift, and a new locale is
coded the day its bundle lands.

The detected / not-detected pair stays hand-written English and German, and
that is the honest limit of this change: the app ships no string for those
terms, they are prose a lab printed and a person copied in, and coding "non
détecté" or "niewykrywalny" would mean inventing clinical vocabulary in four
languages nobody here can check. This module's own rule is that an unverified
code is worse than an honest `.text`. When they need coding they need a quick
pick and a bundle key, which is the route the other two arms took. A test pins
that they stay uncoded rather than leaving it to be discovered.

Borderline stays uncoded as before; a test now pins that the derivation did
not sweep its bundle key up by accident. Comparison folds accents as well as
case, so a result typed without them still resolves.
2026-08-23 14:21:34 +02:00
Marc-André Bombeck ce73729916 fix(fhir): resolve a lab analyte's LOINC code from its name in any shipped locale
A biomarker minted from the labs catalog stores `t("labs.catalog.<slug>")` —
the name in the language of whoever minted it — and that stored name is what
reaches the FHIR exporter as free text. The exporter matched it against an
alias table written in English and German. So an account working in French,
Spanish, Italian or Polish exported "Cholestérol total", "Glucosa en ayunas",
"Glicemia a digiuno" and "Cholesterol całkowity" as text-only concepts with no
LOINC code, on the one document whose whole purpose is being read by another
system.

The names are DERIVED from `messages/<locale>.json` now, not transcribed into
this file. Both sides of the new slug map are app-owned identities with no
language in them, which is what makes it the one edit a new locale does not
need: `locales` grows, `messages/xx.json` lands, and the analyte names it
ships resolve the same day. Transcribing four more languages would have fixed
today's six and reopened the hole at the seventh.

The hand-written aliases keep precedence. They cover what the app owns no
string for — clinical abbreviations, the ways a person shortens a name — and
they were verified one at a time over several releases. A derived name landing
on the same key is a harmless duplicate; one landing on a different key would
be a translation typo re-pointing a verified mapping at another analyte, so
the build refuses it and the guard suite asserts the refusal held.

The lookup fold now drops accents before stripping punctuation. Without it a
name carrying diacritics lost them entirely rather than reducing to its base
letters — "Cholestérol total" folded to `cholestroltotal`, and "Hämoglobin" to
`hmoglobin`. That last one means the German umlaut spellings never resolved
either: the hand-written `hamoglobin` and `nuchternglucose` aliases only ever
caught the un-umlauted typing. Every pre-existing alias is ASCII, so the fold
is a widening and what resolved before resolves to the same key.
2026-08-23 14:19:18 +02:00
Marc-André Bombeck 2dc553057d fix(labs): read a reference range printed in French, Spanish, Italian or Polish
The free-text reference-range parser decided what a printed window meant from
an alternation of German and English words. The app ships six locales, and a
lab prints in the language of the country it stands in, so `jusqu'à 5,0`,
`hasta 5,0`, `fino a 5,0` and `do 5,0` all fell through to `low: null,
high: null`. The string was stored, the reading was then judged against the
biomarker's own band or against nothing at all, and no surface anywhere said
that the lab had printed a window the app could not read.

The vocabulary is TABULATED here, not derived from `messages/<locale>.json`
the way an app-owned word list would be. These words are prose a lab printed
on paper; the app owns no string they could be read out of, and the language
of a report has nothing to do with the language of the UI. So the table is
hand-written, keyed by the shipped `Locale` union so that adding a locale
fails to compile until someone has answered how that language prints a range,
and every locale's words are tried against every input at once. The cost is
written down at the table: a report in a language absent from it stays
text-only.

Three things had to change beside the word lists. Introducing words are now
stripped only on a second pass, because Italian "da", Polish "od" and French
"de" also state a floor on their own and stripping first read "da 3,5" as a
bare number. Input and table are diacritic-folded and their apostrophes
normalised, so a table row written "jusqu'a" meets a report's "jusqu'à" and
the curled apostrophe a word processor emits. And one-letter separators ("a",
"e", "y") are only accepted with whitespace on both sides, so "3.5e5" is not
read as a window. Decimal commas already worked and are pinned by the new
cases.

An unreadable window now has a name. `isUnreadableRange` separates "the report
stated nothing" from "the report stated something nobody could read" — the two
were indistinguishable at every call site, which is what let the French case
pass unnoticed. The manual form already showed the reader that the text was
kept but not read; the two ingest paths now count it into their wide event, so
an unsupported notation surfaces as a number rather than as silence.

The German and English lists are the previous alternation split word for word,
and the existing suite covering them passes unchanged.
2026-08-23 14:16:15 +02:00
Marc-André Bombeck f4c0eb0ab9 feat(api): publish retirement in the contract, the capability read, and the coverage guard
Three surfaces, one source. The registry the proxy answers 410 from now
also emits the tombstones into `docs/api/openapi.yaml` and rides on
`GET /api/meta/capabilities`, so a retirement cannot be honoured at
runtime and invisible everywhere a client could have read it first.

The contract publishes each retired path with 410 as its only response,
the removing version, and the replacement. `deprecated: true` is
imprecise — the word means "still works, stop using it", and these do not
work — but it is what makes a generator warn at the call site, and the
description carries the exact truth the flag approximates. `security: []`
because the answer is produced before any handler and reads no
credential; publishing it as authenticated would tell a client to sign in
to be told a path is gone.

The capability read carries the same list. That surface is the one a
client already polls on launch, so a retirement can reach it before the
failing call rather than through it.

The coverage guard gains a third state. Published and exempted both
describe a route that exists, so removing one used to leave exactly one
legal move — erase it from the contract as well — and that move is
invisible to every client already calling it. A registered path is now
required to be absent from `src/app` AND present in the contract, which
is the one combination the phantom-path case rejected outright. Both ways
out are named in the failure message.

Its docblock says what the state cannot do, because the first draft
overclaimed: a check over one commit's state cannot see a deletion, so it
cannot insist that a removal should have been registered. Proving that
needs the previous release tag, and the job running this suite checks out
at depth one with no tags, which would make the check one that silently
cannot fail. What is held instead is the registration's integrity, in
three directions and with the mutation for each written down.

The sharing-denial guard learns the same state: a retired path resolves
no record fence because it reaches no handler.
2026-08-23 14:06:52 +02:00
Marc-André Bombeck 87929eb3b8 feat(api): answer a retired route with 410 rather than a bare 404
A route removed on purpose still leaves a client calling it. As reported
in iOS #94: between 2026-08-08 and 2026-08-20 the native client asked
`/api/auth/me/research-mode` on every GLP-1 detail screen, got a bare
404, and painted a permanent error card with a retry button aimed at the
same removed path. Twelve days, on every reachable instance including the
public demo, which was built after the removal. Deleting the route was
right and the removing commit reasons it out in full; the answer said
nothing. A 404 from a deployment is indistinguishable from a broken
build, a reverse proxy pointed at the wrong upstream, or a typo in the
caller's own path, so reading it as transient and retrying was the
correct reading of the only evidence there was.

One registry, `src/lib/http/retired-routes.ts`, carrying the path, the
release that removed it, the replacement where there is one, and one
sentence on why. Every other surface reads it.

410 over a 404 with an error code because it is the status whose entire
meaning is "this existed here and is gone": a client that understands
nothing else about this API still learns not to retry. The code is not
dropped, it rides in the same envelope with `removedIn` and `replacedBy`
for a client that reads further. The status is the floor, the code is the
detail.

Answered in the proxy, before routing, rather than by a catch-all route
module: a catch-all under `/api` would intercept every unmatched path and
make the ordinary 404 ours to manufacture, which is a far wider blast
radius than the problem. The proxy already owns the exact-path decisions
of this shape. It reads nothing off the request but the path, so an
anonymous caller and an authenticated one get identical bytes and the
tombstone cannot become an authentication oracle.

Seeded from the removed-route set: every route path under `src/app` at
every release tag, unioned and differenced against the current tree.
Twenty-seven paths have been removed over the project's history; the five
registered here are the ones that were published or client-facing, and
each removal is pinned to its release by the route's presence at one tag
and absence at the next. Whether any client still calls one of them is a
separate question that evidence in this repository cannot answer, and the
registry deliberately makes no claim about it.
2026-08-23 14:06:37 +02:00
Marc-André Bombeck 97d0c26ceb fix(glp1): match side-effect tags by key, not by an English/German word list
The GLP-1 side-effect chips in the mood form write the localised label into
the flat `MoodEntry.tags` column, and three readers matched that label against
a hand-written list of English and German words: the therapy timeline, the
Coach snapshot, and the doctor report's GLP-1 block. The app ships six locales.
Tap the nausea chip with the UI in French, Spanish, Italian or Polish and the
day never reached the timeline, the Coach grounded its answers on an empty
side-effect list, and a clinician read an empty table over a record that had
three months of symptoms. Nothing on any of those surfaces said the table was a
filter rather than the truth. The three lists had also drifted apart from each
other.

The chips are a closed set with stable keys, so matching the label was the
defect and the key is the fix. `glp1-side-effect-tags.ts` holds the catalogue —
seven keys, each with the i18n key its chip renders — and the mood form now
draws its strip from it, so the write side and the read side cannot diverge
again. `glp1-side-effect-tag-match.ts` builds the label-to-key index by reading
`messages/<locale>.json` for every entry in `locales`, rather than transcribing
the labels into a second list. Transcribing would have fixed today's four
locales and reopened the same hole on the day a seventh is added; deriving
means a new bundle is matchable as soon as it lands, with no edit in the
matcher. Comparison folds case, accents and separators, so the English and
German tags already in the database keep resolving and a straight apostrophe
matches the typographic one the French bundle uses.

All three readers now report the catalogue key instead of the stored string.
The same recorded symptom yields one key whatever language it was tagged in,
which also fixes the mixed-language output an account gets after switching UI
locale; the doctor-report PDF resolves the key through the label map so the
clinician reads it in the report's language.

A tag outside the catalogue is still never counted — a free-text mood tag must
not reach a doctor as an invented symptom, and the rest of somebody's day does
not belong on a therapy timeline. It is no longer dropped without trace: the
timeline route annotates the unresolved count on its wide event, so the
classification rate stays answerable while the tag text stays in the database.

The Coach's copy of the list also carried `vomiting`, `reflux` and `erbrechen`.
Those are removed. No chip writes them, so they only ever matched a hand-typed
tag in two of six languages; keeping them would have rebuilt the defect inside
its own fix. Restoring either symptom means giving it a chip and a label in all
six bundles.

The response schema for `GET /api/insights/glp1-timeline` now enumerates the
keys, and its description no longer documents the bilingual match as if it were
the contract.
2026-08-23 13:56:32 +02:00
Marc-André Bombeck b76468f455 Merge pull request #826 from MBombeck/release/v1.37.25
v1.37.25 — the Coach stops answering with numbers it cannot check
2026-08-22 17:06:14 +02:00
Marc-André Bombeck 590911ca72 chore(release): v1.37.25 — the Coach stops answering with numbers it cannot check 2026-08-22 16:49:04 +02:00
Marc-André Bombeck fefda545ae Merge pull request #825 from MBombeck/verify/coach-grounding
Grade the Coach turn that went looking and found nothing
2026-08-22 16:38:12 +02:00
Marc-André Bombeck 1efac85a68 Merge pull request #824 from MBombeck/fix/openapi-meta
Register the schemas that annotated themselves into nothing
2026-08-22 16:24:41 +02:00
Marc-André Bombeck 6f2f43bb49 Say what the AI surfaces actually compute
Three places where the copy promised more than the handler delivers.

The hero's personal-baseline line rendered unconditionally while both its
siblings in the same meta row gate on their own data. It claims the subtitle
above it was drawn from the reader's own last 90 days, but with no briefing the
subtitle is fixed fallback copy computed from nothing — so an account with no
briefing at all was told its generic sentence rested on a personal baseline.
Gate it on the briefing, like the rest of the row.

The pulse sub-page promised a personalised Karvonen target band. Karvonen is
not computed anywhere: the band comes from CDC/NCHS population percentiles by
age and sex, and falls back to a fixed 60-100 for a reader with no age on file.
The copy now says that in all six locales, and the fallback's own source label
says it is a general adult range rather than a personal one, because that arm
is the same band for everyone. Karvonen itself stays unimplemented; whether to
build it is a product decision, not a copy fix.

The Coach's `allTime` window returns 365 days, identical to `lastYear`, and it
is the default. "year so far" was wrong too — a rolling 365 days is not
year-to-date. Both labels now say what the reads do. The two options remain
functionally identical and one of them should probably go, but removing a
default is a product decision.
2026-08-22 16:14:54 +02:00
Marc-André Bombeck c1811bc85b Stop narrating rollup buckets the record cannot account for
A rollup band outlives the rows it was folded from. The read-swap falls back to
live SQL only when a band is EMPTY, so a bucket that is merely wrong is served
as current; `ensureUserRollupsFresh` repairs the DAY tier over the trailing 90
days only, and keys off `Measurement.updatedAt`, which a hard delete does not
bump. The WHOOP body sync hard-deletes a WEIGHT row with no invalidation, so a
MONTH bucket keeps reporting a value the record no longer holds.

The block was handing the model two irreconcilable accounts of the same record
and marking neither: the coarse tail said one thing, the all-time extremes read
live beside it said another, and `asOf` stamped the whole thing current because
it is derived from raw reading age and knows nothing about rollup age.

Reconcile them where they are assembled. A bucket mean is an average of real
rows, so it cannot fall outside those rows' own all-time extremes — when it
does, the band is describing readings the live read cannot see. That is an
invariant rather than a heuristic, so the disputed tail is dropped and
`asOf.coarseHistoryWithheld` records that it went. Narrating a ghost is worse
than narrating less.

`currentForTodayClaims` stays keyed to raw recency, which is what it means. The
surviving readings really are from today, and suppressing a true present-tense
statement to punish a stale history band would trade one dishonesty for another.

The bucket on disk is still wrong, and a wide event now says so. The deeper fix
is to make the tier notice — compare a bucket's `computedAt` against the type's
in-window MAX(`updatedAt`), or invalidate on the hard-delete path — which is a
larger change than this repair.
2026-08-22 16:14:54 +02:00
Marc-André Bombeck 251a42bb0a Grade the Coach turn that went looking and found nothing
The numeric grounding guard keyed its activation off `loop.toolResults` alone.
A tool that finds nothing resolves to `{ present: false, reason: "none" }` with
no `available` payload, `runCoachToolLoop` drops that shape, and the no-tools
snapshot fallback is populated only in the non-tool branch — so the guard sat
out every turn where the record was empty, which is precisely the turn where a
fabricated figure is likeliest and does the most harm. Ask about a metric you
have never logged and an invented number was persisted and streamed verbatim,
with no withheld-figure marker to say it had never been checked.

`toolTrace` is the discriminant, because it records the pure misses the results
array drops. Tools ran and every one missed: grade the reply — an empty ledger
there is not missing information, it is the positive statement that nothing can
be cited, so `findUnverifiedCoachNumbersInLedger` takes an explicit opt-in to
grade against it rather than no-opping. The model answered without calling a
tool: still dormant, unchanged, because the tool-mode base prompt carries no
pre-computed figures and flagging a legitimately recalled one was the v1.32.1
regression. The inventory counts ride along as a widener so a plain count
restatement stays grounded.

Eliding the digits is not enough on an empty record. "Your sleep averaged […]
minutes, up from […]" still asserts a series, an average and a direction for a
metric with no readings; only the precision goes, the false claim stays. So a
turn that missed every tool and lost a figure to the guard is replaced with the
honest answer, in all six locales. Scoped so a reply whose figure reconciles
against a prior turn or an inventory count is left alone.
2026-08-22 16:14:54 +02:00
Marc-André Bombeck d49479bc64 Pin where the Coach stops checking its own numbers
Three characterisation tests for grounding gaps found while verifying that
every figure the Coach states comes from the record.

The numeric grounding guard rewrites any figure the turn's Grounding Ledger
cannot account for, and it holds: removing the strip reddens the existing
cross-turn ledger test. What is not covered is its activation. On the tool
path the guard runs only when `loop.toolResults` is non-empty, and a tool that
found nothing resolves to `{ present: false, reason: "none" }` with no
`available` payload, which the loop drops. So the guard disarms itself exactly
when the record is empty: ask about a metric with no readings, and an invented
figure is persisted and streamed verbatim, with no withheld-figure marker to
tell the reader it was never checked. The no-tools snapshot fallback is
populated only in the non-tool-mode branch, so the tool path has nothing to
fall back to, and every cloud provider runs the tool path.

Separately, a rollup bucket outlives the rows it was folded from. The read-swap
falls back to live SQL only on an empty band, `ensureUserRollupsFresh` repairs
the DAY tier over the trailing 90 days only, and it keys off
`Measurement.updatedAt`, which a hard delete does not bump. The integration
test reproduces the hard `deleteMany` in the WHOOP body sync against a
MONTH-band bucket: the deleted value keeps reaching the Coach's coarse tail
while the all-time extremes beside it report only the surviving value, and the
block is stamped current because `asOf` is derived from raw reading age and
knows nothing about rollup age.

All three assert current behaviour and carry a docblock saying so. Closing
either gap will redden them, which is the point.
2026-08-22 16:14:54 +02:00
Marc-André Bombeck 475db3073c Merge the second half of the meta sweep
The generated document is the whole visible effect of both halves, so it
conflicted line for line. Regenerated from the merged registry rather
than resolved by hand.
2026-08-22 15:38:10 +02:00
Marc-André Bombeck 3ae5bfe1c0 Capture the schemas that annotated themselves into nothing
`.meta()` clones the schema in Zod 4 and registers the clone, so a bare
`schema.meta({ id, description })` statement registers nothing at all.
Forty-one of them sat across nine route modules. The ids they named —
`MeasurementType`, `MeasurementSource`, `LoginPasswordRequest`,
`CreateMeasurementRequest`, `CreateBatchWorkoutRequest` and thirty more —
reached `components.schemas` zero times, the descriptions written for them
were published nowhere, and every use site inlined an anonymous copy. A client
generated from the contract got duplicated nameless types where one named
model belongs, which is the part that matters, because the iOS client is why
the contract is published.

Forty of them now bind their clone, and every use site points at it. Where the
schema comes from `src/lib/validations/*` the import is aliased and the clone
takes the name the use sites already spell, so nothing mutates the runtime
validation schema. The seven that cross module boundaries are exported from
`./shared` and the eight consumers import them from there; importing the raw
schema from the validation module instead is exactly what inlined them.

Thirty-four named components appear where inline copies stood. Fully
dereferenced, the document differs by eighty-six added descriptions and
nothing else: no operation's request or response shape moves. `CoachPrefs`
was already force-registered in the index and finally carries its description.

Five ids legitimately stay out of `components.schemas` —
`ListMeasurementsQuery`, `ListAllergiesQuery`, `ListEncountersQuery`,
`SuggestEncounterQuery` and `ListPractitionersQuery`. The emitter expands a
`requestParams.query` object into inline `parameters`, so a query id has
nowhere to land; they stay in the assigning form for consistency.

Three findings the wiring turned up:

`CreateShareLinkRequest` and `HealthRecordExportRequest` were annotated in the
Coach module, which imported the two schemas for no other reason and never
referenced them. Both operations that send these bodies live in the
health-record module, so the annotations move there. Both descriptions
described a `sections` field: the export body has no such field and rejects it
with a 422, and the share-link body freezes scope through `selection` plus
`documentIds` / `documentOnly`. Publishing either sentence verbatim would have
published a lie, so both are corrected to the shape the routes actually take.

`CoachPlansListQuery` — the forty-first — named a component that nothing
referenced and that a query object could never reach. The operation publishes
its two parameters by hand, because the schema carries a cross-field
refinement the expansion cannot express, and every clause of the annotation is
already published on the operation and on both parameters. It is deleted
rather than left registering nothing.
2026-08-22 15:34:32 +02:00
Marc-André Bombeck 60e17a2617 Publish the mood-tag layout schema its own description relies on
The annotation was already in the assigning form and still never reached
the document, because both consumers extend the base rather than
reference it and .extend() builds a new object. Same shape as Medication
and CoachPrefs, same remedy: name it in the forced-registration block.
2026-08-22 15:34:27 +02:00
Marc-André Bombeck 50287d2743 Merge branch 'fix/openapi-meta-b' into fix/openapi-meta 2026-08-22 15:29:51 +02:00
Marc-André Bombeck 4d53241574 Merge pull request #823 from MBombeck/docs/openapi-contract
Publish the contract the application actually answers: 262 paths to 410
2026-08-22 15:29:27 +02:00
Marc-André Bombeck 032ea5b1a0 Register the schema names the contract was discarding
Zod 4's `.meta()` clones the schema and registers the clone, so a bare
`someSchema.meta({ id })` statement registers nothing at all. Thirty-nine of
those across eleven route modules published neither the name nor the
description written for it: the schema inlined anonymously at every use site,
and a client generated from the contract got a duplicated nameless type where
one named model belongs. That last part is the cost that matters, because the
native client is the reason the contract is published.

Bind each annotated clone to a const and point the route table at that const.
Twenty-nine ids now emit under `components.schemas`, referenced from their
thirty use sites. Seven stay absent by design: they annotate
`requestParams.query` objects, which the emitter expands into inline
`parameters` rather than a component. `MoodTagLayout` stays absent too, for
the reason `Medication` and `CoachPrefs` already carry a forced registration
in the components block: its only consumer is an `.extend()`, and extending
builds a new object rather than referencing the base.

Two annotations in the illness module named ids that no route ever referenced,
`GetIllnessDayLogQuery` and `ListIllnessDayLogsQuery` — the day-log path
publishes the merged `GetIllnessDayLogsQuery` instead. They were dead twice
over, so they go rather than get wired to nothing.

`docs/api/openapi.yaml` grows the twenty-nine components and their refs. The
only other movement in it is thirty descriptions appearing where the text had
never reached the document. No request or response shape changes.
2026-08-22 15:24:05 +02:00
Marc-André Bombeck 965d41f1ed Say how every operation is authenticated
The document defined bearerAuth and cookieAuth and referenced neither,
so the schemes were decoration: a client generated from the contract
wires no credential and reads the whole surface as open.

The default now offers the two as alternatives, and the ten operations
reachable before a credential exists opt out with an empty array. The
opt-out list is derived from what each handler accepts, not from the
proxy's public-path list — /api/ingest/medication is on that list and
requires a Bearer token, so reading it as the answer would publish an
authenticated route as open. Writing the list from the proxy is exactly
the mistake the guard caught: /api/auth/oidc/callback went on it and is
not published at all.
2026-08-22 15:03:28 +02:00
Marc-André Bombeck 50b483d8d1 Merge the health-data route group
Two groups created environment.ts independently; one carried all six
paths, the other only the overview read, so the fuller side stands and
the barrel keeps one import.
2026-08-22 13:29:59 +02:00
Marc-André Bombeck c985f634aa Merge the environment and ingest route group 2026-08-22 13:28:18 +02:00
Marc-André Bombeck 30930b46d0 Merge the auth and integration route groups
Two component-id collisions, both from the same cause: two paths that
are two doors onto one action, documented independently.

DELETE /api/devices/{id} and DELETE /api/auth/me/devices/{id} both call
revokeDeviceCascade and answer with the same shape. Each grew its own
DeviceRevokeResponse, which the emitter refuses outright. The response
moves to shared.ts so neither module owns it and the next door onto the
same call finds it; the two envelopes keep separate names because an
envelope names an operation.

The settings module took both halves by hand rather than by keep-both:
one side added nine paths, the other three, with no overlap but a shared
import block and a shared reminder-thresholds entry that a mechanical
union duplicated.
2026-08-22 13:26:45 +02:00
Marc-André Bombeck bb9bf0ba68 Refuse what these four routes used to absorb in silence
Four surfaces answered a bad request by quietly substituting a good one. Each
fix comes with the test that catches it, and each test was confirmed red
against the old behaviour before the fix went back in.

`PATCH /api/user/ai-provider` inspected its body key by key with `typeof`
guards, so a numeric `model` or a boolean `baseUrl` failed every guard,
produced no entry in the update, and the write went ahead without it — a 200
that says "saved" for a field that was discarded. A body of nothing but such
keys came back as "No valid fields" naming none of them. The real schema now
lives in `src/lib/validations/ai-provider.ts`, the route runs one `safeParse`,
and a mismatch is the multi-issue 422 every sibling answers with. The accepted
field set is unchanged, and the object is deliberately not strict: an unknown
key has always been ignored here and still is. The one thing the schema has to
carry that no other does is that this body holds plaintext credentials, so no
rule may interpolate the value it rejected — noted where the next `.refine()`
would go.

`?slice=` on `/api/analytics` was compared against one literal and fell
through to the DEFAULT body on anything else, so `?slice=summary` answered 200
after running the heaviest chain on the surface. Invisible and expensive at
once. Closed enum, 422 on anything outside it.

`?metricType=` and `?limit=` on `/api/personal-records` were parsed
defensively, which read as robustness and behaved as silence — and in one
direction it was worse than silence: dropping an unrecognised `metricType`
WIDENS the read to every metric, so a typo returned more of the record than
was asked for. Both refuse now, and the 500 ceiling refuses rather than
clamps, because serving a different number of rows than were requested is the
same quiet substitution. No caller in the tree sends a value the new rules
reject.

`POST /api/ingest/medication` bucketed on the client address, so a household
running a chat bridge, a button and a home-automation rule — the normal
deployment for this route — put all three in one 60/min cell and let the
chattiest starve the rest. It already resolves a per-caller identity two lines
further down and threw it away; the bucket is that token now. A request that
resolves no token keeps the per-IP bucket it always had, through the shared
anonymous helper, so a flood is still capped and a broken proxy chain
collapses into the tight global cell rather than a shared "unknown" one. Its
429 goes through `apiError` and carries `meta` like every other refusal.

Two older tests pinned the defects by name — "drops an unknown metricType
silently" and "falls back to default on garbage ?limit" — and one pinned a
throw where the rest of the surface returns an envelope. All three are
rewritten with the reason beside them.

The generated YAML is deliberately not in this commit.
2026-08-22 13:23:48 +02:00
Marc-André Bombeck edccc17a4d Register the rest of the export, insights and medication surface
Twenty-five path entries across nine domains, all of them served and none
of them described. Same cause as the first batch: `openapi:check`
compares the registry against the YAML and never the route tree against
the registry, so a route registered nowhere drifts with every gate green.

Four groups where the contract had to say more than the shape does.

The full backup is the download that carries a whole record in plain
text, so what it contains is a safety question. It has two modes and this
route reaches only one: called with no options, it always emits the
PORTABLE form — decrypted columns, no tombstones, no row ids — while the
disaster-recovery form belongs to the worker and the admin path. Three
things it leaves out say so in the payload's own manifest: document
bytes, workout GPS and per-sample series, and the sensitive pair, where
the screener answers include the PHQ-9 self-harm item and a consent
receipt restored elsewhere would assert an agreement that operator never
obtained. The undeclared gap is named too, since roughly thirty models
the plan marks as backed up still have no reader or restore branch.

The four intake mutations differ in ways a caller has to know before
firing one. The by-id delete, the bulk delete and the purge all
tombstone, so the sync feed carries each removal; only the purge's
compliance rollups are dropped outright, and those recompute. The first
two refund the inventory stamp because not taking a dose puts the units
back; the purge deliberately does not, because refunding a whole history
would inflate the current container count instead. The bulk delete drops
unmatched ids silently, so a partial match succeeds with a lower count
than the ids sent.

The two provider-configuration surfaces are documented by what they do
NOT return. The chain answers provider types and boolean state, never a
credential. The per-medication ingest endpoint returns a raw token
exactly once, on the PUT that mints it, and a re-enable answers a null
token with `created: false` rather than re-issuing — the stored value is
an HMAC and there is no path back.

Insight generation costs money, so both gates are published with the
refusals they produce: the hourly per-user limit, and the day's token
ceiling, which is refused at reservation time before any provider is
contacted and carries its own code so a client can tell "too often" from
"the day's spend is gone". A 200 there does not mean a provider ran.

Two things the code said that were no longer true. The seeded-question
route's docblock declared it deliberately unregistered; it is registered
now, and a comment contradicting the registry is worse than none. And
the idempotency guard went red on `/api/insights/feedback`, whose
exemption said the path could not be published — which is exactly what
that leg exists to catch, so the entry is gone rather than the assertion.

`docs/api/openapi.yaml` is regenerated separately.
2026-08-22 13:23:25 +02:00
Marc-André Bombeck 75f4a39066 Merge branch 'docs/openapi-auth' into docs/openapi-contract 2026-08-22 13:18:42 +02:00
Marc-André Bombeck 79a1395104 Check the routes against the contract, and the contract against itself
The drift check compares the registry to the emitted YAML. It has never
compared the routes on disk to the registry, so a route that was never
registered produced no drift and no failure: the document stayed
internally consistent while going quietly incomplete. Two hundred and
twenty-two paths reached that state.

The coverage guard walks src/app, reads the verbs each module exports,
and requires every verb to be either published or named with a reason.
The reasons are kinds rather than free text, because these fall into a
small number of genuinely different shapes and writing one sentence
seventy-three times would hide the entry whose sentence is different.

The security guard is the same idea one level down. The document defined
bearerAuth and cookieAuth and referenced neither, so a generated client
wired no credential and read the whole surface as open. The schemes
being present is what hid it. The document now declares them as
alternatives, and the guard checks the reference rather than the
declaration.

Both are red until the routes are documented, which is the point.
2026-08-22 13:18:33 +02:00
Marc-André Bombeck 6f62f66105 Describe the WHOOP disconnect in the contract
The eighth teardown endpoint, missed when the seven siblings were split across
the earlier batches. It has no per-user unsubscribe to make — WHOOP webhook
subscriptions are registered once per developer app rather than per category
the way Withings does it — and it leaves the BYO-key credentials in place so a
reconnect does not force a re-paste.

Like every other `POST /api/<provider>/disconnect`, a repeat call answers 404
rather than an idempotent 200, and the description says so. That completes the
tally: all seven disconnect endpoints refuse a repeat, all six credential
DELETEs accept one.
2026-08-22 13:18:25 +02:00
Marc-André Bombeck aa80cb45c1 Say which rule a rejected Web Push subscription broke
`POST` and `DELETE /api/notifications/web-push` both answered a flat
`apiError("Invalid data", 422)` and discarded the Zod issues. A non-HTTPS
endpoint, an endpoint aimed at an internal host, an over-long one and a missing
subscription key produced byte-identical bodies, so a browser whose
subscription was refused could not tell a fixable client bug from a policy this
instance will never satisfy. Both now answer the multi-issue envelope every
other body-parsing route in the tree uses.

Echoing the issues is safe here and the route says why, because it is the kind
of thing that gets re-derived wrongly later: the endpoint is a subscription's
routing secret and `keys` is its crypto material, but `sanitiseZodIssues` emits
`path`, `code` and `message` only — the rejected value lives in `issue.params`
and stays server-side — and every message this schema can produce is a fixed
string or a length/format default rather than an interpolation. A test pins
that none of the four secrets reaches the wire, so a future schema change that
adds an interpolating message fails here instead of leaking quietly.

The tests assert on content rather than status: a status-only check passes
against the flat error it replaces, which is how this survived. Two of them
compare whole bodies between two different refusals and require them to differ.

The two `/test` routes were checked in the same pass and need nothing. Neither
accepts a body — they take no parameters at all — so neither runs a Zod parse
to discard. Their 422s already carry `not_configured`, `vapid_not_configured`
and `rate_limited_self` as machine-readable codes.
2026-08-22 13:17:45 +02:00
Marc-André Bombeck b6e34d1264 Close five honesty gaps on the integration surface
Each of these made the server report something that was not so, and each now
has a test that fails without the fix.

The Withings credential DELETE wrote no audit row and left the ledger at
whatever state it last held. Fitbit, Google Health and WHOOP all park theirs,
and three of them say in their own comments that they do it for parity with a
list that never included Withings. A client reading `state` after the teardown
was told `connected` about a connection that no longer existed.

Oura's and Strava's credential DELETEs audited only when an access token
happened to be present, so removing a stored pair that had never completed
OAuth left no trail at all. Polar's twin has always done both unconditionally;
they match it now. The old Oura test asserted the skip, which is why the gap
survived a rewrite — that expectation is inverted here, with the reason next to
it.

The Withings and WHOOP manual syncs had no rate limiter, while `fullSync` walks
full history against a per-user provider budget. The Fitbit route's own comment
records that it was the outlier until it got one; these two were never brought
along. Both now carry the same 5/60s baseline and 1/hour full-sync buckets as
their siblings.

Every sync route parsed its body inside a catch commented "no body provided",
which was true for one of the three ways to reach it. An absent body still
means an incremental run — that is the documented shape and the web cards send
it. A body that is present and unparseable is now 400, and one that fails the
schema is 422: `{"fullSync": "true"}` used to be read as false and answered 200,
so a client that asked for full history and mistyped the value was told the run
it never requested had succeeded. Unknown keys are still ignored. The four
copies collapse into one helper.

The consolidated integration status swallowed a failed freshness query into an
empty array, which is exactly what a record with nothing in it also produces —
so the signal built to say "this metric has gone quiet" answered "nothing has
gone quiet" when it had failed to look. `metricFreshnessDegraded` separates the
two, as one flag rather than one per entry, because it is a single query for all
eight providers.

The contract follows the behaviour in the same commit.
2026-08-22 13:13:18 +02:00
Marc-André Bombeck e39e2b60c2 Let the GLP-1 read reach the record its own write already reaches
`GET /api/medications/{id}/glp1` resolved the caller as themselves while
the POST beside it has resolved the record since v1.37.0. A manager
inside a shared record could therefore add a titration step to a
medication whose history the same path refused them: may write, may not
read. No reading of the sharing model produces that shape, and the
sibling reads on the same medication — `/inventory`, `/side-effects`,
`/cadence` — have all resolved the record at READ level for releases.

The read joins them at that level rather than at the POST's MANAGE,
because it is strictly narrower than the write already admitted. The
module was already on both reviewed allowlists, so nothing is newly
delegable; its reason line said the module was reached through the
MANAGE arm alone, which is no longer true and now says so.

The gap survived this long because a route that refuses every switched
caller is indistinguishable from a route nobody classified. Three legs
close that: a delegate scoped to medications reads the owner's titration
history and still cannot reach their own medication, a delegate scoped
elsewhere is refused, and a caller who never switched is unchanged. Both
delegate legs assert the refusal CODE rather than the status, because the
pre-fix answer was also a 403 — verified by reverting the handler, at
which point the first leg reads 403 for 200 and the second reads
`sharing.not_permitted` for `sharing.access.denied`.
2026-08-22 13:04:33 +02:00
Marc-André Bombeck a283211586 Describe the remaining auth, settings and notification-transport surfaces
Twenty-eight more verbs that exist, are called, and said nothing in the
contract: registration, password rotation, the profile patch, the SSO entry
point, passkey enrolment, the Codex device-auth flow, the device list and its
revocation cascade, four per-user preference scalars, the email channel and the
four channel self-tests, the record wipe, the privacy facts, the update check,
and the Web Push transport.

Four of them needed more care than the rest.

`GET /api/auth/oidc/login` is documented as the two-armed route it is. The
browser arm redirects to the provider; the native arm takes `client=native`
plus a mandatory S256 challenge and returns to a compile-time scheme with a
one-time code — or an MFA ticket when the account has a second factor. The two
PKCE exchanges in play are named apart, because confusing them is the way to
get this wrong.

`POST /api/auth/register` is the only genuinely anonymous surface in the set,
and its refusals are stated exactly: the SSO-only block, the 5-per-15-minutes
bucket that collapses rather than falls open, the invite that is consumed
whenever it is sent, the zero-user bootstrap that mints the first admin under a
lock, and the one 409 that covers a taken email and a taken username so it
cannot be used to enumerate accounts. `POST /api/auth/password` is a change
behind authentication, not a reset, so it is described as one.

`DELETE /api/settings/data` names what it takes and what it leaves: ninety-nine
models hard-deleted, the account's own personal columns reset, credentials and
interface preferences kept, one transaction, and a confirmation string that is
deliberately not the one account deletion wants.

Two collisions surfaced while wiring this up and are resolved rather than
worked around. `PUT /api/auth/profile` and `PATCH /api/user/profile` are two
doors onto one handler, so they now share one published request component
instead of two descriptions of one validator. Their RESPONSES differ, though —
one carries id and role, the other the display preferences, and neither is a
superset — so they are named apart and the older description no longer claims
to cover both.

The four Web Push and APNs surfaces land in their own route module rather than
beside the notification preferences: that module answers what gets sent and
whether it arrived, this one the plumbing a client sets up and then verifies.
Both self-tests report failure inside a 200, which the contract says plainly,
because a client reading only the status will tell someone their notifications
work when they do not.

The generated YAML is left out; it is regenerated once the remaining groups
land.
2026-08-22 13:03:11 +02:00
Marc-André Bombeck 49da15feaa Publish the nineteen routes the drift check could not see
`openapi:check` compares the registry against the committed YAML, so a route
that was never registered produced no drift and no failure. These nineteen
had shipped without a contract: the health probe, the dashboard analytics
aggregate, the profile summary, personal records, the badge grid, the whole
environmental-context module, both onboarding writes, the Apple Health import
pair, the external medication ingest, the self-context adopt, the AI-provider
update and the AI connection probe.

Each entry is read off the route rather than inferred from a neighbour, so it
carries what a client cannot guess: that `/api/health` answers a bare object
and not the envelope, that `/api/analytics` records a score row and mints
pattern ids on a GET, that `/api/ai/test` reports a provider failure as 200
with `ok: false` because a 5xx comes back as somebody's HTML error page, that
the ingest route replays with 200 and creates with 201, and that a home
location re-stamps its effective-from instant on every write.

Three route-local request schemas move to `src/lib/validations/` so the
published shape and the runtime parse are one object rather than two copies —
a route module may only export handlers, which is why they could not be
imported where they were. The AI-provider PATCH has no schema to move: it
hand-rolls its parse field by field, so its entry says so and spells out that
a wrongly-typed key is skipped in silence.

The generated YAML is deliberately not in this commit.
2026-08-22 12:54:43 +02:00
Marc-André Bombeck 7f67c24ecc Describe the rest of the integration surface in the contract
Thirty-seven more paths the clients already call and the published spec did not
describe: the six OAuth providers' credential, status, disconnect, sync and
probe endpoints, the cross-provider surfaces under `/api/integrations/*`, the
managed record's configuration tree, and the native device-revoke path.

Where providers share a verb name they do not always share a contract, and the
descriptions say so instead of averaging it out. Three divergences are stated
per path. A disconnect refuses a repeat with 404 on six providers and answers an
idempotent 200 on two. `/api/<provider>/test` answers a bare probe result while
the same-named `/api/integrations/<provider>/test` adds the connection's last
sync, and the Google Health one accepts a body that replaces the response shape
outright. `GET /api/withings/status` refreshes and re-persists the OAuth token
while it reads; the other six status endpoints write nothing, and each now says
which it is.

Two further facts a client cannot infer. The Withings credential DELETE writes
no audit row and leaves the ledger at its last state, unlike every sibling, so
its `state` is not proof of a live connection afterwards. The WHOOP connect
ticket is a credential in a response body, returned once and stored only as a
hash.

The Google Health credential schema moves to the validations module; the managed
record's six strict patch schemas are exported from where they already lived, so
the contract publishes the objects the handler parses rather than a restatement.
2026-08-22 12:44:36 +02:00
Marc-André Bombeck 63f791120a Stop the API switch hiding live tokens, and cap the unit-preference body
Four defects the registry work surfaced, each with a check that fails without
the fix.

`GET /api/tokens` no longer consults the instance-wide API switch. That switch
gates the surfaces a token is FOR — external ingest, the MCP bridge — and not a
token's ability to authenticate: nothing on the `requireAuth` path reads it, so
a token minted before an operator flipped it stays live while it is off, and
refusing the list hid exactly the credentials their owner most needed to see,
their own signed-in phone among them. The revoke keeps the gate; the asymmetry
is stated in both route comments and pinned by the test, because widening it is
a decision about what the switch means rather than a fix to the read.

`PATCH /api/auth/me/unit-preference` reads its body through `safeJson` with a
1 KB cap, like the scalar beside it. It used a bare `request.json()` and was the
one endpoint in the family with no body-size limit at all — the new test proves
it by sending 2 KB and watching the old handler answer 200. Malformed JSON now
answers 400 like every sibling instead of 422; the only caller checks `res.ok`
and never the status, so nothing depends on the old code. The existing
malformed-JSON assertion was changed deliberately: it pinned the inconsistency,
not a contract.

`PATCH /api/auth/passkeys/{id}` returns the multi-issue envelope. It answered a
flat "Invalid request", so an empty name and a 200-character name produced
byte-identical bodies and the form had nothing to show beside the field.

`GET /api/user/thresholds` has a header that describes the handler. It promised
`{ defaults, overrides, effective }` and has always returned
`{ effective, overrides }`. The guard compares the two, so the comment cannot
drift again in either direction.

The two published operations whose contracts moved are updated with them.
2026-08-22 12:39:43 +02:00
Marc-André Bombeck d66c4f6cdc Register eleven served routes in the OpenAPI contract
Eleven routes the native client calls have never been in the registry, so
`docs/api/openapi.yaml` does not describe them. Nothing caught it:
`openapi:check` compares the registry against the YAML and never compares
the route tree against the registry, so a route registered nowhere drifts
with every gate green.

  GET       /api/analytics
  GET,POST  /api/cycle/symptoms/custom
  GET       /api/dashboard/summary
  GET       /api/environment
  GET       /api/export
  GET,PUT   /api/insights/settings
  GET       /api/insights/targets
  GET,POST  /api/medications/intake
  GET,POST  /api/medications/{id}/glp1
  GET       /api/mood/insights
  GET       /api/personal-records

Each contract is derived from the handler rather than from its comments:
the methods it exports, the parameters it reads with their real defaults
and bounds, the statuses it can actually produce, whether it resolves the
record fence, and which module gate it sits behind. Where the answer is
awkward it is written down rather than smoothed over — `/api/export`
answers a bare `data` key and not the standard envelope; `/api/analytics`
serves two unrelated shapes behind one query parameter and records the
health score it computes; `GET /api/medications/intake?scope=today`
projects rows before it reads them; the GLP-1 GET is not delegable while
the POST on the same path is; and `highlightInsight` on the dashboard
summary is pinned null by the handler and has never carried anything.

The intake aggregator's query and body schemas move from inside the
handler to `@/lib/validations/medication`, so the contract generates from
the same object the route parses with instead of a second copy of it. The
environmental overview gets its own route module because nothing owns that
surface. `docs/api/openapi.yaml` is regenerated separately.
2026-08-22 12:30:05 +02:00
Marc-André Bombeck b6efc6cb5a Register the sixteen auth, settings and discovery routes the spec never had
`pnpm openapi:check` compares the registry against the committed YAML and
never the routes against the registry, so a route that was simply never
registered stayed invisible to the gate. Sixteen of them are called by the
native client and describe nothing: sign-out, the three per-user preference
scalars, the two pre-session discovery reads, passkey login options, the
passkey rename and delete, registration status, the consent latest-receipt
reader and its revoke, account deletion, the instance service switches, the
API-token list and revoke, the threshold overrides, the version read, and the
assistant feature matrix.

Each contract is derived from the handler rather than from its docblock, so
the published statuses are the ones the code can actually produce — the 413 on
a 1 KB body cap, the 400 the consent family answers where the rest of the API
answers 422, the 403 an instance-wide API switch produces on a token READ, the
last-admin and last-Guardian refusals on account deletion, and the fresh-factor
arm that a Bearer transport cannot clear at any scope.

Four request bodies moved to the validation modules the handlers now parse
with, so the published wire cannot drift from the runtime one: the three
`/api/auth/me` preference scalars into a new `user-prefs` module, and the
passkey rename beside the login schemas. Behaviour is unchanged.

The generated YAML is left out; it is regenerated once the remaining groups
land.
2026-08-22 12:24:52 +02:00
Marc-André Bombeck 1c2e6c5c80 Merge pull request #822 from MBombeck/work/backup-clinical
Carry the clinical history: ECG strips, efficacy targets, schedule eras
2026-08-22 12:23:21 +02:00
Marc-André Bombeck c8035fdd78 Describe the integration, notification and MCP surfaces in the contract
Sixteen routes the native client already calls were absent from the OpenAPI
registry, so the published spec said nothing about them. `openapi:check`
compares the registry against the YAML and never the routes against the
registry, which is why the gap survived.

Nightscout status / test / disconnect, the WHOOP credential and status reads,
and the Withings status / disconnect pair land in the integrations module. The
three per-channel configs under `/api/settings/*` join the settings module; the
notification preference and delivery-health surfaces get their own module, as do
the MCP connector connections and tokens.

These are credential-bearing surfaces, so the contract states what each response
actually carries. Every channel GET reduces its secret to a boolean, and the
descriptions say so, along with the consequence: a client cannot read the value
back, so an empty value on the way in preserves the stored one rather than
clearing it. `POST /api/mcp/tokens` is the one operation that returns a usable
Bearer, and its description says outright that this is the only copy.

Two inline request schemas move to the validations modules they belong in, so
the registry documents the same object the handler parses rather than a
restatement of it.
2026-08-22 12:21:16 +02:00
Marc-André Bombeck a74dc289a8 Carry the archived schedule eras, chain and all
The register said a restored medication keeps today's schedule and loses
the record of when the dose or the timing moved. Measured, it costs more
than a record: the band minter reads each past day against the schedule
that was live THEN, so an account that came back without its eras had its
own compliance history rewritten against a plan it was never on.

The hard part was supersededByRevisionId, the pointer from a corrected
ARCHIVED era to the MANUAL row that replaced it. Three things about it
had to be settled.

It is a bare id column with no relation, so nothing in the database
refuses a value that points at nothing. That makes losing it quieter and
worse than a broken foreign key would be: every era consumer SKIPS a row
that carries the pointer, so a corrected era whose link came back null
goes live again beside its own correction, and the timeline shows one
window twice with past days minted against whichever the query read
first.

A portable restore mints fresh ids, so the pointer cannot travel as one.
It travels as a POSITION in the drug's own ordered era list. That list is
the only address space both ends share: the builder sorts it totally
(validFrom, then createdAt, then id) so two eras sharing an instant
cannot swap places between two exports of the same account, and the
pointer never crosses a drug, because every route that writes it scopes
the update to one medication. The same mechanism serves both purposes
rather than one carrying ids and the other positions.

Writing it needs two passes, because the row a link addresses is as often
written after the row addressing it as before. Pass one creates every era
with the link null; pass two patches the links once every position has an
id.

A hand-edited file that names a position out of range, or an era's own
position, gets the era and not the pointer, and the position is reported
as scheduleRevisionLink with the JSON path into the file. Refusing the
file would cost an operator every era of every drug over one bad integer,
and writing the link would point a correction at whatever row happened to
be there. A row that supersedes itself is treated the same way: every
consumer would skip it, so the era would vanish from the timeline while
still sitting in the table.

The round trip seeds three eras with one supersede among them and asserts
the shape of the chain, then asserts that exactly two are live. Three
rows with every link null satisfies any count and has thrown away the
only thing the pointer says.
2026-08-22 11:51:52 +02:00
Marc-André Bombeck 768320f3d3 Restore what each medication was supposed to move
The register said the drug comes back with no statement of what it was
for, which is exactly what a pinned efficacy target is: a row exists ONLY
where the person overrode the derived ATC / name resolution, so it is a
decision and never a computation. Nothing recomputes it after a restore
because there is nothing to recompute it from.

The lab arm travels as a biomarker NAME rather than an id, the way a lab
result's cross-reference already does. A portable restore mints a fresh
catalogue id, and `Biomarker` is unique on `(userId, name)`, so the name
is the only end of the reference that survives the trip.

The obstacle was ordering, not machinery: the remap map already existed,
but the drugs are rebuilt several hundred lines before the analytes are.
The targets are collected against the id each drug actually got and
written in a second pass once the biomarkers exist.

The alternative was hoisting the biomarker restore above the medications,
and it loses on two counts. `biomarkerByName` and `restoredBiomarkerIds`
are read by the lab-result loop immediately below the block, so moving it
would separate a map from its only other consumer and leave a later edit
free to re-order them back with nothing noticing. And the dependency
would read backwards: a pinned target is a leaf of the medication tree,
and letting a leaf dictate where the clinical record gets rebuilt inverts
what the file is about. The second pass states the constraint where it
applies instead of hiding it in a line order.

A named analyte the restore did not put back is dropped and reported as
medicationTarget rather than written. `biomarkerId` is a real foreign
key, so a dangling value would fail the constraint and cost the whole
account over one override. Dropping beats nulling here because the
override IS the reference: a row with neither arm set is what the
resolver already reads as "no override", so keeping it would restore
something that means nothing while still holding the primary slot.

The round trip asserts the restored target points at the biomarker the
restore itself wrote, resolved from the database rather than remembered
from the fixture. Counting would have passed on a row whose biomarkerId
came back null, and nothing else would have complained: the resolver
falls back to deriving a target and the page still renders.
2026-08-22 11:49:52 +02:00
Marc-André Bombeck 14638a6660 Bring the ECG strips back from a restore
The register said the originating device may still hold them. That holds
for about as long as the phone beside the watch does, and not at all once
a Withings connection is revoked: the signal id stops resolving with it.
So a self-hoster who exported and wiped had a file with no traces in it
and a restore that reported success.

Both ends live in src/lib/export/ecg-backup.ts, the arrangement the
reminders, visits and Coach sections already use.

Three things needed deciding.

The waveform follows the note contract: ciphertext verbatim in a
disaster-recovery payload, the micro-volt samples decrypted in a portable
one. There is no placeholder for a strip that will not decrypt the way
the Coach has one for a turn, because waveformEncrypted is a required
column. Such a recording is left out of a portable file with a warning on
the wide event, so the number of strips in the file is the number of
strips that can be shown.

measurementId is a REAL foreign key against the event row a strip was
filed with, unlike the Coach references next door. A value that will not
resolve does not dangle quietly here, it violates the constraint and
rolls the whole restore back over one cross-reference. A portable export
omits soft-deleted measurements, so that case is reachable rather than
theoretical. The reference is resolved against the measurements the
restore wrote, nulled when it cannot be, and reported as ecgReference.

The strips are wiped and rewritten by the section itself. The wipe at the
top of the restore never reached them: a recording hangs off the account,
not off a measurement, so deleting the measurements only nulled the
pointer and left the row behind.

The round trip asserts the row column by column rather than counting it.
A recording is three things at once and each is the whole value of the
row on its own: a strip with no rhythm verdict is a squiggle nobody has
read, a strip with no recordedAt belongs to no day, and a strip with no
samples is a claim that an ECG exists which nothing can draw.
2026-08-22 11:44:01 +02:00
Marc-André Bombeck a6c239d952 Merge pull request #820 from MBombeck/work/backup-awards
Carry the bests, the badges and the environment days through backup and restore
2026-08-22 11:37:24 +02:00
Marc-André Bombeck 775efad923 Merge pull request #821 from MBombeck/fix/proxy-relative-redirects
Stop redirecting to the address the process bound to
2026-08-22 11:14:31 +02:00
Marc-André Bombeck f95fb95295 Carry the bests, the badges and the environmental history through a restore
Four models leave the coverage-pending register with both ends and a
round-trip proof: PersonalRecord, UserAchievement, EnvironmentContext and
EnvironmentTravelLocation. Two new section modules hold reader and restore
beside each other, the arrangement the visits, vaccinations, reminders and
Coach sections already use.

The register understated two of them. The bests are "recomputable in
principle", which is true and does not help: nothing recomputes them, and a
recomputation over a restored history would find different rows, because
sample series and GPS routes never travel, a portable file omits deleted
readings, and a record set in a reading that has since been corrected cannot
be found twice. The badge's unlock date is worse. The evaluator prefers a
persisted date over a derived one, and several of the dates it can still
derive come from counters no backup carries, so a dropped row does not relock
the badge, it re-earns it today.

PersonalRecord.sourceMeasurementId is the reference that needed care, and it
is the dangerous kind. The schema declares no relation for it; migration 0054
created the column as a real foreign key against measurements. Writing it
blind is not a dangling pointer, it is a constraint violation that rolls the
whole restore back and hands the operator an empty account. Measured, with the
resolution removed: "Foreign key constraint violated on the constraint:
personal_records_source_measurement_id_fkey", HTTP 500, nothing restored. So
the restore runs after the measurements, resolves the pointer against the rows
it actually wrote, nulls what it cannot resolve and reports it under a new
personalRecordReference skip kind.

An unlocked badge names a definition in the code catalogue, which drifts
between the release that writes a file and the one that reads it. The id is
carried and written back verbatim rather than judged, the same answer the
vaccination restore gives an antigen slug it cannot resolve.

The readings and the location periods travel as a pair because carrying the
readings alone is worse than losing them. The environment resolver reads the
periods live, so with them gone the nightly seven-day lookback re-resolves
every trip day to the home location and upserts over the row: an account would
come back with a fortnight abroad and then have it quietly rewritten as a
fortnight at home, days after a restore that reported success. Day keys stay
strings end to end, and fetchedAt is restored verbatim so a two-year-old
provisional reading does not claim it was confirmed today.

The round trip seeds bests that share a metric type and an instant and differ
only in the sport slot, two badges earned years apart (one of them under an id
this build no longer defines), and a trip day beside a home day, then reads
each back column by column. Counting alone passes every one of the failures
worth fearing here: slots dropped so a 5 km best is presented as a 10 km best,
unlock dates stamped at restore time, a trip day re-attributed to the home
city, a location period whose bounds no longer cover the reading it explains.
Each of those was applied on purpose and each failed on its own assertion.

Two schema comments claimed no read path selects a column that this backup now
selects; both say what reads it instead of staying wrong.
2026-08-22 11:14:15 +02:00
Marc-André Bombeck 974a90f28f Merge pull request #819 from MBombeck/work/backup-docs
Carry the vault's filing and its staged facts through backup and restore
2026-08-22 10:58:28 +02:00
Marc-André Bombeck cc8c69aa07 Stop redirecting to the address the process bound to
Reported from the iOS side, iOS #96. `GET /api/auth/native/login` answers

    location: https://0.0.0.0:3000/auth/login?flow=native

behind a proxy that does not pass `Host` through. `NextResponse.redirect`
needs an absolute URL, the route built one with `new URL(path, req.url)`,
and `req.url` there is the address the Node process bound to.

That is the primary onboarding path. ASWebAuthenticationSession follows
the redirect, iOS refuses the restricted port, and the person lands on a
browser error page with no way forward. Distributed builds carry no
associated domains on purpose, so the browser handoff is also how
passkeys are meant to work; without it a new account is down to a
password and a confirmation code.

Two things hid it. Every error branch of that route builds the fixed
healthlog:// scheme with no host at all, so the route behaved correctly
on every failure and broke only when it was supposed to succeed. And its
own test built a request whose host matched, so the absolute URL it
produced looked right. The assertion there used toContain, which is
satisfied by the broken value just as happily as the correct one.

The same line was in six more places: the error redirects of the
Withings, WHOOP and Fitbit connect routes, which send a browser to
/settings/integrations. Behind the same proxy those land on the same
unreachable address, so all seven move to a relative Location.

A relative Location is valid per RFC 7231 and the client resolves it
against the address it actually called, which is the public one by
definition. The alternative is reading X-Forwarded-Host, and that would
put one more proxy setting between a self-hoster and a working sign-in.

Three checks, as the report asked for. The route test now drives a
request whose URL names the bind address, which is what a proxy hop
looks like from inside the handler. A structural test freezes the
pattern out of the four files and, separately, requires each of them to
still reach for the helper, because a file that simply deleted its
redirect would pass the first check and fail its users. The helper
refuses a protocol-relative value, which is a host in disguise.

Verified by breaking it: putting the old call back fails four checks,
the last of them reporting the reported value verbatim.

Refs iOS #96.
2026-08-22 10:55:40 +02:00
Marc-André Bombeck 352ff617da Stop the switched-payload spec failing on its own reload
The scoped-sharing spec routes `/api/auth/me`, and the account switch it
drives ends in a full reload. The reload cancels whatever call is in
flight, Playwright marks the route handled, and the handler's `fulfill`
then lands on it with "Route is already handled!". With
`failOnFlakyTests` on CI that turns the whole shard red over a teardown
race rather than over anything the test is checking.

Same guard the record-session-fence spec and this file's own
accessibility sibling already use. The `fetch` is guarded too, because a
request cancelled mid-flight rejects there rather than at the fulfill,
and the earlier of the two is the one that decides which error the run
reports.
2026-08-22 10:42:32 +02:00
Marc-André Bombeck d5dde3eb1c Carry the vault's filing and its staged facts through backup and restore
`DocumentConditionLink` and `ExtractedFact` were classified as backed up and
came back from no restore. The register said a restored vault is unsorted and
that the facts are re-derivable by re-running the extraction. The first is
right; the second understates it. What a re-run cannot produce is the REVIEW
DECISION on each fact, and every column holding one defaults to "nobody has
looked at this yet". `POST /api/documents/inbound/[id]/confirm` acts only on a
PENDING fact and commits it into the structured store, so a restore that let
those columns default would offer an already-committed reading for approval a
second time and write a second lab result behind it.

Both ends live in `src/lib/export/document-filing-backup.ts`, beside each other
like the Coach, reminder and vaccination sections. `status`, `needsReview`,
`confidence` and the commitment pair are carried and restored verbatim, and the
wire schema requires the first three rather than defaulting them.

Ordering: the section runs after the documents, the condition episodes, the lab
results and the medications. The first two are real foreign keys, unlike the
Coach's bare id columns, so an unresolvable value there does not cost one edge,
it aborts the transaction and the operator gets none of the account back. The
last two are what `committedRecordId` resolves against. The builder therefore
carries a filing or a fact only when both of its ends are carried, and the
restore still checks and drops what a hand-edited file leaves unresolvable.
`committedRecordId` is nulled together with its type, because a type with no id
claims a commitment the row cannot name.

The round trip seeds a second condition and files the page under it, so a
restore that kept the count and lost the pairing fails rather than handing back
a lab report filed under a head cold. A third case breaks both references in a
saved file to prove the drop path runs and still answers 200.

Three new skip catalogues arrive with it, and with them labels for the three
that had none: a dropped Coach attachment had been reaching the operator's
screen labelled "mood factor" since it was added. The label chain is exhaustive
now, so the next catalogue without one stops the build.
2026-08-22 10:23:58 +02:00
Marc-André Bombeck 4d2fc06fe7 Merge pull request #818 from MBombeck/work/backup-sensitive
Carry the screener history and the consent record, disaster recovery only
2026-08-22 10:16:48 +02:00
Marc-André Bombeck f4fe08c73e Carry the screener history and the consent record, disaster recovery only
Two models come off the coverage register together, and neither is an
ordering or an id-remap problem. Both hang off the account and nothing
else. What kept them off was a question the code never wrote down, so
this change writes it down.

The screeners hold completed WHO-5, PHQ and GAD administrations, and for
PHQ-9 the encrypted blob contains item 9, the question about thoughts of
being better off dead. The application already draws a line around that
blob: it keeps a coarse item9Flagged boolean so the history view can
re-surface crisis resources without decrypting anything. The intent here
was to follow that line and carry the administration while leaving the
answers encrypted. The schema settles it more firmly. responsesEncrypted
is Bytes and NOT NULL, so there is no half-row to write and the choice
is the whole thing or none of it. A plaintext export in a downloads
folder is the wrong home for that answer, so the row rides in a
disaster-recovery file only.

The consent receipts are not sensitive in that way. Their problem is
that a consent is given to an operator. A receipt restored onto a
different instance asserts an agreement that operator never obtained,
with a signature timestamp to make it look settled. A disaster-recovery
file goes back to the same instance, so it travels there and not in a
portable one.

In both cases the portable file SAYS so in its own manifest rather than
reporting an account that has neither. The manifest is merged rather
than added beside the records one, because two keys of the same name
would shadow each other depending on spread order.

item9Flagged is restored from the file rather than recomputed.
Recomputing would mean decrypting every administration during a restore,
which is the handling this data is kept away from, and the stored flag
is what the history view has been reading all along.

Verified by breaking it: dropping revokedAt on the way back fails the
round trip with a withdrawn consent coming back as an active one.
2026-08-22 09:48:10 +02:00
Marc-André Bombeck 79725a85e9 Merge pull request #817 from MBombeck/feat/backup-notification-prefs
Carry per-drug reminder phase timings, and stop claiming the notification preferences could travel
2026-08-22 09:34:59 +02:00
Marc-André Bombeck 16b10c7855 Carry per-drug reminder phase timings, and stop claiming the notification preferences could travel
Two entries sat side by side on the coverage register, described as "the
same shape of loss". They are not the same shape at all, and the
difference is worth writing down.

ReminderPhaseConfig hangs off a medication, one row per drug, nested
inside something that already travels. It needed nothing new and it
travels now. The round trip tunes all four thresholds away from their
defaults and puts one of them in PERCENT rather than MINUTES, because a
restore that quietly fell back to the schema defaults would hand back
four plausible numbers and change when the drug turns orange.

NotificationPreference cannot travel, and the register was wrong to
imply it was merely unbuilt. A preference addresses ONE notification
channel by a hard foreign key. The channel model is deliberately
excluded from every backup because it carries channel secrets, and the
restore deletes every channel it finds. A carried preference would point
at a row that cannot exist: the same constraint violation the custom
mood categories were causing, waiting for somebody to implement it in
good faith.

So it moves to the deliberate exclusions with a reason that names the
dependency instead of the symptom. Re-applying somebody's tuning to a
channel they add after a restore is a feature about channel types, not a
backup contract about rows, and it should be argued for on its own
terms rather than smuggled in as debt repayment.
2026-08-22 09:16:38 +02:00
Marc-André Bombeck e56b54cf24 Merge pull request #816 from MBombeck/feat/backup-mood-taxonomy
Restore an account that grouped its own mood factors
2026-08-22 09:16:34 +02:00
Marc-André Bombeck d596f8c66d Restore an account that grouped its own mood factors
An account that ever created its own mood category could not be restored
at all. Not partially, not with a gap: the restore violated
mood_tags_category_id_fkey and rolled the whole file back, so the
operator got a 500 naming a constraint and an empty account.

The coverage register described this as custom tags landing in a
grouping that no longer exists, which reads like a cosmetic loss.
Measured, it is the same shape the retired-catalogue-key work already
removed once: one row nobody thought about taking down everything else
with it.

MoodTag.categoryId is a real foreign key. Seeded categories belong to
the instance and are deliberately still not carried, but a category the
person made is theirs, cascades away with them, and has to travel. It
now does, and it is written before the tags that point at it.

The hidden set travels by key rather than id, because what people hide
is almost always a seeded tag whose id differs on every instance. A key
this instance no longer knows costs one hidden row and is reported: a
silent drop would un-hide a factor somebody had deliberately taken out
of their mood editor, and they would have no way to know why it came
back.

Found by experiment rather than by reading: seeding a user-owned
category into the round trip turned it red with the constraint name, and
the same test is green now.
2026-08-22 01:15:59 +02:00
Marc-André Bombeck 460ed37a2a Merge pull request #815 from MBombeck/feat/backup-medication-stock
Carry medication stock and its ledger through backup and restore
2026-08-22 01:15:55 +02:00
Marc-André Bombeck 86231ed23e Carry medication stock and its ledger through backup and restore
A restored account reported no supply at all. Every pack was gone, and
with it every low-stock reminder, on a feature that became first-class
when medication moved to one stock per drug.

The two travel together because the register itself paired them: without
the events the count "cannot be rebuilt even in principle", and without
the packs the events are a list of deltas against nothing.

The count comes back exactly as recorded, not recalculated from the
ledger. It is the value the server had resolved and the person was
shown, and every reminder already sent was computed from it. The fixture
makes the difference visible on purpose: thirty in, eight consumed, and
a remaining count of twenty-one, because somebody dropped one without
recording it. A restore that "corrected" that to twenty-two would
disagree with the account's own history and look like a bug fix while
doing it.

Both decimal columns cross the wire as strings. Half tablets are a real
prescription and a JSON number would round them.

The note follows the contract the side effects and dose changes beside
it already use, and the packs nest inside their drug, so a portable
restore minting fresh ids needs no remap.

Verified by breaking it: recomputing the remaining count from the ledger
fails the round trip with twenty-one against twenty-two.
2026-08-22 00:59:15 +02:00
Marc-André Bombeck f4e65c827a Merge pull request #814 from MBombeck/feat/backup-coach-memory
Carry the Coach's memory through backup and restore
2026-08-22 00:59:10 +02:00
Marc-André Bombeck 1fbd3b628b Carry the Coach's memory through backup and restore
The transcript came back in the previous change; what the Coach keeps
BETWEEN threads did not. A restored account had every word of every
conversation and a Coach that has to be told its own history again — the
register said as much for all three: "a restore makes the account
re-tell its history", "keeps the talk and loses the commitment", "a
restored account silently stops sending them".

Tombstones ride only in a disaster-recovery file. All three soft-delete,
and a deleted fact is hidden from injection while kept for audit — a
distinction only the owning instance can act on. A portable file
carrying them would hand a person rows their own app refuses to show
them, and a restore that resurrected one would put a fact back into the
Coach's mouth that the person had deliberately taken out of it.

Neither reference here is a foreign key. sourceConversationId, on all
three, and relatedPlanId on the reminder are bare id columns, so nothing
in the database refuses a value pointing at nothing. That makes them
more dangerous than a real key rather than less: a dangling reference
costs no error, it just quietly stops meaning anything while the row
goes on looking complete. The restore resolves both against what it
actually wrote, nulls what it cannot resolve, and reports the count.

Nulling rather than dropping is the point. A live reminder must not be
lost because the plan it mentions was tombstoned out of a portable file.
The reminder is still the person's and it still fires; what it loses is
a pointer that was already going nowhere.

Order follows from that: threads, then plans, then reminders. Running
the memory before the transcript would cut every fact loose from the
conversation it came out of and still report success.

Verified by breaking it: making the conversation lookup always return
null fails the round trip on the fact's own source field.
2026-08-22 00:41:26 +02:00
Marc-André Bombeck ad8325f18d Merge pull request #813 from MBombeck/feat/backup-coach-transcript
Carry the Coach transcript through backup and restore
2026-08-22 00:41:21 +02:00
Marc-André Bombeck bcb7716ffa Carry the Coach transcript through backup and restore
A restored account got a Coach that had never spoken to it. The
conversations, every turn in them, and the record of which vault
documents a thread was grounded in were all classified as backed up and
travelled with nothing. The register's own entry for the messages called
them the largest volume of free text an account owns after its
documents.

The three travel together because two of them mean nothing alone: a turn
without its thread has nowhere to hang, and an attachment names a
pairing rather than a thing.

documentScoped is the field that makes this more than lost history. It
is a permanent fence — set when a conversation is created through the
fenced endpoint or gets its first document, and lowered by no code path
anywhere, not by detaching every document and not by deleting one. A
restore that let it default to false would hand the tool loop back to
precisely the conversations the fence exists to keep away from it, and
nothing in the interface would look wrong afterwards. So it is carried
verbatim, restored verbatim, and asserted per thread rather than in
aggregate: a restore that wrote false everywhere would still return both
threads and every turn and satisfy every count.

Prose follows the contract the rest of the payload already uses. A
disaster-recovery file carries the stored ciphertext; a portable file
carries the text, because a portable export exists to be readable by the
person who owns it, exactly as it already decrypts medication notes,
mood notes and document summaries. A single row under a key the instance
no longer holds is named rather than thrown, so one unreadable turn
cannot cost someone the rest of the transcript.

Ids ride in both modes, as the reminders do, so an attachment resolves
and the facts, plans and reminders still owed have something real to
point at. The restore runs after the documents for the same reason, and
an attachment naming a document the file does not carry is dropped and
reported instead of failing the whole file over one link.

Verified by breaking it: forcing documentScoped to false on the way back
fails the round trip on that field by name.
2026-08-22 00:25:07 +02:00
Marc-André Bombeck b400e8bb4a Merge pull request #812 from MBombeck/test/portable-restore-refusal-ordering
Pin that a refused restore has not already wiped the account
2026-08-22 00:24:26 +02:00
Marc-André Bombeck a8898bbee7 Pin that a refused restore has not already wiped the account
The restore refuses a portable backup, because a portable export carries
document metadata without the stored bytes and `contentEncrypted` is NOT
NULL. That refusal is deliberate and documented at the guard.

What nothing pinned is the half that makes it survivable: the check runs
above the transaction that wipes the account. The guard reads like input
validation, and input validation drifts toward wherever the value is
first used. Move it below the wipe and the operator loses everything to
a file the server was always going to reject — and the non-null
assertions further down are safe only because it stands where it does.

The test drives a real portable payload through the real route and reads
rows, not return values: the refusal happens, the account still has
every row it had, the cache invalidation never fired, and the audit row
names the document. Asserting the status alone would stay green through
exactly the edit this is here to catch, so the surviving rows are
asserted separately rather than inferred from it.

Verified by breaking it: disabling the guard turns the 422 into a 500,
which is the raw TypeError from decoding bytes that are not there.
2026-08-22 00:01:52 +02:00
Marc-André Bombeck 3f570b6f53 Merge pull request #811 from MBombeck/feat/backup-medication-history
Carry medication dose changes through backup and restore
2026-08-21 23:39:46 +02:00
Marc-André Bombeck 5e0994aab9 Carry medication dose changes through backup and restore
The titration history was classified as backed up and travelled with
nothing. An account restored from a backup showed the current dose and
no record of how it got there: the ramp, the reductions, the note the
prescriber gave for each step. For a long-running drug that history is
often the more clinically interesting half.

Export writes the rows nested inside their drug, ordered by
effectiveFrom, so a portable restore that mints fresh ids needs no
remap. The note follows the contract the side effects already use: a
portable export decrypts it for a human reader, a disaster-recovery
export carries the ciphertext verbatim, and a restore never writes it
into the legacy plaintext column.

Order is the content here, not decoration. Two rows on the same drug in
the same unit, 5 mg then 10 mg, describe a ramp; the same two rows
returned in the other order describe a taper. Counting them back cannot
tell those apart, so the round-trip test asserts the sequence and the
values, not the count.

MedicationDoseChange moves from the coverage-pending register into the
two-ended list, which makes the round-trip registry incomplete until a
row is seeded and counted. That is a compile error, not a review note.
2026-08-21 23:23:23 +02:00
Marc-André Bombeck aca5b2d30b Merge pull request #810 from MBombeck/feat/backup-mental-health-consent
Carry medication pause eras through backup and restore
2026-08-21 22:19:29 +02:00
Marc-André Bombeck 48f4cba3aa Carry medication pause eras through backup and restore
`MedicationPauseEra` was classified as backed up and travelled nowhere. The
spans where a drug was deliberately paused are the difference between "stopped
taking it" and "was told to stop taking it", and nothing else in the payload can
reconstruct them: an era is a decision, not an observation, and no intake row
records its own absence.

Without them the compliance recomputation reads a deliberate pause as missed
doses, so a restored account looks non-adherent for a stretch during which it
did exactly what it was told.

Both ends land together. The eras ride nested inside their medication, like the
schedules and side effects beside them, so a portable file that mints fresh
medication ids needs no remap — Prisma binds each child to whatever id the
parent actually got.

## The open era is the point

`resumedAt` is nullable end to end and the writer always emits it. An open era
means the drug is paused right now, and readers run it to the present. The
restore passes the null through rather than closing it at restore time: a pause
that was still running when the backup was taken is still running afterwards,
and closing it would silently turn an ongoing decision into a historical one.

Counting alone cannot catch that — a restore that closed the era would still
hand back two rows. So the round-trip test seeds one closed era and one open
one and asserts both field by field.

## What is proven and what is not

Moving the model out of `COVERAGE_PENDING` and onto `TWO_ENDED_MODELS` makes
the round-trip test's registry incomplete, which is a compile error. Verified
by watching `tsc` fail with TS2741 before the count-back was written: the
coupling the plan's comment describes does hold.

The round-trip test itself needs Postgres via testcontainers and has not been
run here. Typecheck, lint, format and the 21458-test unit suite are green; the
integration proof comes from CI.
2026-08-21 22:01:51 +02:00
Marc-André Bombeck af386066e5 Merge pull request #809 from MBombeck/docs/idempotency-contract
Publish the idempotency contract the server has honoured all along
2026-08-21 18:51:04 +02:00
Marc-André Bombeck eddb67975d Publish the idempotency contract the server has honoured all along
`withIdempotency` has made writes safe to retry since v1.5.x. It was described
in route comments and in no schema, so an app generated against
`docs/api/openapi.yaml` could not learn that a retry was safe. The iOS side
asked for it; the mechanism does not change, only what it says about itself.

34 operations now declare `Idempotency-Key` and the `X-Idempotent-Replay`
header, plus the 409 that refuses a duplicate still in flight. The description
leads with the one silent failure in the mechanism: a key that misses
`^[A-Za-z0-9_\-:.]{8,128}$` is IGNORED rather than refused, so the write
proceeds unprotected and looks exactly like a request that carried no key.

## What the work turned up

Three things the contract had wrong or missing, none of them the thing being
built:

- `/api/insights/chat` describes `withIdempotency()` in its header comment and
  applies it nowhere. The Coach chat is not retry-safe. Its prose says it is.
- `/api/measurements` exports GET, POST, PUT and DELETE and wraps only POST.
  Publishing the header per PATH would have promised a safe retry on two
  methods that do not honour one — the dangerous direction, so the guard works
  per OPERATION.
- `/api/insights/feedback` and `/api/admin/backups/{id}/restore` are not in the
  document at all. Both are named in the guard's exemption list with a reason,
  not filtered out silently.

## The guard

`idempotency-contract-publication.test.ts` reads the expected set out of the
route tree on every run — nothing is hand-listed, so it cannot fall behind the
code. It fails in both directions: a new wrapped route that forgets to publish,
and a published claim no handler honours.

A fourth assertion checks the exemption list itself is still true. It earned
its place immediately: the first draft exempted the whole `/api/medications`
family on the strength of a grep for path literals that came back empty. The
paths are not written as literals there; the emitted document carries 19 of
them. The test went red, the claim was wrong, the list is two entries now.
Measure the artefact, not the source that builds it.
2026-08-21 18:32:29 +02:00
Marc-André Bombeck b8a0aead7f Merge pull request #808 from MBombeck/fix/prisma-cli-deepmerge-override
Pin deepmerge-ts in the npm install the workspace override cannot reach
2026-08-21 14:08:37 +02:00
Marc-André Bombeck 2e5ec7f49f Pin deepmerge-ts in the npm install the workspace override cannot reach
The image builds two dependency trees. `pnpm install` builds the app tree and
honours `pnpm-workspace.yaml`. A second, npm-owned install builds
`/opt/prisma-cli` for the migration CLI, and it reads none of that file.

Only the first was pinned. `prisma@7.8.0` resolves `@prisma/config@7.8.0`,
which resolves `deepmerge-ts@7.1.5`, so the Trivy image scan reported
CVE-2026-40345 (HIGH, stack exhaustion on recursive merges) against
`/opt/prisma-cli` on a commit whose dependency audit over the app tree was
green. The pin read as complete because the check that could see the gap runs
against the artefact, and the one that ran against the lockfile could not.

`overrides` is npm's own mechanism, so `npm pkg set` writes it into the
package.json `npm init -y` just created, before anything resolves. Rebuilding
this exact install both ways: without the field `deepmerge-ts@7.1.5` lands,
with it `8.0.1` lands and `prisma --version` still reports 7.8.0.

The guard beside it fails when the two files name one package at two ranges,
and asserts a non-zero match count first, so a matcher that stops matching
fails loudly instead of passing vacuously. It compares declared ranges only —
a new vulnerable transitive that neither file mentions remains something only
the image scan can see, and that job runs on main-push, not on pull requests.
2026-08-21 13:31:49 +02:00
Marc-André Bombeck 5d3d512e82 Merge pull request #806 from MBombeck/fix/demo-published-credentials
Write the published demo password on every migration
2026-08-21 13:28:34 +02:00
Marc-André Bombeck 92af3c213c Merge branch 'main' into fix/demo-published-credentials 2026-08-21 13:10:00 +02:00
Marc-André Bombeck dc24e2250b Merge pull request #807 from MBombeck/fix/deepmerge-ts-advisory
Force the patched deepmerge-ts through Prisma's config loader
2026-08-21 13:09:33 +02:00
Marc-André Bombeck b8859ae424 Force the patched deepmerge-ts through Prisma's config loader
A new advisory turned the dependency audit red on the trunk without a line of
our code changing: DeepmergeTS recurses without bound on deeply nested input
until the stack gives out (GHSA-ggr8-5vv4-36mx, fixed in 8.0.0). Re-running the
same job against the same main commit that passed on 16 August confirms it is
the advisory database that moved, not us.

Waiting for Prisma does not help. `@prisma/config` still asks for 7.1.5 on the
current 7.9.1, so the copy never updates on its own, and an override is the only
route to the patched version. The workflow reserves `auditConfig.ignoreCves` for
advisories with no upstream fix, which is not this one.

The reach is the config-loading and CLI path rather than anything under a
request, so the practical exposure was small. The blocked release train was not.

Verified rather than assumed: `pnpm audit --prod --audit-level=high`, the exact
command CI runs, drops from twelve findings with one high to eleven with none
and exits clean. Because this is a major bump under Prisma's own config loader,
`prisma generate` and `prisma validate` were run explicitly alongside typecheck,
lint, format, 21446 unit tests and the production build. All pass.
2026-08-20 08:58:16 +02:00
Marc-André Bombeck 350294670d Write the published demo password on every migration instead of carrying one
The edge01 demo refresh copied `password_hash` straight from the source
account, and the README beside it asserted "demo login works". That only held
while the source account happened to use the password the project publishes.
The source is the operator's own instance, so the moment that password was
rotated the demo started rejecting the credentials the README hands to every
visitor, and nothing anywhere noticed. Someone eventually filed it as a bug
(#805) after being locked out of the shop window.

The load now hands the row an explicit password: the same Argon2id literal the
seed script writes, applied right after the copy, then read back and compared
byte for byte. A mismatch aborts the run rather than waiting for a stranger to
discover it at a login screen.

The statement goes in on psql's stdin. Interpolating it into the ssh command
string would let the remote shell expand the hash's `$argon2id`, `$v`, `$m`,
`$t` and `$p` segments to empty strings and store something no password can
ever match, which is the same outage wearing a different hat. A guard test
pins that too, alongside pinning the literal to the seed script's copy so the
two cannot drift apart again.
2026-08-20 08:20:16 +02:00
Marc-André Bombeck 0a20925d35 Merge pull request #763 from MBombeck/dependabot/github_actions/pnpm/action-setup-6.0.10
Bump pnpm/action-setup from 6.0.9 to 6.0.10
2026-08-16 20:11:20 +02:00
Marc-André Bombeck 08fd7c208f Merge pull request #762 from MBombeck/dependabot/npm_and_yarn/playwright/test-1.62.1
Bump @playwright/test from 1.60.0 to 1.62.1
2026-08-16 20:11:17 +02:00
Marc-André Bombeck 2435c9cefe Merge pull request #760 from MBombeck/dependabot/npm_and_yarn/pg-boss-12.27.0
Bump pg-boss from 12.26.0 to 12.27.0
2026-08-16 20:10:37 +02:00
Marc-André Bombeck e6c2aa86b1 Merge pull request #764 from MBombeck/dependabot/npm_and_yarn/testcontainers-12.1.0
Bump testcontainers from 12.0.3 to 12.1.0
2026-08-16 19:54:07 +02:00
Marc-André Bombeck c486096845 Re-verify the failed-row retention assumptions against pg-boss 12.27.0
The guard pins the installed version alongside the three source facts the
72-hour reader depends on, so a dependency bump has to stop and be looked at
rather than sliding past. It did its job here: 12.27.0 tripped the version
line.

Checked the release against 12.26.0. The retention plan is untouched, all
three assertions still match the shipped dist/plans.js verbatim. What moved
sits in the fetch path (group concurrency reworked to a keyed JSONB lookup,
schema names now routed through normalizeSchemaName / resolveSchemaName) and
in start_after, which becomes inclusive so a job written with the default
start time is fetchable on the next statement. None of that touches the
failed-row ledger.

So the assumption holds and the pin moves with it.
2026-08-16 19:28:11 +02:00
dependabot[bot] 552f11c21f Bump @playwright/test from 1.60.0 to 1.62.1
Bumps [@playwright/test](https://github.com/microsoft/playwright) from 1.60.0 to 1.62.1.
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.60.0...v1.62.1)

---
updated-dependencies:
- dependency-name: "@playwright/test"
  dependency-version: 1.62.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-16 17:27:52 +00:00
dependabot[bot] c9a3132893 Bump testcontainers from 12.0.3 to 12.1.0
Bumps [testcontainers](https://github.com/testcontainers/testcontainers-node) from 12.0.3 to 12.1.0.
- [Release notes](https://github.com/testcontainers/testcontainers-node/releases)
- [Commits](https://github.com/testcontainers/testcontainers-node/compare/v12.0.3...v12.1.0)

---
updated-dependencies:
- dependency-name: testcontainers
  dependency-version: 12.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-16 17:27:38 +00:00
Marc-André Bombeck 50e4138ed5 Merge pull request #761 from MBombeck/dependabot/npm_and_yarn/testcontainers/postgresql-12.1.0
Bump @testcontainers/postgresql from 12.0.3 to 12.1.0
2026-08-16 19:25:17 +02:00
Marc-André Bombeck 2e119f19c4 Merge pull request #759 from MBombeck/dependabot/npm_and_yarn/prettier-3.9.6
Bump prettier from 3.9.1 to 3.9.6
2026-08-16 19:24:39 +02:00
dependabot[bot] 73c3eff294 Bump @testcontainers/postgresql from 12.0.3 to 12.1.0
Bumps [@testcontainers/postgresql](https://github.com/testcontainers/testcontainers-node) from 12.0.3 to 12.1.0.
- [Release notes](https://github.com/testcontainers/testcontainers-node/releases)
- [Commits](https://github.com/testcontainers/testcontainers-node/compare/v12.0.3...v12.1.0)

---
updated-dependencies:
- dependency-name: "@testcontainers/postgresql"
  dependency-version: 12.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-16 16:41:09 +00:00
dependabot[bot] 238d63f3b9 Bump pg-boss from 12.26.0 to 12.27.0
Bumps [pg-boss](https://github.com/timgit/pg-boss) from 12.26.0 to 12.27.0.
- [Release notes](https://github.com/timgit/pg-boss/releases)
- [Commits](https://github.com/timgit/pg-boss/compare/12.26.0...12.27.0)

---
updated-dependencies:
- dependency-name: pg-boss
  dependency-version: 12.27.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-16 16:41:07 +00:00
dependabot[bot] cc670633ff Bump prettier from 3.9.1 to 3.9.6
Bumps [prettier](https://github.com/prettier/prettier) from 3.9.1 to 3.9.6.
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.9.1...3.9.6)

---
updated-dependencies:
- dependency-name: prettier
  dependency-version: 3.9.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-16 16:41:05 +00:00
dependabot[bot] 68448b2c5f Bump pnpm/action-setup from 6.0.9 to 6.0.10
Bumps [pnpm/action-setup](https://github.com/pnpm/action-setup) from 6.0.9 to 6.0.10.
- [Release notes](https://github.com/pnpm/action-setup/releases)
- [Commits](https://github.com/pnpm/action-setup/compare/0ebf47130e4866e96fce0953f49152a61190b271...0977fd99725f1db4007ccb2928dbb4e90d06cc86)

---
updated-dependencies:
- dependency-name: pnpm/action-setup
  dependency-version: 6.0.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-16 16:40:16 +00:00
Marc-André Bombeck c93a947408 Merge pull request #804 from MBombeck/fix/codeql-action-4-37-7
Bump every codeql-action reference together
2026-08-16 18:19:34 +02:00
Marc-André Bombeck 290ce3441a Bump every codeql-action reference together
Dependabot treats `init`, `analyze` and `upload-sarif` as separate
dependencies, so it raised `init` to 4.37.7 in one PR and left `analyze` on
4.37.6 in the same workflow. The action refuses that pairing outright:
"Loaded a configuration file for version '4.37.7', but running version
'4.37.6'", and the CodeQL job failed on the very PR doing the bump.

All five pinned references move together here: init and analyze in
codeql.yml, and the three upload-sarif steps in scorecard.yml and trivy.yml.
The commit SHA is the one the v4.37.7 tag dereferences to, which is also the
SHA both Dependabot PRs pin.
2026-08-16 17:58:49 +02:00
Marc-André Bombeck e00d013459 Merge pull request #801 from MBombeck/release/v1.37.24
v1.37.24 — stop waiting for sleep that never comes
2026-08-16 10:12:30 +02:00
Marc-André Bombeck d252940381 Give the just-in spec a record that expects sleep
The scenario purges every sleep row so last night can be the arrival that
flips the day. That left an account with no sleep source at all, which now
reads `final` on purpose, so the provisional assertion could not be reached.

Seeding a night from three days ago restores what the scenario means: a
record that does track sleep, waiting for last night's. Written through the
same ingest route as the fresh night and swept by the same purge.
2026-08-16 09:56:12 +02:00
Marc-André Bombeck 23278318ef chore(release): v1.37.24 — the card stops waiting for sleep that never comes 2026-08-16 09:33:42 +02:00
Marc-André Bombeck 6c4f27794b Stop waiting for sleep that is never coming
The hero card on the start page told anyone without a sleep source, every
morning, that last night's sleep was not in yet. The freshness rule only
asked whether last night's sleep had landed, so a record that has never had
a night in it, or whose owner has stopped wearing the tracker, read as
permanently waiting. Not everyone owns one, and people put them away.

Waiting now requires that sleep is actually reaching the record: a night
within the last seven days. A flat battery or a few nights without the
tracker keeps the note, since tonight's sleep really is still expected. A
week of silence retires it.

The same rule settles the day itself. It used to park on `provisional`
forever for those records, which the daily push line reads too, so the
notification carried the same untrue "last night's sleep is still missing"
aside.

Two existing tests pinned the old behaviour by name ("is provisional when
sleep has never been recorded", "stays provisional when sleep never
arrives"). They described the defect rather than a contract worth keeping,
so they now assert the opposite, and a third covers the boundary between an
ordinary gap and a source that has gone quiet.
2026-08-16 09:32:01 +02:00
Marc-André Bombeck b7fdfc3a2e Merge pull request #800 from MBombeck/release/v1.37.23
v1.37.23 — postpone reads as an action, not a menu row
2026-08-15 19:47:21 +02:00
Marc-André Bombeck 370a7b3df8 chore(release): v1.37.23 — postpone reads as an action, not a menu row 2026-08-15 19:29:40 +02:00
Marc-André Bombeck 12f7441f82 Put postpone beside the checkup's primary action
The preventive-care card kept postponing in the overflow kebab, three taps
from the thing a person actually wants when a due date does not fit: open
the menu, find the row, open the sheet. The medication card has never done
that — taken and skipped sit side by side on the card, one tap each — and
the checkup card should read the same way.

Postpone is a second button in the action row now, outline against the
filled primary, at its natural width beside it. The dense list branch gets
the same action as an icon button, so neither view offers what the other
withholds. The kebab keeps edit, measurements and delete.

The sheet behind the button is unchanged in what it offers (quick offsets,
a free date, the honest-skip zone), but the offsets are computed on the
calendar now rather than by adding 86 400 000 ms per day. Across a DST
shift the old arithmetic moved the wall clock over midnight and wrote the
neighbouring date, so a chip labelled "+7 days" could fill in the sixth or
the eighth.
2026-08-15 19:26:23 +02:00
Marc-André Bombeck 9a3c1d181c Merge pull request #799 from MBombeck/fix/dead-code-sweep
Remove the unreachable insights cluster and the retired comparison toggle
2026-08-15 03:53:45 +02:00
Marc-André Bombeck eb087f9fc2 Drop the two recommendation type aliases the deleted card exported for
The schemas stay: the insight result still parses recommendations
through them. Only the exported aliases went unused once the card that
consumed them was removed, and the dead-code gate says so.
2026-08-15 03:35:41 +02:00
Marc-André Bombeck 52f8c5a57a Remove six insights surfaces and a toggle nobody mounts
The production dead-code check has been documented rather than enforced
since PR #691, because its list mixed real debt with false positives.
Triaged against the shipped tree, six of them are genuinely unreachable
and go now.

Five died when their host was retired and the leaves were left behind:
the recommendation card with its confidence meter and feedback control,
the grid that mounted them, and the suggested-prompts chip strip that
left the hero band in v1.18.7. The sixth, the comparison toggle, has had
two regression tests pinning its absence since v1.4.22, because the
preference it once set is a Settings concern now.

Deleting them freed sixteen translation keys in every locale, a pinned
entry in the success-affordance register, and two entries in the Coach
gate fixtures. Each of those was found by a guard rather than by
reading, which is the point of having them.

The adapter under signals/adapters stays: knip reports it as unreachable
because only a test imports it, but that test is the registry invariant
it exists to prove, and deleting it would remove a check rather than
dead weight.
2026-08-15 03:15:48 +02:00
Marc-André Bombeck 8ec682f007 Merge pull request #798 from MBombeck/release/v1.37.22
release/v1.37.22
2026-08-15 00:55:24 +02:00
Marc-André Bombeck 1a4cff11d2 chore(release): v1.37.22 — two deferred audit findings, closed 2026-08-15 00:36:30 +02:00
Marc-André Bombeck 09446846b1 Refuse an export nobody scoped, and stop naming UCUM without a code
Two findings from the deferred-audit list, both live since July.

A FHIR lab quantity stamped the UCUM system unconditionally while the
code was only added when the analyte map resolved a symbol for exactly
that unit. A receiver was told the unit came from UCUM and then handed
no UCUM code, which is a coding claim the bundle cannot back. System
and code now travel together, on the value and on both reference-range
bounds.

The doctor-report export accepted a selection that admits nothing. The
panel disables its own submit in that state, so only a hand-built
request reached it, and it rendered an empty artefact while spending a
rate-limit slot. This route has no documents-only mode that would make
an empty leaf list a legitimate scope, so it refuses with 422. The
share-link route, which does have that mode, is untouched.
2026-08-15 00:23:44 +02:00
Marc-André Bombeck d2491d5589 Merge pull request #797 from MBombeck/release/v1.37.21
release/v1.37.21
2026-08-14 19:17:28 +02:00
Marc-André Bombeck 5ddf00420e Carry the version bump into the API description 2026-08-14 19:00:24 +02:00
Marc-André Bombeck 548e94cc75 chore(release): v1.37.21 — every intake path resolves a dose the same way 2026-08-14 18:42:50 +02:00
Marc-André Bombeck aafc1a3c1a Quiet the snooze and clear the web reminder on every intake path
The two halves of a resolved dose were split across routes: the single
intake route reset the medication's snooze but never closed the pending
dose-due Web Push reminder, while the bulk route closed the reminder but
left the snooze standing. Each path was missing exactly what the other
had. A dose drained from a device's offline queue lands on these routes,
so a synced take could keep ringing as snoozed or leave a stale web
badge behind.

The bulk route now nulls snoozedUntil once per affected medication when
a non-skipped entry actually lands, and the by-id route dispatches the
same fire-and-forget web clear the other intake paths have carried since
v1.18.4.
2026-08-14 18:34:11 +02:00
Marc-André Bombeck 3a2c0e757e Merge pull request #796 from MBombeck/release/v1.37.20
release/v1.37.20
2026-08-14 14:49:54 +02:00
Marc-André Bombeck 54afd3e42c chore(release): v1.37.20 — checkups you can postpone, skip, and look back on 2026-08-14 14:28:41 +02:00
Marc-André Bombeck a104963daf Register the skip and snooze admissions in the MANAGE handler matrix
The two new measurement-reminder routes were admitted in the frozen
fixture but never got their integration drivers, so the matrix count
stayed at 75 and the executable proof was missing. Both routes now
carry a full manageContract driver: the skip driver asserts the stamped
column, exactly one SKIPPED ledger row, and that lastSatisfiedAt stays
untouched; the snooze driver asserts the snoozed-until write under the
same invariant. All three inventory pins move to 77.
2026-08-14 14:27:58 +02:00
Marc-André Bombeck a5016c6eed Accept Apple's single-column ECG waveform layout
Apple Health exports write ECG CSVs in two shapes. The importer only
understood the paired Lead,Voltage form; the single-column form (Lead
and Unit as metadata rows, a blank separator, then one bare reading per
line) failed every row as malformed and the whole recording was skipped.

The parser now treats a blank line after Lead and Unit metadata as the
start of the waveform, reads one bounded numeric sample per row, and
converts the declared unit to integer microvolts before the existing
amplitude and safe-integer bounds. The paired layout parses exactly as
before, and an unknown unit fails with a fixed message.

Refs #794
2026-08-14 12:49:15 +02:00
Marc-André Bombeck a48efb6976 Keep the status description one sentence and admit the retokenise fact
The rewritten notification-status description ran to two sentences and
130 characters — the card-description guard is right, the slot holds one
meta sentence. Folded to one em-dash sentence in every locale. The new
documents_retokenised job fact joins the outcome allowlist with its
reason.
2026-08-14 10:14:21 +02:00
Marc-André Bombeck d33be187e6 Copy polish: one pause dash, du-imperative errors, bare-question confirms, tokened micro-text
The German bundle's 109 spaced en-dash pauses join the em-dash norm (the
two date-range placeholders stay ranges); the three straight-quote
stragglers and three mixed-quote strings take German quotes; the eleven
Bitte-Infinitiv validation errors speak du-imperative like the rest of
the app; the two wirklich confirms become bare questions; the
notification-status description trades its semicolon telegram style for
two sentences in every locale; the Withings setup action shortens to the
sibling single word. Twelve arbitrary text-[10px]/[11px] sites move onto
the text-2xs/text-xs tokens; chart tooltips and the vendor calendar stay
as they are.
2026-08-14 10:08:49 +02:00
Marc-André Bombeck 09fbac3a33 Hygiene: drop dead export modifiers, delete the dead series module, wire the tokenizer version
The knip blind spot (ignoreExportsUsedInFile) left eight symbols carrying
an export nothing outside their file consumes — the modifier goes, the
symbols stay. The score series module goes whole: its only importer was
its own guard test, whose composite- and config-guarding suites survive
in place.

DocumentContentIndex.tokenizerVersion gains the consumer that was the
point of storing it: the content-index job now re-tokenises rows whose
version trails CONTENT_TOKENIZER_VERSION, from the decrypted index text
along the same path the rotation script uses, keyset-paginated and
fault-isolated per row — a future tokenizer bump migrates the index
instead of silently splitting it. ImportJob.uploadSha256 turned out to
already have its dedupe consumer (both kick-off routes short-circuit on
same-bytes non-failed jobs); its comment now names that instead of
pretending to be write-only. The remaining write-only columns carry
their honest annotations in the shape the audit sweep parses.
2026-08-14 10:08:43 +02:00
Marc-André Bombeck 4941cd075b Carry the custom-metric entry tombstone through backup and restore
The entries gained a soft-delete this release; both backup ends follow in
the same one. A portable export omits tombstoned readings so a restore
cannot resurrect them; a disaster-recovery payload carries the tombstone
and the restore writes it back, so the account returns exactly as it
stood — undo affordance included.
2026-08-14 09:58:11 +02:00
Marc-André Bombeck bcabd43ca7 Hygiene: name the FHIR immunization gap, cache the digest offline, freeze the no-FK pair, document the pin bump
Four small debts from the audit tail. The FHIR bundle's missing
Immunization resource gets the same written-decision paragraph the visits
exclusion carries — deliberate follow-up, not oversight. The service
worker's offline allowlist gains /api/daily/digest (both copies, policy
module and sw.js, plus the test) so the Today rail renders on an offline
reopen. The two Telegram plumbing tables that link to an account by a
bare userId string are frozen as a closed NO_FK_BY_DESIGN set in the wipe
guard — a third such table now fails the test instead of passing rule 1
silently. And deploy.md documents the manual digest-pin bump end to end:
imagetools inspect, the env update, and the three-probe /api/version
verification with the too-fast-deploy warning.
2026-08-14 09:56:45 +02:00
Marc-André Bombeck 9d64eb6aa2 Show what a backup contains before the operator types RESTORE
The restore dialog asked for its typed confirmation on nothing but a
filename and a date; the counts only surfaced in the audit row after the
rows were already replaced. A read-only summary endpoint now decrypts and
schema-validates the stored file through the same helpers the restore
itself runs and answers the summarizeBackup counts, and the dialog shows
them — per section, with an other-records line so a future summary key
can never silently vanish from the preview. A failed preview states its
own absence and never blocks the restore.
2026-08-14 09:51:40 +02:00
Marc-André Bombeck 90bad17cc8 Show the answers behind a screening score
Refs A3-8. The per-item PHQ-9 / GAD-7 / WHO-5 / SCI answers have been
stored encrypted since the assessments shipped, and nothing ever read
them back — the clinical detail (item 9 included) was invisible. A new
by-id read decrypts them for whoever holds the mind read grant (the same
grant that already serves the mood diary's prose and the item-9 flag),
degrades to an honest items-unavailable state on any decrypt or shape
problem, and the history rows gain an expandable breakdown rendering the
official instrument texts the check-in flow already carries — nothing
retranslated, no alarm styling on item 9 beyond what the house already
does.

Rides along: the guard inventories learn the branch's new routes (frozen
counts moved with reasons), the reminder-engine test harnesses carry the
ledger delegate, and the custom-metric restore toast keys sit in their
right namespace in all six locales.
2026-08-14 09:46:48 +02:00
Marc-André Bombeck 651d37b494 Let the dashboard hero show what matters most to its owner
The hero card composition was fixed: score panel first, the worth-a-look
rail beneath. A reminder-driven person asked for the reverse. The stored
dashboard layout gains an optional hero field ('score' default,
'reminders' promotes the rail into the hero slot), validated as a closed
enum, preserve-when-absent on write, omitted from the blob at the default
so untouched accounts serialize byte-identically. The choice sits in
Settings beside the other hero controls; the promoted rail degrades to
the calm all-clear line when nothing is due.
2026-08-14 09:46:35 +02:00
Marc-André Bombeck a3561b4600 Tell a first-run what Apple Health is actually doing
Refs #778. Two honesty gaps from the first-run report: the web onboarding
presented Apple Health like a web connector although the connection only
completes in the iPhone app, and the initial backfill gave no sign of
progress, so a working first sync looked broken.

The onboarding source step now says plainly that Apple Health is set up in
the iPhone app after onboarding, without dead-ending the flow. The
integration card gains a server-authoritative progress summary — rows
accepted, oldest reading reached, and an honest flowing/waiting line
derived from the last accepted batch. Nothing the server does not know is
shown: no percentage, no ETA, no invented throttle state; a quiet stretch
reads as waiting for the phone, not as an error.
2026-08-14 09:46:24 +02:00
Marc-André Bombeck b1be67bfa7 Carry the reminder schedule and its ledger through backup and restore
The reminder cadences were the oldest entry on the coverage-pending
register: carried in name, restored never — an account came back silent
until every reminder was rebuilt by hand. Both models are two-ended now,
in the house shape (both ends in one file, reminders-backup.ts): every
column travels, nextDueAt verbatim rather than recomputed, the completion
ledger beside it, tombstones in disaster recovery only, and a portable
export omits a tombstoned reminder together with its ledger rows.

Encounter.reminderId and VaccinationRecord.reminderId stop being dropped
on restore: both remap against the restored reminders and fall to NULL
with a skip report only when the file genuinely lacks the row. The wipe
plan names the ledger child-before-parent; the classification guard,
completeness guards and the integration round trip all demand the new
coverage (proven failing with the section removed).

Refs #223
2026-08-14 09:36:03 +02:00
Marc-André Bombeck a1ca0dc911 Let a German search find an English letter, and the other way round
Document search does whole-token equality over a blind index, so
'Blutdruck' never found the discharge letter that says 'blood pressure'
and 'hypertension' missed every German Arztbrief. A curated German/English
medical synonym list (vitals, common labs, imaging, specialties, document
words — static, no vendor names) now expands the QUERY tokens before they
are hashed: the stored index, its tokenizer version and the schema are
untouched, the expansion happens ahead of the one-way hash, and recall
simply widens. Typed tokens always survive the expansion cap.
2026-08-14 09:34:54 +02:00
Marc-André Bombeck 7bf8dbd8af Give custom-metric values the same second chance as every other entry
Refs A3-11. Deleting a logged custom-metric value was the one hard delete
left on an entry surface — everywhere else a deletion tombstones and the
toast offers Undo. The DELETE verb now stamps deletedAt, every read
(list, latest-value, counts, revive check) filters the tombstone, and the
new entries/restore endpoint clears it scoped to owner and parent metric —
a foreign, live or mismatched id is a silent no-op, never an existence
leak. The history table's delete toast carries the Undo action.
2026-08-14 09:34:43 +02:00
Marc-André Bombeck 689cacc039 Keep the measurements and mood filters in the URL
The documents view already round-trips its filters through the query
string; the measurements and mood lists kept theirs in memory, so any
navigation dropped them. The documents pattern is extracted into a shared
hook (use-url-filter-sync) and both lists adopt it: type/source/day-bounds
and the measurement value range survive reload, back and sharing, defaults
stay out of the URL, invalid facets drop leniently. The insights readings
subpage keeps its locked type in memory — that URL belongs to the insights
route. /measurements no longer strips ?type=, so the deep links the
Vorsorge cards mint now persist as filter state.
2026-08-14 09:24:08 +02:00
Marc-André Bombeck 5619783648 Let a checkup be skipped or pushed back, and remember every outcome
Refs #223. A due Vorsorge item could only be done, deleted or ignored;
Telegram's postpone moved the date with no trace. Both decisions are
first-class now, and both are honest:

- POST /{id}/skip (no body): the interval restarts from the skip instant
  through the recurrence engine, lastSkippedAt is stamped, skipCount
  increments, any snooze clears. lastSatisfiedAt is NEVER touched — done
  and skipped stay distinguishable forever, enforced in the primitive and
  pinned by tests.
- POST /{id}/snooze ({until: YYYY-MM-DD}): the server resolves the day to
  the notifyHour in the profile timezone and moves snoozedUntil and
  nextDueAt to the same instant, so every due-state consumer follows
  without knowing snooze exists. At least tomorrow, at most five years.
- GET /{id}/history: the new append-only completion ledger
  (MeasurementReminderEvent), one row per satisfy from every engine path
  and per skip, onTime derived at write time against the due instant that
  was current when the event landed.

Two anchor fixes close the backdated-event gaps: the auto-resolve floor is
now the later of last satisfy and last skip (an old reading synced late no
longer resolves the cycle the user just skipped), and a backdated real
result re-anchors the next due at the later of its own instant and the
skip decision.

Screenings stay skippable and snoozable — the satisfy-side 409 guards
claimed fulfilment; a skip claims the opposite. Appointment reminders 404
on all three routes, in the lookup, like every by-id sibling. /checkups
gains the postpone sheet (quick chips, date field, the skip zone with its
own confirm) in both view branches, with muted meta lines and no card
colour change. The MCP preventive-care tool carries the resolved fields;
the OpenAPI contract publishes all three paths and the widened DTO.
2026-08-14 09:23:58 +02:00
Marc-André Bombeck cd12b3886e Say what the stage tooltip's total actually is
Refs #611. The nap separation itself shipped in v1.34.4; what remained of
the report was the tooltip footer labelling a single night's total with the
orphaned 'Average per night' key (the headline card that owned it was
dropped in v1.22.0, so hovering one column claimed an average that was that
night's sum). The footer now names the main session's sleep, and on a day
with an inferred nap adds the whole-day total beside it — the Main sleep /
Naps / Total triple the report asked for. Percentages keep dividing by the
night alone.
2026-08-14 09:23:39 +02:00
Marc-André Bombeck 57ec22073c Publish the mood-entries family, the linked-context read and the import endpoint
Ten operations the spec owed: the seven mood-entries routes (list, create,
read, edit, delete, restore, bulk-delete) whose /bulk twin was already
published, GET /api/mood/linked-context (a cross-section read through the
mood URL that grant-scope reviewers need visible), and POST /api/import
(the spec documented polling an import job with no way to create one).
Every schema mirrors the handler's own Zod source; the envelope, refusal
and error semantics are read off the routes, not invented. Request-body
ids are bound instances now — a bare .meta() call clones in Zod 4 and
never reaches components.schemas.
2026-08-14 09:23:34 +02:00
Marc-André Bombeck 832aad9dd8 Add the Vorsorge skip/snooze columns, the completion ledger and the custom-metric tombstone
Migration 0334, all additive. MeasurementReminder gains snoozedUntil,
lastSkippedAt and skipCount; the new MeasurementReminderEvent table is the
append-only completion ledger (kind SATISFIED|SKIPPED, occurredAt, write-time
onTime, source). CustomMetricEntry gains the deletedAt tombstone for undo
parity with every other entry surface. Consumers land in the sibling commits
of this branch.

Refs #223
2026-08-14 08:54:43 +02:00
Marc-André Bombeck d8cbe2596f Merge pull request #793 from MBombeck/release/v1.37.19
Release v1.37.19
2026-08-14 08:01:42 +02:00
Marc-André Bombeck 1b183f64fe Wrap the widened assertion the way prettier wants it 2026-08-14 07:44:08 +02:00
Marc-André Bombeck 7cfe13db8c Follow the toast copy into the vault delete assertion 2026-08-14 07:43:31 +02:00
Marc-André Bombeck 83fa7856c8 chore(release): v1.37.19 — the supply math agrees with itself 2026-08-14 07:19:43 +02:00
Marc-André Bombeck d2ff7cb769 Settle the suite-wide fallout of the wave
- The record-settings contract, slug-list, and section-frame tests
  follow the slugs that left the registry (layout children resolve
  their headings from the layout namespace, like production).
- The orphaned settings.sections.<module>.title/description keys leave
  all six locales; the reverse-coverage guard flagged them the moment
  their nav entries stopped existing.
- The operator-cap ledger read fails open on a read error — the
  reservation layer still meters against the same ledger, and a
  transient blip must not take the fallback chain down.
- The reaper queue joins the subsystem surface; its healed count and
  the sweep's nag_dismissed join the job-fact vocabulary.
- The intake-event contract fixture carries the full row the resource
  now declares; the workouts empty-state test asserts the
  source-neutral cue; the persister poll gates on rendered content
  first.
2026-08-14 06:37:30 +02:00
Marc-André Bombeck 4eeaec74aa Give the tiered context its promised live fallback and un-truncate all-time stats
- The tiered AI context's band reader now falls back to a live grouped
  aggregate when a rollup band is empty (the module doc promised
  replace-with-fallback from day one; only the replace half existed), so
  a coverage-miss or never-folded YEAR partition no longer hands the
  model empty history. Far-from-UTC users get the day-grain band keyed
  on their own calendar (the same ±3h guard the correlation readers
  carry).
- The slim analytics slice splices measurements older than the 5-year
  fold window into its all-time count/min/max/mean: the rollup tier
  only covers the window, so "all time" silently truncated for long
  histories while the live fallback told the truth. A type whose only
  rows are pre-fold no longer reads as never logged.
2026-08-14 06:24:37 +02:00
Marc-André Bombeck 7611c82ae7 Poll on real conditions in the e2e suite and un-age the expiry fixtures
- account-sharing polls the offline persister's own IndexedDB store for
  the flushed snapshot instead of sleeping past the debounce.
- The record-session-fence cases poll for the observable halves of their
  setups (the switch round-trip landing, the exit switch being issued);
  the one remaining fixed window is a documented absence-assertion grace
  with nothing to poll on.
- The documents suite's two remaining sleeps are named for what they
  are: a focus-dance grace the outer document cannot observe, and the
  long-press gesture duration itself.
- The inventory-date fixtures derive their printed expiry from now
  instead of a fixed 2027 date that would silently flip the fixture to
  expired when the calendar catches up.
2026-08-14 06:17:34 +02:00
Marc-André Bombeck 97cb63a77f Report every restored section, disclose export decrypt losses, re-fold on zone change
- The restore summary counts practitioners, encounters, the three link
  tables, and vaccinations — restored in full since 08-01 but absent
  from the report, so a file carrying visits or an Impfpass read as if
  those sections were empty.
- A portable export that cannot open a field's ciphertext still nulls it
  fail-soft, but now names the loss in the file's own decryptFailures
  manifest — an export with a lost emergency note is no longer
  byte-identical to one where the note was never written.
- A timezone change enqueues the medication-compliance re-fold: the
  rollup keys its rows by the local day minted under the OLD zone, and
  the coverage probe compares counts, not keys, so nothing else could
  notice the stale bucketing.
2026-08-14 06:14:13 +02:00
Marc-André Bombeck ac44b35867 Claim reminder slots before egress, classify the bulk race, fold the vault probes
- The measurement-reminder tick claims its slot in the record-event
  ledger BEFORE any provider egress (the documented claim-first pattern
  from reminder-dedup.ts); a crash between dispatch and the nextDueAt
  advance can no longer double-send.
- mood-entries/bulk classifies a lost P2002 race as the duplicate it is
  (with the winning row id) instead of a skip carrying a raw Prisma
  message — the row IS stored, the racing twin wrote it. The workouts
  batch already re-derives per-entry status from RETURNING.
- The vault list's content-index and thumbnail probes ride the same
  Promise.all as the link loads: four independent grouped queries, no
  serialized round-trips on a 4s-polled list.
2026-08-14 06:06:43 +02:00
Marc-André Bombeck 14e9edfa7a Adopt the shared post-mutation tail everywhere a Measurement is written
The six measurement routes carried eight copy-pasted rollup-recompute +
status-invalidate blocks — the documented two-ended failure class
waiting for the next surface to remember one leg and forget the other.
All of them now call afterMeasurementMutation (the helper the deletion
fix introduced), and the two write surfaces that bypassed the hook
entirely join it: the nightly Recovery/Stress/Strain score rows and the
PHQ-9/GAD-7 assessment projection now recompute their (type, day)
bucket on the tick that writes them.
2026-08-14 05:59:12 +02:00
Marc-André Bombeck 6ebd5e8711 Guard the operator's cap on fallback hops and reap dead summary promises
- The provider-chain walker now checks the day's recorded spend against
  OPERATOR_COST_CAP before invoking an operator-funded admin-* entry. A
  request whose primary provider runs on the user's own key reserves
  under the generous user-plan ceiling; a fallback hop (or health-ledger
  reorder) onto the operator's key could then spend past the operator's
  cap unchecked. An exhausted cap skips the candidate like a failed hop.
- summaryState PENDING gets a giver-upper: the detail serialiser
  degrades a PENDING older than an hour to UNAVAILABLE (which offers the
  manual generate action), and an hourly reaper persists the same heal
  following the orphan-ImportJob reconcile precedent — a job dead past
  its retry budget no longer leaves the sheet saying "generating"
  forever.
2026-08-14 05:53:17 +02:00
Marc-André Bombeck f67fcec1c9 Complete the intake-event spec and align workout nullability with the DTO
- MedicationIntakeEvent declares the full row both intake responses
  actually return: autoMissed, attributionSource, injectionSite,
  doseTaken, inventoryConsumption, externalId, updatedAt, syncVersion,
  deletedAt were served but undeclared.
- GET /api/medications/{id}/intake is published (query schema, paged
  envelope); the spec only knew the POST while the client-facing
  history list has consumed the GET since v1.4.37.
- WorkoutListEntry's sportType/startedAt/endedAt/durationSec become
  nullable, matching the DTO — declaring them non-null was a
  strict-decoder bomb for the Swift client.
- OpenAPI regenerated.
2026-08-14 05:44:36 +02:00
Marc-André Bombeck 4b009c3a45 Publish the resolved per-slot dose units and a slot-aware runway on the medication wire
A medication whose slots carry different doses (a whole tablet in the
morning, a half at noon — #219) was consumed correctly but reported
wrongly: the wire shipped only the raw nullable per-slot column (clients
had to derive the inheritance), stockDosesRemaining divided by the
medication-level units alone, and no runway figure existed outside the
low-stock push.

- Every schedule now carries resolvedUnitsPerDose, resolved server-side
  exactly like the intake consumption resolver.
- stockDosesRemaining divides the units pool by the schedule-weighted
  average units per dose.
- runwayDays (whole days of supply under the slot-aware burn rate) rides
  the list AND detail payloads; the detail GET also gains the stock
  aggregates the list already had.
- The low-stock engine runs the same slot-aware math, so the push and
  the wire cannot disagree; the web cards, table, and detail Übersicht
  prefer the server figure over their client estimate.
- OpenAPI regenerated with the new fields.
2026-08-14 05:41:15 +02:00
Marc-André Bombeck 542ca91be5 Finish the wiring polish: verbosity gate, upload flash, /about links, dead settings slugs
- The Coach verbosity picker is disabled while the concise tone forces
  brief, with a hint saying so, instead of a live control that silently
  does nothing.
- A fresh document upload flashes its new row like the duplicate path
  always did; the settle decision is a pure exported helper with a test.
- /about gains its two inbound links: the /privacy footer and a
  Settings→About credits row (the GeoLite2 EULA wants the attribution
  reachable from the running app).
- The eight settings slugs shadowed by permanent redirects (the seven
  layout children + sharing) leave the slug registry: no more
  prerendering unreachable pages, no dead component wirings, and the
  SectionPlaceholder fallback that could never render is gone. The
  redirects, section components, and layout-hub subpages are unchanged.
2026-08-14 05:31:33 +02:00
Marc-André Bombeck 3b1314d1b0 Enforce the reminder nag cap, compare the disclaimer version, drop the unread analytics columns
- The daily Coach sweep now charges each ignored day against
  surfaceCount and auto-dismisses at three — the cap the schema comment
  promised since v1.22 but nothing enforced.
- The welcome gate compares the stored disclaimer acknowledgment
  version against the current one, so revised disclaimer text
  re-prompts; /api/auth/me carries the version for the client.
- slope90 and anomalyCount leave the analytics wire: slope90 had no
  reader anywhere (computed on every request, in SQL twice), and the
  slim path could never compute anomalyCount (it always reported 0).
  anomalyCount stays as an in-process field on summarize() for the
  insights feature builder, which is its only real consumer.
2026-08-14 05:19:05 +02:00
Marc-André Bombeck 6b3a5a4182 Settle the four remaining layout deviations from the audit
- Vorsorge dashboard tile title joins the dashboard heading ladder
  (titleAs=h2 like its sibling tiles).
- A user's own note on the mobile measurement card renders in the
  foreground colour; user data is never muted.
- The compact Vorsorge list row expresses its density on the Card
  instead of overriding the content slot's padding with an off-scale
  step.
- The AI-consent card holds its space with a skeleton while the receipt
  loads instead of popping in and shifting the section below.
2026-08-14 05:07:14 +02:00
Marc-André Bombeck 487eb6970c Polish the copy the audit flagged across all six locales
- Singular variants for the bulk-delete toast and confirm dialog
  (measurements + mood); the call sites branch on a count of one.
- Consent confirm buttons shortened so they no longer overflow the
  small button on phones.
- Workouts empty-state CTA is source-neutral instead of assuming an
  iPhone with Apple Health.
- "Pills" is no longer a navigation term in a medication app: DE says
  Navigations-Chips, EN chips, PL chipy; ES/FR/IT subtitles align with
  their own established terms.
- Health-score insufficient hint drops the translationese and fixes the
  pronoun.
- Side-effect tag helper uses the established Stimmungs-Tags term.
- Success toasts that are single fragments lose the terminal period
  (37 keys, all locales).
- Integration pill parked state short enough to survive truncation.
- The iPhone-managed reminder badge carries a short label; the full
  sentence moved to a helper line below instead of clipping mid-word.
2026-08-14 05:02:49 +02:00
Marc-André Bombeck 1cde353965 Merge pull request #792 from MBombeck/release/v1.37.18
Release v1.37.18
2026-08-14 04:19:03 +02:00
Marc-André Bombeck dd885043c4 chore(release): v1.37.18 — the app stops promising what it does not do 2026-08-14 04:01:21 +02:00
Marc-André Bombeck 9e555b7fd2 Expect the fenced label on the real-DB preventive-care read
The integration twin of the tool test still asserted the raw reminder
label; the tool now fences it like the appointment reason beside it.
2026-08-14 03:56:38 +02:00
Marc-André Bombeck 8ee123d06b Settle the suite-wide fallout of the wave
The evaluator stubs hoist properly for vitest's factory rewrite, the
WHOOP webhook route test's prisma double learns the pre-image read the
delete branch now performs, and the connector-token card description
shrinks to the one-sentence, 120-character shape the card guard
enforces — still saying what the mint truthfully does.
2026-08-14 02:40:53 +02:00
Marc-André Bombeck 2b3a67d43c Keep the leaf-guard regexes inside the compiler's target 2026-08-14 02:34:40 +02:00
Marc-André Bombeck 95baf58be7 Harden the guards that could go green for the wrong reason
The bearer MINT matcher demanded a literal apiToken.create( in the very
file that documents how a whitespace-wrapped call walked past its T1
sibling; it is whitespace-tolerant now, asserts a non-zero match count,
and the always-true filter beside it is gone. The T1 resolver matcher no
longer demands tokenHash first in the where object. The English-leak
guard pins a non-zero key floor per bundle so a broken walker cannot
pass as no-leaks-found. The two audit-row integration suites poll for
the fire-and-forget rows instead of sleeping a fixed span, with one
deliberately widened grace kept for the absence assertion. And the
fixture fuses with 2027 horizons (suggested-actions next-due, the
printed-expiry trio) are now-anchored so they can never age into
inverted assertions.
2026-08-14 02:33:07 +02:00
Marc-André Bombeck b49013e6c6 Bound the sleep-timeline delete to the window the re-sync can restore
The Withings arm of the backfill deleted the source's entire
SLEEP_DURATION history while its re-sync fetches only the trailing 30
days regardless of fullSync — every older night was raw data loss with
orphaned rollup buckets on top. The delete is now bounded to the
re-sync window and the touched rollup span is recomputed afterwards;
WHOOP keeps the whole-history clear because its full sync genuinely
re-imports every night.
2026-08-14 02:29:01 +02:00
Marc-André Bombeck 2c0b4d60dd Re-anchor the service-worker fallback cache version
The fallback stayed at v1.37.15 through two releases while package.json
moved on, and the anchor test that exists to catch exactly this reads
red on the tip. Point it at the current release.
2026-08-14 02:26:05 +02:00
Marc-André Bombeck b7dfd236ee Move the API error classes into a leaf module
api-handler imports the record-session fence and the fence threw
RecordSessionChangedError / SharingAccessDeniedError imported back from
api-handler — the one real import cycle in the tree, working only by
evaluation-order luck. HttpError, the SharingAuthError family and
StepUpRequiredError now live in api-errors.ts (importing nothing but
the fence contract), api-handler re-exports the identical class objects
so no importer moves, and the fence imports the leaf. A guard pins both
the identity and the leaf structure.
2026-08-14 02:26:05 +02:00
Marc-André Bombeck d75034a9f4 Mint a default Idempotency-Key on every client POST and PATCH
Every apiHandler route accepts the header and the wrapped write routes
dedupe on it, yet almost no client call site sent one — a replayed
create could land a duplicate dose or vaccination and shift the series
index and booster-due date behind it. apiPost and apiPatch now mint a
per-call crypto.randomUUID() key unless the caller set its own; reads
stay bare.
2026-08-14 02:19:59 +02:00
Marc-André Bombeck 3973af69d4 Fence the reminder free text the preventive-care tool shipped raw
get_preventive_care passed a reminder's label and location — the user's
own free text — unfenced beside a fenced sibling, and get_lab_history
shipped the document-derived canonical analyte raw while sanitizing the
valueText next to it. Both are the marker-forging class the fence
doctrine exists for: fence label and location like the appointment
reason, scrub and sanitize the analyte like the default labs path.
2026-08-14 02:16:46 +02:00
Marc-André Bombeck 30aad51fac Sweep the measurement caches after Google Health and Withings syncs
Both hourly sync tails left the per-user analytics, correlations,
targets, derived and achievements caches serving pre-sync bodies until
their TTL lapsed — the correlations route documents the exact invariant
these tails were breaking. Mirror the Fitbit tail: mark the cells stale
whenever rows landed, on partial failures too.
2026-08-14 02:12:49 +02:00
Marc-André Bombeck 4e12aef5fd Type the evaluator stubs as variadic mocks
tsc rejects spreading unknown[] into a zero-parameter vi.fn; give the
context-evaluator stubs a variadic signature and cast the recorded call
tuples where the tests read them back.
2026-08-14 02:07:42 +02:00
Marc-André Bombeck db6465c17d Account for every dropped Apple Health sample the result used to hide
Three silent gaps in the import accounting, one commit:

The reproductive samples of an export land in recordsRead but were
discarded without a counter when cycle tracking is off — the result now
names them (samplesSkippedModuleDisabled). A cycle flush that failed
partway zeroed its stats AFTER day-by-day writes had landed; the flush
is now fault-isolated per day and reports daysFailed plus the first
failure reason instead of claiming nothing happened. And the import
card hardcoded skipped: 0 while the worker has computed, persisted and
served per-class skip counters since v1.15 — it now renders them,
splitting deliberate exclusions (unsupported and deferred types, a
disabled cycle module) from genuine refusals (unparseable, out of
range, failed writes), with a per-type breakdown. Only refusals tip
the outcome tone.
2026-08-14 02:06:19 +02:00
Marc-André Bombeck a45dde2039 Retire the guardian toggle over a pref nothing reads
The evidence disclosure stopped honouring showEvidenceByDefault in
v1.4.27 and the owner surface retired the control with it — but the
managed-record coach form still offered the switch, silently governing
nothing. Remove the control, the managed-schema pick, the response
field, and the label in all six locales; the strict schema now refuses
the key outright.
2026-08-14 01:56:25 +02:00
Marc-André Bombeck 15fb5dbbdb Point the import-guide links at the docs site that actually has them
Both import cards linked /docs/integrations/data-import — a path the
app never serves, so every click 404'd. Link the external docs site
through the shared INTEGRATION_DOCS_BASE constant, opening in a new tab
like every other integrations runbook link.
2026-08-14 01:54:10 +02:00
Marc-André Bombeck c23e677b6e Gate the bottom-nav Meds slot on the medications module
The mobile bar pinned /medications unconditionally while the page
renders nothing when the medications module is off — a visible tab over
a blank screen. Run both fixed flanks through the one slot filter the
Insights slot already uses (sharing coverage + module map, fail-closed
until mounted), so a disabled module is hidden everywhere instead of
relocated.
2026-08-14 01:52:37 +02:00
Marc-André Bombeck 11aa3dc060 Stop describing a Research-Mode gate that no longer exists
The titration-curve docblock contrasted itself against an estimated-PK
chart 'behind the Research-Mode gate' — that switch was retired as inert
and the columns dropped with migration 0321. Describe the real contract:
both charts render ungated, the estimated one carrying the persistent
modelled-not-measured disclaimer.
2026-08-14 01:48:31 +02:00
Marc-André Bombeck cd127010fe Evaluate the context cues the reminder grammar has promised since v1.22
A Coach reminder captured with NEXT_BP_LOGGED, NEXT_WEIGHT_LOGGED,
NEXT_SLEEP_LOGGED or NEXT_APP_OPEN confirmed to the user and then never
fired: the daily sweep skipped context triggers and no other evaluator
existed.

Build the evaluator. The three logging cues resolve on evidence — a
live matching-type measurement logged after capture — and ride the same
eventful reminder-satisfy hook every ingest path already fires, with the
daily sweep re-running them as the idempotent backstop. NEXT_APP_OPEN
resolves on the nudge-status read (the poll that mounts with the app
chrome), owner-only so a delegate's visit never satisfies it, with a
capture grace so the session that created the reminder does not count as
the next open. Every trigger delivers through the surfacing transaction
extracted from the sweep: conversation + assistant message + status
flip, all-or-nothing.
2026-08-14 01:45:47 +02:00
Marc-André Bombeck 0cec8b07bd Publish the vaccination booster mint and upload suggestion
The iOS tracker was told both endpoints were in the spec; neither was
registered. Publish POST /api/vaccinations/{id}/booster (201 mint /
200 re-anchor with the resolved MeasurementReminder DTO) and
GET /api/vaccinations/suggest (the server-decided one/many/none
verdict), and regenerate the YAML. A structural guard now derives the
expected path set from the route files so the next vaccination route
cannot ship unpublished.
2026-08-14 01:30:28 +02:00
Marc-André Bombeck cb86b24c0d Tell the truth about what a connector token can do
The mint card called every connector token read-only while the
health:write toggle sat directly beneath it — a token minted with the
toggle on writes measurements and mood entries. Rewrite the card
description and scope note in all six locales so the copy matches the
mint: read is the floor, write is a per-token choice made at mint time.
The copy guard now pins the pair so the read-only claim cannot return.
2026-08-14 01:28:03 +02:00
Marc-André Bombeck c7400abb48 Scrub document-derived biomarker names before they reach the prompt
The biomarker catalog mints name and unit from labResult.analyte —
model-transcribed free text out of an uploaded document. Both rode into
the status generator raw, the name in system-prompt position, so a
hostile PDF could smuggle instructions past the fence the coach
labs-snapshot already applies to the same fields. Sanitize both at the
snapshot and the system-prompt site.
2026-08-14 01:25:15 +02:00
Marc-André Bombeck 9fb5d7d7d0 Route measurement deletions into the rollup recompute path
A soft-deleted measurement never reached the rollup tier: the WHOOP
delete webhook tombstoned rows without recomputing the dirtied buckets,
and the freshness watermark probe filtered tombstones out, so the
deletion's updatedAt bump was invisible and the ghost aggregate read as
fresh forever.

Extract the post-write tail every measurement surface repeats into
afterMeasurementMutation (rollup recompute + status-insight
invalidation, both best-effort), call it from the WHOOP delete webhook
with the (type, measuredAt) pre-image collected before the updateMany,
and drop the deletedAt filter from the watermark probe so a tombstone
counts as staleness.
2026-08-14 01:22:41 +02:00
Marc-André Bombeck a3f0698525 Merge pull request #791 from MBombeck/release/v1.37.17
Release v1.37.17
2026-08-13 23:16:12 +02:00
Marc-André Bombeck 82a535c9b5 chore(release): v1.37.17 — the discovery reads days, not readings 2026-08-13 22:58:38 +02:00
Marc-André Bombeck 35d798ad68 Round-trip the rollup swap through the real writer
The unit battery derives rollup fixtures in JS; this pins the same
parity through the pipe itself. Seed raw measurements, read the tiered
fetch before the fold (coverage miss, raw path baseline), fold with the
real recomputeUserRollups DAY pass, read again, and assert the two
daily series are equivalent — including a dual-source weight day whose
per-source rows must compose to the all-source mean. A drifted writer
projection, coverage-probe SQL, or bucket compose surfaces here.
2026-08-13 22:07:57 +02:00
Marc-André Bombeck f9ac7a3327 Pin the rollup swap's parity, fallback, and eligibility contracts
Both paths read identical fixtures — per-(day, source) DAY rollup rows
derived from the same raw rows the fallback reads — and must produce
equivalent daily series: the plain daily-mean case, the multi-source
day (the all-source weighted mean, never a ladder-collapsed single
source), and the pre-sum_value mean-times-count compose. A far-from-UTC
profile timezone must force the raw path so day keys stay profile-tz
keyed; the near-UTC midnight band's single-day attribution shift is
pinned explicitly so it stays a documented decision rather than drift.
Coverage misses and empty in-window bucket reads fall back per channel;
sleep and the cumulative types never enter the rollup query.

Every assertion family was broken on purpose and observed failing with
the site named before restoring green; the record sits in the test's
doc comment. The route test mocks the new coverage probe and bucket
read as empty so every channel rides the raw path unchanged there.
2026-08-13 22:06:10 +02:00
Marc-André Bombeck 8390b4d24e Serve correlation-discovery spot channels from the DAY rollup tier
The discovery scan read every raw measurement in the 180-day window for
all nine measurement channels and bucketed them into daily means in JS,
paying tens of thousands of rows on every cache miss (a CGM glucose
channel alone can exceed the read cap). The DAY rollup tier already
stores those per-day aggregates, so eligible spot channels now read one
pre-aggregated row per day per source and compose the all-source
count-weighted mean — the exact reduction toDailyMeans applies.

Read-swap replaces the raw read per channel, with fallback-on-miss:
structural ineligibility (SLEEP_DURATION's per-night reconstruction,
the cumulative types' device-type collapse axis the rollup rows do not
carry), a far-from-UTC profile timezone (the v1.4.38 W-A near-UTC
guard), a coverage-probe miss, or an empty in-window bucket read all
route that channel to the existing raw path. The SWR cache cell stays
in front; the swap only lowers the cost of a cache miss.
2026-08-13 22:00:27 +02:00
Marc-André Bombeck f44d2276fa Merge pull request #790 from MBombeck/release/v1.37.16
Release v1.37.16
2026-08-13 21:15:19 +02:00
Marc-André Bombeck 5374bed5b7 Raise the nanoid override floor past the zero-size loop advisory 2026-08-13 20:57:58 +02:00
Marc-André Bombeck 5d508575c9 chore(release): v1.37.16 — every write reaches every reader 2026-08-13 20:37:28 +02:00
Marc-André Bombeck 84176af515 Enrol the two new prefetching pages in their structural guards
The prefetch-caching guard's frozen route set and the session-surface
guard's direct-derivation list both name every RSC prefetch wrapper;
/checkups and /mood join them with the same reasoning as their five
predecessors — getUnswitchedSession only, skipped under a switch.
2026-08-13 19:11:57 +02:00
Marc-André Bombeck 61114fab90 Accelerate the chart range switch, prefetch two list pages, calm two polls
placeholderData keeps the previous range painted while a health-chart
range switch fetches, paired with its truth condition: the container
dims and goes inert while isPlaceholderData is true, so the old range
cannot masquerade as the new one. The mood chart needs no pairing — its
range is a client-side slice over one static-key query and never drops
to a skeleton.

/checkups and /mood gain the dashboard-template RSC prefetch: the
primary list read moves into a shared lib read (route + wrapper consume
one query, so filter/order/wire shape cannot drift), the wrapper honours
the DASHBOARD_SSR_PREFETCH kill-switch, resolves identity through
getUnswitchedSession, JSON-round-trips the dehydrated state, and fails
soft to the bare client on every error path. Page-prefetch unit tests
pin the seeded keys and the fail-soft arms; the SSR hydration spec
gains an assertion per page.

The achievement-unlock poll drops to five minutes (in-app writes already
invalidate the cell; the poll only covers out-of-band ingest), and the
plan-proposal poll gains the advisor-style bounded attempt ceiling so an
open thread stops polling after its budget.
2026-08-13 19:06:56 +02:00
Marc-André Bombeck ac96e5e975 Cache the correlations discovery read and keep writes off the hit path
GET /api/insights/correlations was the most expensive uncached read in
the app: a 180-day window, ~10 parallel series reads, Pearson + FDR
in-process, plus two syncAcceptedPatterns DB writes — all paid on every
mount. The built body now reads through the analytics bucket's SWR cell
(60 s fresh / 1 h stale, keyed userId|correlations|locale), and the
pattern-sync writes live inside the builder, so a cache hit performs no
write on the read path. Eviction truth comes free: measurement, mood,
medication, illness and custom-metric writes already sweep the user's
prefix in that bucket, and a pattern dismiss sweeps it through
invalidateUserCorrelationPatterns.

The route test pins the contract: a second GET inside the fresh window
re-runs neither the measurement window read nor the pattern sync, and
serves a byte-equal body.
2026-08-13 18:52:07 +02:00
Marc-André Bombeck f2f40ae8b2 Pair every daily-read invalidation with its inactive refetch
Ten client mutation sites forgot a consumer: a coach-accepted checkup
stayed invisible for up to five minutes, a threshold or target edit left
the dashboard bands stale, a score-config save marked the daily reads
stale but never refetched them, a booked visit missed the Today rail, a
source-priority reorder kept every chart on the old canonical picks, an
adopted self-context note never reached the Settings read. Each site now
invalidates what its write changed and forces the unmounted snapshot +
digest reads to refetch through refetchInactiveDailyReads.

New illnessDependentKeys bundle carries the daily reads (Rest Mode
frames both), dailyDigest joins encounterDependentKeys, and the
chart-data prefix gains a factory accessor for whole-cache flushes.

The daily-reads guard learns the cycle / encounter / vaccination /
illness bundle families and a second matcher for direct snapshot/digest
invalidateQueries without a forced refetch, each with a frozen reasoned
allowlist. Both matchers were proven live by reverting a fix and
watching the guard go red (see the test doc comment).
2026-08-13 18:48:10 +02:00
Marc-André Bombeck 002d120b69 Reach every cached reader from the integration and context write paths
Integration syncs (Fitbit, Oura, Polar, WHOOP, Strava, Nightscout) now
mark the per-user analytics cells stale and sweep the workouts cache at
their sync tails — imported rows used to stay invisible to the cached
dashboard, analytics and workout readers until the TTL lapsed. The WHOOP
per-resource webhook/cron driver and the Polar workouts leg carry the
same call, matching the posture Google Health and the workout batch
route already had.

Illness, cycle and encounter write routes hard-evict the analytics
bucket through the new invalidateUserHealthContext helper: Rest Mode,
the cycle context and the Today-rail appointment feed all read from
cached cells under that bucket, and an interactive write must be true on
the very next read.
2026-08-13 18:33:46 +02:00
Marc-André Bombeck e3169fe3b3 Merge pull request #789 from MBombeck/release/v1.37.15
Release v1.37.15
2026-08-13 14:19:17 +02:00
Marc-André Bombeck feb3ad93fd chore(bundle): raise the aggregate cap for the async-truth copy
The settling state's copy, the index-outcome plain-words line across
six locale catalogs and the reindex-count wiring take the whole-build
client sum to 3429 KB gzip, one kilobyte over the cap set at v1.37.4.
Every per-route ceiling stays met, so nothing a person downloads on a
given route grew beyond its ceiling; the aggregate cap moves to 3452
with the same margin as previous re-measurements.
2026-08-13 14:01:37 +02:00
Marc-André Bombeck 297496b517 chore(release): v1.37.15 — async work reports what actually happened 2026-08-13 13:38:44 +02:00
Marc-André Bombeck 589b35589b Prove the raster-failed chain and name the fax-codec cause
The residual scan from the report is a CCITT Group 4 single-image PDF,
the codec class pdfjs rasterization is known to fail on. Chain checks:
a pdfjs open failure or throw already lands as render-failed with the
error text annotated; the zero-pages shape now annotates too instead
of returning silently. An end-to-end test drives the REAL rasterizer
through prepareVisionInput and pins the rasterFailed mapping; the test
header documents why a tiny in-repo CCITT fixture is deliberately not
checked in (probed against this pdfjs version, it renders the page as
blank instead of throwing, so the fixture cannot deterministically
fail and would be flaky across upgrades). The detail view's
raster-failed line now names scanned fax compression formats as a
known cause, in all six locales.

Refs #776
2026-08-13 13:04:41 +02:00
Marc-André Bombeck 408c1f599a Resolve the settle verdict in render, not in an effect
Same guarded transition, expressed as the render-phase state
adjustment the hooks lint rule asks for: a resolved settle clears the
state in the same committed render that carries the outcome, so the
falling-edge toast still sees both flips at once and the block runs at
most once per settle.
2026-08-13 12:46:55 +02:00
Marc-André Bombeck b2908343c4 Use the consent surface the error type expects in the contract test 2026-08-13 12:43:27 +02:00
Marc-André Bombeck dceca62f8e Pin the async-truth contract over both document state machines
Two contract tests enumerate every branch of the summary job and the
index tree and assert each ends in a terminal state write: the summary
job's opt-out branch heals a phantom PENDING back to NONE, every
failure branch lands UNAVAILABLE or WITHHELD, success lands READY; the
index tree records an attempt outcome on every terminal branch,
success included. A third block pins the enqueue side: no PENDING is
claimed when the job's only branch would be the opt-out no-op, and
none before a job id exists. Honest scope stated in the test header:
these pin the two known machines, not a generic detector.

Refs #776, #788
2026-08-13 12:42:33 +02:00
Marc-André Bombeck 893db887e9 Record why a document's index attempt failed and say so
A content-index attempt that failed (raster failure, a scan with no
text layer, a provider error) recorded its reason only in the server's
observability stream. In the vault, hasContentIndex false looked
identical for a document nobody ever tried and one that failed three
times, and the detail sheet had nothing to say about either.

Apply the summaryState pattern to the index. Two additive columns on
InboundDocument (migration 0333) record when the last attempt finished
and why it produced no index, as a closed reason set: local-empty,
local-unsupported, decrypt-error, raster-failed, provider-error,
pdf-needs-anthropic, empty-transcription. The writer sits at the choke
point the auto job and the corpus backfill share, and in the manual
index route; a success clears the reason. The provider path's specific
failure now survives the local fallback, since "no text" is less
actionable than "the PDF would not render". rasterizePdf names its
failure class so a build that cannot rasterize at all is distinguished
from a PDF that would not render. New guard in both index paths: an
empty provider transcription never becomes a successful empty index.

The detail sheet renders the reason in plain words (muted, six
locales). The DTO and OpenAPI carry the two fields; the disaster
recovery backup and restore carry them verbatim like their summary
siblings.

Refs #776
2026-08-13 12:40:50 +02:00
Marc-André Bombeck 45dc93932a Settle a timed-out assessment refresh instead of calling it failed
The force regenerate aborts its request at 45 s while the server's
inline generation keeps running and usually writes the fresh briefing
moments later. The old handling fired an error toast at the abort and
re-read the old cache once; with a one hour staleTime and focus
refetch off, nothing ever converged, so the page claimed failure while
holding a finished assessment at arm's length.

A timeout now enters a settling state: the hook remembers the cachedAt
baseline it was showing and polls the read path on the existing
bounded cadence (25 s, up to 10 attempts) until it can prove an
outcome. Cache advanced past the baseline: the fresh payload lands and
the success toast fires. A failure marker newer than the baseline, or
the attempt cap: an honest error. While settling, the strip's button
stays busy and says the assessment is still being prepared; no toast
fires until the outcome is proven. Both poll reasons live in the
nextAdvisorPollInterval seam, the verdict in resolveAdvisorSettle, the
toast mapping in regenerateToastKind; all three are pure and pinned by
unit tests. The contract is documented at both ends (hook and generate
route). New copy in all six locales.

Refs #786
2026-08-13 12:24:46 +02:00
Marc-André Bombeck 86a3d74187 Report how many documents the reindex actually queues
The index-all trigger returned Boolean(jobId) while the client typed
the field as a number, so the toast read "Indexing true document(s)".
The route now answers with the count of live documents still lacking a
content index, computed from the same live-scoped counts the usage
gauge reads, and an honest 0 when no job was created. OpenAPI schema
updated to the integer shape; the hook's type carries a contract note
so the wire and the toast cannot drift apart again. Route test pins
the number, a component test pins that the toast renders the count and
never the word "true".

Refs #776
2026-08-13 12:13:55 +02:00
Marc-André Bombeck 4543fa7192 Let the app CSP frame and render its own blob previews
Since the record fence, vault previews load through object URLs: the
detail sheet frames a decrypted PDF from a blob: URL and thumbnails
render from blob: images. The app CSP carried no frame-src, so the PDF
iframe fell through to default-src 'self' and was blocked outright,
while img-src 'self' data: silently degraded every thumbnail to its
fallback icon.

Add frame-src 'self' blob: and extend img-src with blob: in both the
dev and prod policies. This admits exactly the app's own documents: a
blob: URL is mintable only by same-origin script, script execution
stays nonce-bound in production, and object-src 'none', frame-ancestors
'none' and default-src 'self' are untouched. The vault serve route
keeps its stricter document CSP. A unit test pins the directives so a
future CSP edit cannot silently regress the previews.

Refs #787
2026-08-13 12:08:59 +02:00
Marc-André Bombeck 2a85da67f7 Stop claiming a summary is pending when auto-read is off
The upload path enqueued a summary job and stamped PENDING without
consulting the owner's auto-read opt-in; the job's opt-out branch then
deliberately left the state alone, so a document uploaded with the
opt-in off said "summary is being generated" forever. Two writers,
contradictory assumptions.

Both ends of the contract now agree. enqueueDocumentSummary checks the
opt-in first and refuses to mint a job (or a PENDING) it knows the job
cannot resolve; the job keeps its own check for a pref flipped between
enqueue and run and heals a stranded PENDING back to NONE, scoped so
READY / WITHHELD / UNAVAILABLE stay untouched. Migration 0333 drains
the rows already orphaned. The view needs nothing: NONE already
renders the manual summary action.

Refs #788
2026-08-13 12:07:39 +02:00
Marc-André Bombeck c8b3f49915 Merge pull request #785 from MBombeck/fix/detail-fixture-horizon
Keep the workout-detail fixture inside the retention horizon
2026-08-13 11:51:32 +02:00
Marc-André Bombeck 698844d0e2 test(workouts): keep the detail fixture inside the retention horizon
Sister file of the HR-curve integration fixture fixed on the release
branch: the same fixed session day aged past the 90-day dense-intraday
horizon today. This suite stayed green because its pulse read is mocked
empty either way, which is worse — the fallback branch its comments
describe was silently no longer reachable, and the timezone assertion
pinned a literal next-day key. The session day is relative now and the
day key is computed from it.
2026-08-13 11:33:26 +02:00
Marc-André Bombeck 5ac096ede2 Merge pull request #784 from MBombeck/release/v1.37.14
Release v1.37.14
2026-08-13 10:43:19 +02:00
Marc-André Bombeck 3e346e299c test(integration): keep the HR-curve fixture inside the retention horizon
The workout session sat on a fixed calendar day, and the pulse-window
fallback only reconstructs a curve inside the 90-day dense-intraday
retention horizon. On day 91 the fixture aged out and all three curve
assertions went red on every branch, ours and main alike. The session
day is relative to the test run now, ten days back, which stays inside
the horizon forever.
2026-08-13 10:25:39 +02:00
Marc-André Bombeck 499ca2c4b4 chore(release): v1.37.14 — the rail tells today's truth, immediately 2026-08-13 10:05:23 +02:00
Marc-André Bombeck e991ef7c77 Refetch the inactive daily reads after a quick-add intake
The medication quick-add mounts from the bottom-nav capture picker on
every page, not only on the dashboard, so its bare dependent-key bundle
invalidation (default active refetch) left the unmounted Today digest
and dashboard snapshot stale until the next poll — back on the home
screen the dose still read as due for up to two minutes. Route the
submit through invalidateMedicationReads, the one blessed entry point
that pairs the bundle with the forced inactive refetch, and drop the
surface's allowlist entry in the refetch guard: its dashboard-only
rationale stopped being true when the capture picker started mounting
this form globally. The other capture-picker forms (measurement, mood)
already pair the refetch.
2026-08-13 09:14:55 +02:00
Marc-André Bombeck 767a2b039b Bound the Today rail's non-overdue doses to the user's local day
A weekly or rolling medication with the default dose window opens its
availability ~25 h ahead of the anchor (one early day plus the grace
minutes), so the rail announced tomorrow's slot as today's pending
business — on Friday the Saturday dose appeared as due. Thread the
profile-timezone end of today from the digest IO seam into the builder
and keep a not-yet-overdue candidate off the rail unless it falls due
before that instant. Overdue candidates still always surface, and the
early-take affordance on the medication card is untouched.
2026-08-13 09:12:20 +02:00
Marc-André Bombeck 7e4a4d2544 Merge pull request #783 from MBombeck/release/v1.37.13
Release v1.37.13
2026-08-13 08:12:36 +02:00
Marc-André Bombeck 17fb291aaf fix(import): draw the extraction temp name from crypto randomness
The extracted export.xml lands in the shared system tmpdir under a
name built from the clock and Math.random, which is predictable enough
for a local pre-creation or symlink attack to aim at. The name comes
from crypto.randomBytes now. Flagged by code scanning on the import
path.
2026-08-13 07:55:07 +02:00
Marc-André Bombeck 91d4908204 e2e: pin the auto-read contract per document read state
The auto-read spec pinned the old collapse rule: with auto-read ON the
sheet always dropped the AI block. Since the read action stays visible
for a document that has no content index yet, the collapse assertion
now runs against the indexed content fixture, and a second test pins
the recovery path: an unread document keeps its AI section and manual
read under auto-read. Refs #777.
2026-08-13 07:35:15 +02:00
Marc-André Bombeck ff88dd1f8f coach: keep cancelled-turn markers out of the plan fold too
The facts fold already skips the empty assistant row a cancelled turn
leaves behind; the plan fold read it as a blank turn and spent one of
its recent-turn slots on nothing. Same skip, same reason. Also state
the accepted one-slot slack a late rate-limit refund can leave in a
freshly opened window. Refs #781.
2026-08-13 07:11:32 +02:00
Marc-André Bombeck 47b0d340b7 chore(release): v1.37.13 — the record reads honestly under load 2026-08-13 06:19:13 +02:00
Marc-André Bombeck ce6364f265 coach: keep cancelled-turn markers out of summary and fact folds
The rolling-summary and fact-extraction workers read message bodies
directly, so an empty cancelled marker would ride their prompts as a
blank assistant line. Skip empty bodies in both folds. Refs #781
2026-08-13 06:16:45 +02:00
Marc-André Bombeck a1b1617d0f settings: move the About-me note and free-text allergies into the Anamnese
The free-text self-context note and the free-text allergy line are
personal medical context, so they join conditions, allergies and family
history in Settings -> Anamnese. The note is its own card (same AI-surface
gate as the inclusion card); the allergy line sits directly under the
structured AllergyManager in the same card, labelled as a free-text
supplement so the two inputs never read as duplicates. The account
section drops the old panel. Store, API and query keys are unchanged;
the scoped Clear (note only, allergies untouched) carries over with its
tests. Orphaned strings removed, new labels in all six languages.
Refs #159
2026-08-13 06:16:45 +02:00
Marc-André Bombeck 13b7d0379b coach: reopen an interrupted conversation with a visible retry
An aborted stream now leaves a trace on both ends. The unmount cleanup
records the interrupted conversation (sessionStorage, one-shot) before
the abort fires, and invalidates the cached thread + rail so the return
visit refetches the advanced server state. The /coach page consumes the
record on its next mount: a known id reopens that thread, a first-turn
abort resolves via most-recent; every explicit entry intent (?c=, ?doc=,
?workout=, ?scope=, ?ask=) wins over the resume. The persisted cancelled
marker renders as a muted interrupted note with an Ask-again action that
resubmits the question through the normal send path and its gates.
Localised in all six languages. Refs #781
2026-08-13 06:16:45 +02:00
Marc-André Bombeck 9a631c8f8b coach: close an aborted turn with a persisted cancelled marker
Navigating away mid-reply aborts the SSE fetch; the provider call tears
down, but the conversation was left with the user message dangling and
no trace of the interruption. Persist an empty assistant row tagged
providerType "cancelled" (the refusal/nudge sentinel channel) when the
request signal is aborted, refund stays intact, and the abort is
annotated as insights.coach.cancelled instead of a provider failure or
a GlitchTip defect. Cancelled markers are filtered out of the provider
transcript on later turns. Refs #781
2026-08-13 06:16:45 +02:00
Marc-André Bombeck 12e5817c16 test(import): prove bounded heap on a large synthetic export archive
Generate a 700k-record export.xml (~200 MB decompressed, 500k
cumulative step records each carrying a fresh HKDevice runtime address,
200k interleaved spot rows) streamed into a temp stored-method ZIP —
never checked in, never held in memory whole — and push it through the
real extractExportXml + streamParseExportXml pipeline against a
discarding Prisma stand-in.

Live heap is measured after forced collections at every progress tick;
the asserted growth bound (48 MiB) is a quarter of the decompressed
volume. Both historical failure modes blow past it: reverting the
device-address normalization retains ~61 MiB of fragmented source
buckets, and unbounding the batch buffers retains ~76 MiB and starves
the progress ticks. The fixed pipeline measures under 1 MiB of live
growth. The suite also pins semantics alongside memory: every record
read, every spot row flushed, and exactly one cumulative estimate row
per day rather than one per device address. Refs #775.
2026-08-13 06:16:44 +02:00
Marc-André Bombeck d26bbca52a fix(import): translate machine-readable import failure reasons
A user whose import died to a worker restart saw the literal string
interrupted_by_restart in the import card — the reconcile writes it as
a machine-readable code, and the card echoed it raw. Classify the two
coded reasons (interrupted_by_restart, the insufficient_memory prefix
from the memory preflight) onto translated, actionable copy across all
six locales; the copy tells the user their data is safe and to upload
the export again, which the re-enabled card already supports. Honest
free-text reasons keep passing through verbatim. Refs #775.
2026-08-13 06:16:44 +02:00
Marc-André Bombeck 50ff90a409 feat(import): refuse an Apple Health import the heap cannot carry
Before the multi-minute unpack starts, compare the archive's declared
uncompressed export.xml size against the V8 heap limit. The streaming
parse keeps resident state span-bounded, so the model is generous —
a fixed 192 MiB base plus 1/64 of the XML size; the 8 GiB extraction
cap needs ~320 MiB, which any default heap clears. The check only
refuses the truly impossible (an operator-pinned tiny heap against a
huge export) and does so with an actionable failureReason naming
NODE_OPTIONS=--max-old-space-size, instead of an OOM-killed worker
and a job stuck in a running state (#775).

Document the memory model, the insufficient_memory refusal, and the
interrupted-import reconcile in the self-hosting scaling guide.
2026-08-13 06:16:44 +02:00
Marc-André Bombeck dd02f983cb fix(import): bound Apple Health import memory independent of archive size
The export.zip extractor buffered the whole archive through
readFileSync — hundreds of MB resident for the entire unpack phase on
a real multi-year export. The central directory is now located through
a bounded tail read on a file handle, read as one size-capped slice,
and the export.xml member streams through a byte-range read stream
into the inflate pipeline, so peak extraction memory no longer scales
with archive size.

The cumulative fold hashed the raw device attribute into its per-day
source buckets. Apple serialises that attribute from the live HKDevice
object including its runtime address (<<HKDevice: 0x283a08640>, ...),
which is not stable across the export enumeration — the map fragmented
toward one bucket per record and an 11-million-record export grew it
past the default 1 GB Node heap, killing the worker mid-parse (#775).
Stripping the volatile address before hashing restores the documented
invariant: parser state bounded by actual source cardinality.

Also carry split multi-byte UTF-8 sequences across read-chunk
boundaries with a StringDecoder — a bare per-chunk toString decayed a
split umlaut in a source name to U+FFFD.
2026-08-13 06:16:44 +02:00
Marc-André Bombeck a075a2fc50 Bump the service-worker version fallback to v1.37.12
The prebuild generator rewrites it on every build; keep the committed
literal in step so a stale checkout cannot resurrect old caches.
2026-08-13 02:27:05 +02:00
Marc-André Bombeck 0716f7a2fb Pin the declared diabetes flag's route contract with tests
GET/PATCH /api/auth/me/diabetes carried no test; the web toggle on the
Targets page and the iOS client both ride it. Cover the auth gate, the
resolved-state echo both ways, the field-by-field write, the audit row,
the 422 shape rejections, and the 429 path.
2026-08-13 02:27:05 +02:00
Marc-André Bombeck e83b58c9da Let the AI-consent card grant again after a withdrawal
POST /api/consent/ai/web now accepts an optional { intent } body. Without
one (the AI-settings mount heal) a standing revocation still blocks the
mint; intent "affirmative" is the user's own consent act and may
supersede an earlier revocation, exactly as a first grant would. The
consent card offers the explicit grant control whenever consent does not
stand, and the audit row records which intent minted the receipt.

The document auto-read opt-in already declared "affirmative" on enable;
the settings-mount heal posts no body. Both stay as they are.
2026-08-13 02:27:05 +02:00
Marc-André Bombeck fd104dd0ac feat(documents): review and extract lab values on the document itself
The server chain existed end to end (extract stages PENDING facts, per-fact
edit clears the low-confidence gate, confirm is the only write into the
structured stores) but the document detail offered no control over any of
it: it counted observation facts and linked to Labs. A user whose automatic
staging run was skipped had to re-upload the same PDF through Labs > Scan a
report.

- The detail sheet gains a staged-facts block with honest states: pending
  facts open an inline review (approve/reject per fact; a low-confidence
  fact is checked and saved first via the existing per-fact edit); a
  lab-filed, already-read document with nothing staged offers "Extract lab
  values" over its stored text; otherwise nothing renders.
- The extract route gains { mode: "stored" }: the same text-structuring
  pass the automatic worker runs, over the document's own content index.
  No re-upload, no second read of the original; full gauntlet including
  the shared document-AI bucket with charge-at-dispatch honesty; 422
  notIndexed when no stored text exists.
- A manual "Read with AI" / "Read again" now continues into the same
  lab auto-staging the background worker performs; the response reports
  labFactsStaged and the toast names the values waiting for review.
- Unchecked values are rejected and the copy says so; an unverified
  low-confidence fact receives no decision and stays pending rather than
  being silently discarded. Confirmation remains the only write into
  Labs, conditions, and medications; approved facts carry the
  committedRecordId link back to the source document (existing model, no
  schema change).
- The "lab values from this document" link now counts APPROVED facts
  only — it claims values that actually exist in Labs.
- Copy in all six locales; OpenAPI regenerated for the new extract mode
  and the index response field.
2026-08-13 00:33:14 +02:00
Marc-André Bombeck 8e16df6894 feat(documents): make the document-AI rate limit an operator setting with honest accounting
The document-AI actions (read/index, extract, suggest, summarise) shared a
hard-coded 6/hour bucket that lied twice: the 429 said "try again in a few
minutes" while the window is an hour, and several failure paths burned a
slot before any provider was dispatched.

- DOCUMENT_AI_LIMIT_PER_HOUR configures the shared per-user ceiling
  (default 6, clamped 1-1000), wired end to end: compose environment
  whitelist, .env.production.example, env manifest, operator docs.
- INSIGHTS_RATE_LIMIT_PER_HOUR joins the compose whitelist and manifest;
  it was documented but never listed, so an operator value could not reach
  the container.
- The 429 mirrors the bucket's reset instant into meta.retryAt (plus the
  existing X-RateLimit-Reset header); the client derives "try again in
  about N minutes" from it in all six locales, with a plural-aware key.
- A slot is consumed only when a request actually reaches the provider (or
  the local index/echo work): malformed bodies, unreadable originals,
  refused consent, and exhausted daily budgets refund the charged slot via
  a window-scoped refundRateLimit primitive. Consistent across all four
  routes sharing the bucket.
2026-08-13 00:33:14 +02:00
Marc-André Bombeck 592d1e9aa8 fix(documents): let index-all rasterise PDFs for image-input providers
The content-index backfill built its candidate MIME list from the
provider's native PDF support, so a provider that reads images but not
PDFs never saw a single PDF in "index all documents" — while the
per-document path already rasterises a PDF to page images for exactly
that provider class. The prefilter was stricter than the authority it
fronts.

PDFs are always candidates now; prepareVisionInput stays the per
document authority (native pass-through or rasterised pages). The run
summary also stops folding outcomes into one number: skipped (nothing
billable happened, retried later) and failed (a provider call missed)
are counted separately, carried through the wide event and the worker
log, and reruns stay idempotent because indexed documents drop out of
the candidate set.

Refs #776
2026-08-12 22:52:03 +02:00
Marc-André Bombeck 3254e44281 fix(documents): keep the read action visible for an unread document under auto-read
The AI section of the document detail sheet collapsed whenever auto-read
was on and nothing was pending review, without checking whether the
document actually has a content index. A document the automatic pass
never reached (uploaded before the preference, or the pass did not
complete) then had NO visible way to be read; turning auto-read off was
the only workaround.

Collapse only once the document is read (or when indexing is unavailable
on the transport, where no action could be offered anyway). An unread
document keeps the Read with AI action, introduced by a short honest
note in all six locales; the suggest and summarise extras stay hidden
because the auto-read promise still covers them. The three states stay
distinct: unread shows the note plus the action, an in-flight read shows
the reading label, a read document collapses the block.

Refs #777
2026-08-12 22:52:03 +02:00
Marc-André Bombeck 19c54082bf fix(score): read biomarker bounds by their real column names
The score reader's labs query selected referenceLow/referenceHigh on the
joined Biomarker, but the catalog's range columns are lowerBound and
upperBound. Prisma rejects a select against names a model does not have
at query-validation time, before any row is read, so every labs read
threw and both the Glycaemia and Lipids pillars reported a failed read
permanently, Retry included, even for accounts with valid lab results.

Select the real columns, map the catalog bounds onto the reader's range
fallback, and pin two contracts: a real-Postgres round trip that scores
both pillars through the biomarker join (including a lipid row whose
range lives only on the catalog), and the honest empty state, where a
labs account with no rows reads as not tracked rather than read_failed,
which stays reserved for a read that genuinely failed.

Refs #780
2026-08-12 22:52:03 +02:00
Marc-André Bombeck d21fe48e3c Merge pull request #773 from MBombeck/release/v1.37.12
v1.37.12 — the public privacy policy matches the app
2026-08-11 18:59:00 +02:00
Marc-André Bombeck 5191f213f4 chore(release): v1.37.12 — the public privacy policy matches the app 2026-08-11 18:20:18 +02:00
Marc-André Bombeck 40e2c71f42 Merge pull request #772 from MBombeck/fix/public-privacy-support
Align the public privacy data-flow disclosure
2026-08-11 17:56:18 +02:00
Marc-André Bombeck 92898b5271 docs(privacy): align the public data-flow disclosure 2026-08-11 17:36:15 +02:00
Marc-André Bombeck ca88d8c1a9 Merge pull request #771 from MBombeck/release/v1.37.11
v1.37.11 — one save for the lifestyle context
2026-08-10 10:43:54 +02:00
Marc-André Bombeck 1e89b8de9c chore(release): v1.37.11 — one save for the lifestyle context 2026-08-10 10:23:59 +02:00
Marc-André Bombeck 6e85cbb2f1 test(e2e): scan the mood insights page and fix its stale a11y mock
The `/api/mood/insights` mock still returned the pre-heatmap shape, so
`summary.totalEntries` was undefined, the empty-state guard never
short-circuited, and the page threw reading `heatmap.cells`. Correct the
mock to the current MoodInsightsResponse and add `/insights/mood` to the
a11y route matrix so the page is scanned henceforth.
2026-08-10 10:23:24 +02:00
Marc-André Bombeck cfda1d9a78 refactor(charts): route the mood chart header through TileHeader
The mood chart hand-rolled a CardTitle where every other insights tile
header goes through TileHeader. Swap it for the shared primitive, which
renders the same CardTitle at text-base, and drop the now-unused CardTitle
import. Like-for-like; the surrounding control rows are untouched.
2026-08-10 10:23:24 +02:00
Marc-André Bombeck 6130f6ee6f feat(records): save the whole lifestyle-context tile with one action
The lifestyle-context tile carried a Save button per fact kind. Collapse
them into one footer Save that writes only the dirty kinds, firing the
existing bitemporal call per kind (POST a first value, PATCH a revision)
and settling them together so a single conflict cannot take the healthy
writes down with it. A kind that 409s keeps its draft on screen and names
itself, instead of vanishing behind one green toast. The per-kind Remove
stays.
2026-08-10 10:23:24 +02:00
Marc-André Bombeck b81e3928d8 Merge pull request #770 from MBombeck/release/v1.37.10
v1.37.10 — one drug, a different dose at each time
2026-08-10 08:45:18 +02:00
Marc-André Bombeck 61e5c36d0a style(medications): prettier-format the per-slot consumption test 2026-08-10 08:22:42 +02:00
Marc-André Bombeck 196b37fa78 chore(release): v1.37.10 — one drug, a different dose at each time 2026-08-10 07:59:29 +02:00
Marc-André Bombeck dbb3f216d8 test(medications): type the consumption stamp reduce accumulator 2026-08-10 07:58:48 +02:00
Marc-André Bombeck 88763aaf7f test(medications): update consume mock for per-slot units reads
The consume hook now loads the user's zone, the schedules, and the
intake's scheduled anchor to resolve per-slot units, so the fake
client grows the schedule read and the batch scheduledFor lookup. The
Italian per-dose card label reworded so it no longer echoes English.
2026-08-10 07:58:48 +02:00
Marc-André Bombeck 83d31dc9c1 style(medications): prettier formatting for the per-slot override step 2026-08-10 07:58:48 +02:00
Marc-André Bombeck 33769de372 test(medications): cover per-slot units consumption and wizard round-trip
Integration: a medication with a morning slot at 1 unit and a noon slot
at 0.5 draws the right count for each taken dose against a real
Postgres. Unit: a per-slot dose + units set in the wizard survives
create and round-trips on edit-hydrate.
2026-08-10 07:58:48 +02:00
Marc-André Bombeck 3d6770ddb6 chore(api): regenerate OpenAPI for schedules[].unitsPerDose 2026-08-10 07:58:48 +02:00
Marc-André Bombeck 08a1dbccac feat(backup): carry per-schedule units-per-dose through backup and restore
The schedule exporter enumerates columns, so the new per-schedule
units-per-dose needs adding by hand: export it as a Decimal string in
the disaster-recovery payload, accept it in the wire schema, and write
it back on restore (NULL stays NULL to inherit). Extend the round-trip
test to prove a half-tablet slot survives export and re-import.
2026-08-10 07:58:48 +02:00
Marc-André Bombeck 80958ab307 feat(medications): show per-slot units on both med cards
Surface the per-schedule units-per-dose beside the per-slot dose the
card already prints, identically on the standard and the GLP-1 card,
so a split plan reads at a glance which time takes a half. Muted
addendum, no width movement.
2026-08-10 07:58:48 +02:00
Marc-André Bombeck 64093d2124 feat(medications): per-slot dose and units in the create wizard
Give each parallel schedule its own optional dose and units-per-dose
input on the times step, so a split plan (a whole tablet in the
morning, a half at noon) is ONE medication with three schedules
instead of two drugs that double-count. Leaving both blank inherits
the medication-level values, so a single-dose plan is unchanged. An
as-needed slot that sits alongside scheduled ones now rides the same
medication as a PRN schedule rather than flipping the whole-medication
as-needed flag. New keys land in all six locales.
2026-08-10 07:58:48 +02:00
Marc-André Bombeck 88123c53da feat(medications): accept and return per-schedule units-per-dose
Add schedules[].unitsPerDose to the create/update contract with the
same whole-number-or-curated-fraction validation as the medication
level, built into the Prisma data field-by-field on both the create
and the schedule-replace path. Unwrap the nullable Decimal to a JSON
number at every medication read/write response through one shared
serializer so the wire shape cannot drift, keeping NULL as NULL to
mean inherit-the-medication-level.
2026-08-10 07:58:48 +02:00
Marc-André Bombeck 820dde2365 feat(medications): consume per-schedule units for a taken dose
The inventory consume hook counted the medication-level units_per_dose
for every dose, so a split plan could not decrement a whole tablet in
the morning and a half at noon. Resolve the units from the taken
intake's own slot: match its scheduled wall-clock time in the user's
zone to a schedule and read that schedule's units_per_dose, inheriting
the medication level on NULL or no match. A medication whose schedules
all leave the column NULL resolves exactly as before. The batch-import
path binds each dose by its scheduled anchor the same way.
2026-08-10 07:58:48 +02:00
Marc-André Bombeck 0e34f9edda feat(medications): add per-schedule units-per-dose column
Add a nullable units_per_dose to medication_schedules so a split-dose
plan can consume a different unit count at different times of day (a
whole tablet in the morning, a half at noon) on ONE medication instead
of two. NULL inherits the medication-level units_per_dose, so every
existing row keeps its current behaviour. Migration 0332 adds one
nullable Decimal(10,4) column with no backfill.
2026-08-10 07:58:48 +02:00
Marc-André Bombeck 9a74bfb629 Merge pull request #769 from MBombeck/release/v1.37.9
v1.37.9 — the record you want a paramedic to have
2026-08-10 05:55:03 +02:00
Marc-André Bombeck 0de59a7360 chore(release): v1.37.9 — the record you want a paramedic to have 2026-08-10 05:33:51 +02:00
Marc-André Bombeck 57938982ea feat(settings): edit emergency profile under Anamnese
Add a Notfalldaten card to the Anamnese settings section with a manager
for the three enum facts and the three free-text fields, writing through
the new emergency route. Add every string across the six shipped locales.
2026-08-10 05:32:59 +02:00
Marc-André Bombeck 310a9a4690 feat(doctor-report): put emergency data on page one
Add an EMERGENCY leaf to the identity group of the report catalogue,
default-on, no module gate. When the leaf is admitted and the profile
holds emergency data, the aggregator collects it and the PDF renders an
emergency sheet as page one (banner, blood type, severe allergies, active
medications, chronic conditions, implants, advance directive and organ
donor, contacts, notes), then breaks to send the rest of the report to
page two. The section is withheld when the leaf is not admitted or no
data is present. Guards updated for the new leaf counts.
2026-08-10 05:32:59 +02:00
Marc-André Bombeck 6770bf3b7f feat(api): add emergency profile read and write route
GET/PATCH /api/anamnesis/emergency, wrapped in apiHandler. The PATCH
validates a partial body with per-field length caps, builds the Prisma
data field-by-field from the parsed input (never a spread), narrows the
user from requireAuth rather than the body, encrypts the free text on
write, and audits the change. The GET decrypts fail-soft for the form
prefill. Registers the OpenAPI operations and schema. An integration
test reads the row back to prove the write lands.
2026-08-10 05:32:59 +02:00
Marc-André Bombeck 772da42348 feat(backup): carry emergency profile through rotation and backup
Register the three encrypted emergency columns in the rotation registry
and the key-rotation script so a legacy-key drop cannot strand them.
Carry all six new columns through the profile backup builder and restore
(the enums by value, the free text as ciphertext in a DR payload or
decrypted plaintext in a portable export) and extend the wire schema.
The full-backup round-trip integration test seeds the six columns and
asserts each survives an export and restore.
2026-08-10 05:32:59 +02:00
Marc-André Bombeck 9e52285acc feat(profile): add emergency profile storage
Fold six nullable columns into user_health_profiles: three closed-set
enums (blood type, organ-donor status, advance-directive status) read as
plaintext, and three AES-256-GCM free-text columns (emergency contacts,
implants, ICE note). Migration 0331 is additive only: three CREATE TYPE
plus one ALTER TABLE with nullable ADD COLUMNs. An integration test
asserts the columns and enum types exist on the migrated schema.
2026-08-10 05:32:58 +02:00
Marc-André Bombeck a4bea8b0ce Merge pull request #768 from MBombeck/release/v1.37.8
v1.37.8 — the assistant can answer for your visits
2026-08-10 02:47:30 +02:00
Marc-André Bombeck 4d37ebfc8a chore(release): v1.37.8 — the assistant can answer for your visits 2026-08-10 02:19:59 +02:00
Marc-André Bombeck a38b3bd1df Redact a warning on the way into the wide event
addWarning pushed the raw string while setError, setHttp and
addExternalCall all scrub through redactSecrets. A warning routinely
carries an outbound error string, and for several integrations that
string is the request URL with a credential in it, so a secret could
reach stdout and the log store unredacted. It now scrubs on the way in
like the other entry points, and a test asserts a licence-key-bearing
warning is masked.
2026-08-10 02:18:45 +02:00
Marc-André Bombeck 5933a2dad0 test(links): freeze the link tables to their one gateway
A structural guard asserts that no file outside src/lib/links touches
the five link tables the service owns, with the two backup restore
writers as the only, frozen exemption. The matcher is whitespace
tolerant and proven non-vacuous: it must match every owned table inside
the service, so it can never pass by matching nothing.

This makes provable the property the link module was built for, that the
later absorption of these narrow tables into one join model is a storage
change behind the module rather than a sweep across every call site.
2026-08-10 02:18:45 +02:00
Marc-André Bombeck 448008ac93 feat(coach): give the snapshot a small visits context block
The Coach can now see that a visit is coming and what the last one was
about, without being handed a visit archive. The block is deliberately
small: the appointments booked within the next 14 days plus the single
most recent visit that happened. A full history is a get_visits
question, not a prompt-budget one.

Built as a peer of the illness and labs blocks and registered for
degradation EXPLICITLY against the lowest-priority cluster, so it is
among the first blocks shed when the character cap binds, before any
clinical cluster. Encrypted reason and outcome decrypt fail-soft and
every free-text string routes through the prompt sanitiser first.
2026-08-10 02:18:45 +02:00
Marc-André Bombeck a730ad188b feat(mcp): answer the visit history over the assistant wire
Add get_visits, a bounded read of past visits (default the last 12
months, optional practitioner-name filter) returning date, status,
kind, practitioner, specialty, the visit's own reason and outcome, and
the linked condition labels, newest first. Absence is explicit: an
account that has never recorded a visit reads { present: false }, never
{ present: true, visits: [] }.

Fold upcoming appointments into get_preventive_care as their own named
field rather than minting a second due-list tool, so a question about
what is coming up gets one answer. The Vorsorge arm stays free of
ENCOUNTER-origin reminders; the appointments are read from Encounter
directly. Reason and outcome ride the USER_TEXT wrapping, and every row
is scoped to the caller by construction.
2026-08-10 02:18:45 +02:00
Marc-André Bombeck 79de1181d8 Merge pull request #766 from MBombeck/feat/geolite2-runtime
feat/geolite2-runtime — runtime GeoLite2 fetch (#659)
2026-08-09 23:22:24 +02:00
Marc-André Bombeck 4757e0588c Allow the POSIX tar the GeoLite2 fetch test uses
The runtime fetch extracts databases in pure Node, but its unit test
builds a MaxMind-shaped tar.gz fixture with the system tar, which the
dead-code gate flagged as an unlisted binary. It is available in CI and
dev, alongside the docker and pg_isready entries already listed.
2026-08-09 22:58:09 +02:00
Marc-André Bombeck 0d496aaf86 chore(release): v1.37.7 — runtime GeoLite2 fetch for self-hosters
A self-hoster on the published image can set MAXMIND_LICENSE_KEY at
runtime and the app fetches the GeoLite2 databases itself, no rebuild or
manual mount. Refs #659.
2026-08-09 22:31:51 +02:00
Marc-André Bombeck 8bad747770 Keep the MaxMind licence key out of the runtime-fetch error path
safeFetch embeds the full target URL in its thrown error, and the
GeoLite2 download URL carries license_key=<secret> in its query string.
The wide-event warning and job-failure paths do not redact it, so a
timeout or network error on the runtime fetch printed the key to stdout,
Loki and GlitchTip in clear. The download timeout is 120s for slow
self-host links, so that path is expected, not rare.

The fetch now re-throws with the edition and the error kind only, never
the URL. As defence in depth, the central query-param redactor also
learns license_key, so any other path that logs such a URL through
redactSecrets is covered too. A regression test asserts the returned
error carries neither the key nor the parameter name.
2026-08-09 22:25:48 +02:00
Marc-André Bombeck 0a2cacb8b3 Document the runtime GeoLite2 fetch path
Cover the new MAXMIND_LICENSE_KEY route in the self-hosting guide as the
first of the three ways to get the offline databases (fetch, mount, bake),
and note that the monthly runtime refresh keeps a keyed host current on its
own. Add the variable to both env examples and to the env-check manifest so
the optional group lists it.

Refs #659
2026-08-09 22:09:12 +02:00
Marc-André Bombeck 869d91c4c2 Fetch the GeoLite2 databases at runtime when a licence key is set
The offline geo tier only reached a self-host two ways: baked into the
image at build time, or mounted from the host. Both need something the
operator of a stock `:latest` pull does not have. Add a third: set
MAXMIND_LICENSE_KEY and the worker downloads GeoLite2-City + GeoLite2-ASN
itself into GEOLITE2_DIR, so the offline tier starts working with no
rebuild and no manual mount.

A worker-only pg-boss queue drives it. Boot discovery fetches once when a
key is set and no database is present yet; a monthly cron (past MaxMind's
first-Tuesday reissue) keeps a keyed host current. The fetch is fail-soft:
each edition extracts to a temp file in the target directory and is
promoted with an atomic rename only after both are in hand, so a bad key
or an upstream error leaves the previous databases exactly as they were
and never writes a partial `.mmdb`. After a successful place the reader
cache resets so a running process picks up the files without a restart.

Extraction is pure Node (zlib + a minimal tar reader), not a shell-out:
this module is reachable from the worker-boot import chain, and a
child_process import there makes Next's file tracer pull the whole project
into the standalone output. zlib keeps the trace bounded and drops the
busybox runtime dependency. The download goes through safeFetch with the
public-host pin and redirect-following, since the MaxMind permalink 302s
to a signed CDN.

The runtime image now owns /opt/geolite2 as the unprivileged app user so
the worker can write it; a read-only bring-your-own mount at that path
still wins, because the fetch cannot write over it and fails soft.

Refs #659
2026-08-09 22:09:02 +02:00
Marc-André Bombeck 9e20b32154 Merge pull request #765 from MBombeck/release/v1.37.6
release/v1.37.6
2026-08-09 19:05:26 +02:00
Marc-André Bombeck 976c14b223 chore(release): v1.37.6 — the server-side safety pass
Two hardening changes collected on the trunk: a screening reminder can no
longer be marked done through a crafted request, and editing a custom mood
tag, tag group or cycle symptom now leaves an audit entry the way deleting
one already did.
2026-08-09 18:01:26 +02:00
Marc-André Bombeck fe17d06572 Give mood-tag and cycle-symptom edits an audit row
Editing a custom mood tag or group, and editing a custom cycle symptom,
wrote nothing to the audit ledger, while their delete siblings did. Two
of these paths destroy data: a custom mood tag or cycle symptom purged
with ?purge=true cascades its entry links and unpicks historical
entries, so a destruction left no trace of who ran it or when.

Every vocabulary-mutating verb now records an audit row: create, edit,
and delete for both custom tags and custom groups, and edit for a custom
cycle symptom. Encrypted labels are never logged; the row carries only
the field names touched and the resulting active state. The two
display-only writes on this surface, hiding a catalogue tag and
reordering the layout, stay ledger-free by design and say so inline,
since a per-user display preference is not a health-data write and a row
on every drag-to-reorder would be noise rather than a record.
2026-08-09 14:57:12 +02:00
Marc-André Bombeck 311adcfdda Refuse a manual satisfy of a screening reminder server-side
A Vorsorge screening (PHQ-9, GAD-7, WHO-5, SCI) resolves only from the
score row a completed check-in writes, never from a manual done. The web
and iOS clients enforce this by routing a screening to the check-in page
instead of offering the done action, but the satisfy and complete routes
trusted that gate and would stamp any reminder, screening included. A
crafted POST could therefore mark a screening satisfied with no
assessment behind it.

Both routes now reject a screening reminder with 409 before the shared
satisfy primitive runs, mirroring the client rule as defense in depth.
Typed numeric reminders keep their manual satisfy, which is intentional
and covered. The satisfy route gains its first route test alongside the
new guard case on complete.
2026-08-09 14:18:56 +02:00
Marc-André Bombeck 53359d292c Merge pull request #758 from MBombeck/release/v1.37.5
chore(release): v1.37.5 — the app-wide UI and copy polish
2026-08-09 13:30:55 +02:00
Marc-André Bombeck d711392bea chore(release): v1.37.5 — the app-wide UI and copy polish 2026-08-09 13:15:08 +02:00
Marc-André Bombeck a0200c61a6 Merge pull request #757 from MBombeck/fix/fable-retrofit-headers-spacing
UI: modernize managed-record controls, headers, and spacing
2026-08-09 13:04:25 +02:00
Marc-André Bombeck ca50b92025 docs(changelog): note the managed-record controls and spacing sweep under Unreleased 2026-08-09 11:38:59 +02:00
Marc-André Bombeck 7bb4fe3310 refactor(settings): modernize the managed-record controls onto the primitives
The delegated-caregiver settings forms were the last hand-rolled control
block: native <input>/<select> with a copied border literal, a native
type=date for the birth date (the browser-locale trap closed for the
owner surface in v1.25.4), module checkboxes where the owner section
shows switches, and a save button mid-form with the error line dropped
below it.

Route them through Input, NativeSelect, DateField, and Switch, and give
every form a shared footer that places the error line above the action
row and the action row last (§12). The Switch rows keep a hidden mirror
input so the FormData submit contract is unchanged. Extend the section
tests to hold the DateField primitive and the action-last order in place.
2026-08-09 11:38:17 +02:00
Marc-André Bombeck b24a6eac2c feat(lint): extend spacing-scale to the full off-scale step family on shells
The shell check caught only the bare `5` step on p/px/py/space-y/gap, so
off-scale directional and half-step spacing (`ml-5`, `pl-5`, `gap-3.5`,
`py-2.5`, the `7` step) slipped through on hand-rolled card shells. Widen
it to the whole spacing prefix family (padding, margin, gap, space) and
every banned step — `5`, `7`, and half-steps other than the sanctioned
`1.5`. Height stays out of scope: it is a dimension, not a scale step.

Verified the rule bites by injecting `gap-3.5` onto a real bg-card+border
shell and watching lint flag it, then reverting; the sweep this rule
guards left the tree clean apart from one tooltip shell, now on-scale.
2026-08-09 11:27:29 +02:00
Marc-André Bombeck a959db8679 refactor(ui): route settings shells, actions, and empty states through primitives
Bring the remaining settings and dashboard surfaces onto the shared
anatomy: the API and MCP revoke buttons become the destructive variant
instead of an outline hand-tinted red; the runtime-actions row places
its raw-data setting and status lines above the actions, not under them;
the account section paints its card and header while loading instead of a
lone spinner; the share revoke becomes a right-aligned row action rather
than a full-width alarm strip per link; the recent-workouts tile and the
MCP and notifications empty states compose Card and EmptyState instead of
hand-rolled bg-card shells.
2026-08-09 11:27:18 +02:00
Marc-André Bombeck 7f6eae8425 style(ui): pull off-scale spacing and micro-labels onto the scale
Sweep the spacing rests that sat off the 1/1.5/2/3/4/6/8/10 scale: the
health-score panels and their skeleton, the recommendation ask-Coach
gutter, the onboarding tour footer, the vaccination row, the danger-zone
alert margins, the recovery-codes action wrapper, and the chart-tooltip
tile. Move the last hand-written micro-sizes (coach counters, the
personal-record badge, the score-ring label, the dose-history and
cycle-calendar headers, the mood tag chips) onto the text-2xs token, and
give the documents upload buttons the mobile tap floor their peers set.
2026-08-09 11:27:05 +02:00
Marc-André Bombeck b6332a96d9 refactor(ui): route hand-rolled card headers through the shared header primitives
Move the last hand-rolled tile and section headers onto TileHeader and
SectionHeading so every card speaks one header language: the vorsorge
dashboard tile, the three illness cards, the metric-correlation section,
and the custom-metric list group. The mood-chart title drops to the
primitive semibold weight and its bucket label becomes a TagChip.

Align the in-card sub-headings of the integration cards to the one
sanctioned section-label tier (muted uppercase eyebrow) instead of a
second text-sm font-semibold dialect.

Keep the onboarding and mental-health wizard hero H1s at their
deliberate semibold weight, now marked inline as an intentional
exception so a future heading sweep leaves them alone.
2026-08-09 11:03:43 +02:00
Marc-André Bombeck 844ec396d1 Merge pull request #756 from MBombeck/fix/fable-copy-and-docs
Copy: tighten the metric explainers and settle terminology
2026-08-09 10:54:36 +02:00
Marc-André Bombeck 7aa1fa0174 docs(changelog): note the copy tightenings under Unreleased 2026-08-09 10:32:11 +02:00
Marc-André Bombeck f8197912bb i18n: settle measurement, practitioner, and visit-toast wording
- the single- and bulk-delete flows on the measurement list both say
  Messwert now, instead of switching to Messungen for the bulk case
- the practitioner field on the visit and vaccination forms reads
  Praxis oder Arzt on both, dropping the slash form and the lone feminine
  variant so it matches the practitioner list heading
- the visit saved/updated toasts lose their trailing period to match the
  vaccination toasts they ship beside
2026-08-09 10:31:24 +02:00
Marc-André Bombeck 6ddea30590 i18n: tighten measurements subtitle, mood prognosis, and briefing empty state
- measurements subtitle drops to a single sentence and loses the phrase
  that named Insights twice
- the mood self-rating card takes a short title so it stops wrapping three
  lines and stops sharing the word Einschaetzung with the AI assessment
  beside it; its noPattern and expectation lines move to direct address
- the daily-briefing empty state drops the worked example, leaving the
  setup instruction on its own
2026-08-09 10:28:21 +02:00
Marc-André Bombeck cc36cc501a i18n(insights): trim the six metric explainer bodies to a definition line
The sub-page explainers had grown to four sentences of guideline detail that
pushed the stat strip and chart below the fold; the contract is a one- to
two-sentence definition, with the long form living behind the knowledge
disclosure. Each body now states what the metric is and why it matters.
Also aligns the readiness explainer to the score title across locales
(Bereitschaft / Disposición / Disponibilité), retiring the stray Tagesform.
2026-08-09 10:25:44 +02:00
Marc-André Bombeck 27826ac825 docs: correct stale UI comments on error handling and colour tokens
- mood-insights-sections: the docblock claimed the sections render nothing
  on a failed read; the rest region now surfaces a QueryErrorRow with retry
- band-tokens / coverage-meter: the raw dracula primitives now carry their
  own AA-tuned light overrides, so the no-override claim no longer holds;
  the band still rides the semantic token for concept cohesion
- medication-card-body: drop the pb-2.5 header claim the header no longer sets
- modules-section: the body follows the card gap rhythm, not an mt-4 margin
2026-08-09 10:18:33 +02:00
Marc-André Bombeck 500ed8a7cd Merge pull request #755 from MBombeck/release/v1.37.4
chore(release): v1.37.4 — honest settings copy and doctor-visit polish
2026-08-09 09:43:40 +02:00
Marc-André Bombeck 3a03732578 chore(release): v1.37.4 — honest settings copy and doctor-visit polish 2026-08-09 09:27:27 +02:00
Marc-André Bombeck dbe2aba7eb Merge pull request #754 from MBombeck/feat/arztbesuch-water-polish
Doctor-visit, link-picker, address-book and water-entry polish
2026-08-09 08:41:37 +02:00
Marc-André Bombeck 089c74cf23 feat(links): searchable, grouped entity link picker for visits and shots
The visit form's document / lab / condition link blocks and the
vaccination form's document link were flat lists capped at 25 rows with
no search: 30 lab values arrived undifferentiated and anything past the
cap was unreachable. Replace them with one shared picker — an inline
summary of removable chips over an add button, and a sheet that searches,
groups and multi-selects. Lab results gather under their panel and sample
date with a select-all per group, documents gather by month, illnesses
stay flat. The picker raises only the fetch limit; the server link cap
stays authoritative.
2026-08-09 07:01:15 +02:00
Marc-André Bombeck 40e53b14d6 feat(practitioners): search and group the address book by specialty
Search now covers the specialty column alongside name and practice, so a
field name like "Zahnmedizin" finds the practice even when the name and
practice hold nothing of the sort. The same OR reaches the visit form's
practitioner picker, which now shows the specialty beside the practice so
a specialty hit is legible. The list groups its rows under their
specialty, sorted alphabetically with the unspecified rows gathered into
one group at the end; when nothing carries a specialty the headings stay
suppressed and the list reads flat as before.
2026-08-09 06:53:57 +02:00
Marc-André Bombeck 9aefce1625 fix(checkups): offer the record-a-visit action only for real visits
The file-a-visit affordance painted on every checkup reminder, including
the self-measurement ones (weigh-in, blood pressure, a screening
check-in) where there is no appointment and 'you went' is never a
reading. Gate both the card and the dense-list branch on the same
free-text predicate the mark-done action already uses: a reminder with a
measurement type is satisfied in the app, a free-text reminder stands for
a practice visit. The server states the same boundary in resolve.ts.
2026-08-09 06:48:46 +02:00
Marc-André Bombeck 4335b38e02 feat(nutrients): remove in-app water logging, keep the sync path
Manual water entry is gone from the app: the water item on the capture
picker, the dashboard quick-add menu and the hydration card's add button
are removed, and the manual quick-add sheet is deleted. Water that syncs
in through Apple Health still arrives and still shows on the hydration
card with its daily total, history and reference line.

The POST /api/nutrients/water endpoint and the batch sync path stay
untouched. The nutrients page's module-enable error, which had borrowed
a water-quick-add string, gets its own key across all six locales.
Input-only water keys (nav.capture.water*, nutrients.hydration.quickAdd*)
are removed.
2026-08-09 06:46:28 +02:00
Marc-André Bombeck 18e9a80ea9 Merge pull request #753 from MBombeck/fix/honest-errors-and-security-copy
Honest read-failure states and MCP scope-note correction
2026-08-09 06:30:12 +02:00
Marc-André Bombeck 9ae42ae33f chore(bundle): raise the aggregate cap for the honest-error-state code
Adding recoverable read-failure handling to thirteen surfaces and the MCP and
managed-record copy rewrites across six locales lifts the whole-build client
total to 3404 KB gz. Every per-route ceiling is still met; the aggregate cap
moves 3352 to 3428 with the same margin.
2026-08-09 06:14:43 +02:00
Marc-André Bombeck 73b82f444e test: use render thunks in the read-error family suites for the jsx-key rule 2026-08-09 04:37:03 +02:00
Marc-André Bombeck edaa5bf424 style: wrap a long assertion in the api-section error test 2026-08-09 04:34:18 +02:00
Marc-André Bombeck c8500dd869 docs(changelog): record the honest-error and MCP scope-note fixes under Unreleased 2026-08-09 04:33:35 +02:00
Marc-André Bombeck ba42354733 fix(admin): replace hand-rolled read-error boxes with the shared primitive
Eight admin surfaces rendered a failed read as their own destructive-
tinted box, and most offered no way to recover. Sweep them onto the shared
QueryErrorRow with retry so the console uses one error form (§13). The
statically renderable sections were watched fail first against the
hand-rolled boxes.
2026-08-09 04:32:54 +02:00
Marc-André Bombeck f6a0ee4623 fix(checkups): use the shared query-error primitive on the Vorsorge list
The section carried a bespoke muted error row with its own retry button —
the exact drift QueryErrorRow was made to absorb. Swap it for the shared
primitive so the failure reads as foreground content. Test watched the
bespoke row first.
2026-08-09 04:28:18 +02:00
Marc-André Bombeck 44582008e9 fix(settings): make settings read failures foreground and recoverable
A family of settings surfaces rendered a failed read as a bare
text-destructive line with no way to recover: the security sessions,
trusted-devices and activity cards, the coach memory and reminders
sections, the about-me section, and the document link/share pickers. Swap
each to the shared QueryErrorRow primitive with a retry control. The suite
covering the statically renderable members was watched fail first against
the bare lines; the two portaled pickers take the same swap.
2026-08-09 04:26:46 +02:00
Marc-André Bombeck f63fdb373e fix(cycle): use the shared query-error primitives on failed cycle reads
The cycle tabs rendered a bespoke error row in muted text, wrapped in a
bare card. Replace it with the shared primitives: QueryErrorCard on the
standalone prediction/insights/settings tabs, and a borderless
QueryErrorRow inside the calendar card so the failure reads as foreground
content with retry rather than muted meta. Test watched the muted row
first.
2026-08-09 04:20:55 +02:00
Marc-André Bombeck 6485aae787 fix(insights): surface mood-insights read failures instead of silent degradation
The mood-insights regions returned nothing on a failed read by documented
intent, degrading to the line chart. Enforce the honest-error standard
here too: on error the main region paints a QueryErrorRow with retry, once,
mirroring how the loading skeleton is scoped to that one region so the
three regions do not stack identical rows. Test watched the silent empty
first.
2026-08-09 04:15:12 +02:00
Marc-André Bombeck 1229d54d30 fix(insights): recoverable read failures on the ECG detail and list page
The ECG detail rendered a read failure as a muted, non-recoverable line;
the routed list page had no error branch at all, leaving the shell
heading over an empty body that read the same as loading. The detail now
paints a QueryErrorCard with retry (an alert is content, not muted meta),
and the page shows the same instead of an empty shell. The overview teaser
still unmounts silently, which is right for the overview. Tests watched
each fail first.
2026-08-09 04:13:46 +02:00
Marc-André Bombeck 22d5c01a68 fix(settings): surface AI settings-read failures instead of a default form
The three AI configuration reads each returned null on a non-OK response,
so a failed read painted the default provider form as if the account were
configured that way. Throw on a non-OK response so the query reports its
error, and render a QueryErrorCard with retry when any read fails. Test
watched the misleading form render first, then pass on the honest error.
2026-08-09 04:11:08 +02:00
Marc-André Bombeck 51c40c61d9 fix(dashboard): show a read failure on the Vorsorge tile, not an empty state
The tile already read the query's error flag but never branched on it, so
a failed reminder read fell through to "no upcoming checkup reminders" —
a missed preventive-care nudge hiding behind an honest-looking empty
state. Add a QueryErrorRow with retry before the empty check. Test
watched fail first against the fall-through.
2026-08-09 04:08:57 +02:00
Marc-André Bombeck 48e4882400 fix(settings): show read failures on the MCP connector lists, not empty states
The connected-assistants and connector-token queries had no error or
loading branch, so a failed read rendered "no connected assistants" or
"no active tokens" on this security surface. Gate both lists with
QueryErrorCard and retry, a skeleton while loading. Test watched fail
first against the old empty-state fall-through.
2026-08-09 04:07:10 +02:00
Marc-André Bombeck ab2c5cb2aa fix(settings): show a read failure on the API-token list, not an empty state
Same fall-through as the share-link list on another security surface: the
token query had no error or loading branch, so a failed read rendered
"no active tokens". Gate the list on the query state with QueryErrorCard
and retry, a skeleton while loading. Test watched fail first against the
old empty-state fall-through.
2026-08-09 04:05:35 +02:00
Marc-André Bombeck 53a463f11b fix(settings): show a read failure on the share-link list, not an empty state
The share-link query had no error or loading handling, so a failed read
collapsed to an empty list and rendered the "no active share links"
copy — on a clinical sharing surface a load failure was indistinguishable
from "you have shared nothing". Gate the list on the query state:
QueryErrorCard with retry on failure, a skeleton while loading, the lists
only once the data is in. The added test was watched fail first against
the old fall-through before this fix made it pass.
2026-08-09 04:03:09 +02:00
Marc-André Bombeck 6e3965146c fix(settings): honest address, greeting comma, and managed-record error classes
Three small copy corrections that share the locale bundles:
- Resolve the formal-address outliers on the owner sharing and report
  scopes to the informal register the rest of those surfaces use.
- Add the direct-address comma to the personalized dashboard greeting.
- Split the managed-record form error: a client-side validation failure
  no longer surfaces as a network error, and a failed save gets its own
  line.
2026-08-09 03:59:34 +02:00
Marc-André Bombeck 6d67e84cea fix(dashboard): localize the respiratory-rate unit label
The respiratory-rate tile hard-coded the English unit while the metric
sub-page already reads the localized string. Point the tile at the same
key so every locale shows its own unit.
2026-08-09 03:59:19 +02:00
Marc-André Bombeck 338e9bc818 fix(settings): render AI consent copy as foreground content
The central-codex and auto-read consent notes are safety copy the user
has to read before enabling a data-sharing path, but both rendered as
muted extra-small meta. Promote them to foreground text-sm and keep only
the decorative icon muted.
2026-08-09 03:59:19 +02:00
Marc-André Bombeck b46550d9a2 fix(settings): correct the MCP token scope note to match the write toggle
The note above the write toggle claimed tokens are read-only in every
case, which the toggle directly below it contradicts by minting a
read_write scope. Rewrite it to state the real model: read-only by
default, write opt-in per token, never admin. Resolve the pronoun that
read as a formal address, and promote both scope notes to foreground so
this security copy no longer renders as muted meta.
2026-08-09 03:54:23 +02:00
Marc-André Bombeck 1c7efd9b9a Merge pull request #752 from MBombeck/release/v1.37.3
chore(release): v1.37.3 — the immunization record
2026-08-09 02:34:33 +02:00
Marc-André Bombeck 8d5948ceb3 chore(release): v1.37.3 — the immunization record 2026-08-09 01:55:42 +02:00
Marc-André Bombeck 2f7f522225 Merge pull request #751 from MBombeck/feat/vaccinations-phase-2
Vaccinations: the immunization record, visible and reachable
2026-08-09 01:14:58 +02:00
Marc-André Bombeck 34cd41a359 fix(a11y): name the catalogue and practitioner combobox triggers
A role=combobox button is not named from its content, so the visible
placeholder text left both the vaccine-catalogue trigger and the shared
practitioner trigger without an accessible name, and the wrapping field label
pointed at an id the button did not carry. Name each from its field label. The
practitioner trigger is shared, so the visit form gains the same name.

Also settle CSS animations before the accessibility scan and poll the reminder
reads in the booster flow: the scan otherwise raced the capture sheet's fade
and measured a half-opacity blend as a contrast failure, and the flow read the
reminder list before the mint and the re-anchor had propagated. Both wait for
the settled state rather than relaxing any assertion.
2026-08-09 00:50:35 +02:00
Marc-André Bombeck 77ba829fcf test(sharing): drive the booster admission through its owned effect
The booster route was admitted into the MANAGE matrix but had no driver, so
the strict-driver and real-effect inventories stayed one short of the admission
count and the completeness guards failed. Register the write-effect driver that
mints the reminder against a tetanus dose and asserts the delegated WRITE actor
on the audit row, matching every other admitted write.
2026-08-09 00:28:32 +02:00
Marc-André Bombeck e5072ba99e fix(reminders): bound a rolling reminder's re-anchor by the notify-hour slot's own day
A rolling reminder at the ten-year maximum interval lost its next due when
the satisfy instant fell in the late-UTC evening. The next-occurrence search
bounded the single deterministic rolling slot by the end of the anchor's UTC
day, but the applied notify-hour slot lands on the following UTC day whenever
the anchor sits in the evening (the local morning is the next calendar day in
a positive-offset zone). The anchor-day ceiling was then a day short and
clipped the very slot it meant to admit, so logging the next dose set nextDueAt
to null and the booster silently disappeared. Key the ceiling off the applied
slot instant instead; endsOn stays enforced inside expandRolling.
2026-08-09 00:21:39 +02:00
Marc-André Bombeck 4766828555 fix(reminders): keep a maximum-interval rolling reminder's next due after satisfy
A rolling reminder at the engine's ten-year maximum interval lost its next
due date the moment its cadence was satisfied. The rolling branch of
nextOccurrenceAfter bounded its search by the 10-year anti-spin hardCap, and
a satisfied reminder computes its next slot with after === lastSatisfiedAt,
so the single deterministic slot lands exactly after + 3650 days — equal to
the hardCap to the millisecond. The notify-hour slot then spilled a few hours
past the raw boundary and was clipped to nothing, leaving nextDueAt null.

The rolling slot is one deterministic instant, not an open-ended walk, so the
anti-spin cap must never gate it. Bound the rolling search by that slot's own
day instead; endsOn stays enforced inside expandRolling, so a course-window
reminder still self-expires.

This surfaced on a ten-year tetanus booster: logging the next dose silently
dropped the reminder instead of rolling it forward a decade.
2026-08-08 23:54:44 +02:00
Marc-André Bombeck 9f2cbcb32b test(sharing): count the booster handler in the MANAGE matrix
The booster mint adds one mutating handler, so the admitted inventory and its
strict-driver and effect mirrors are 75, not 74. The registry and the frozen
route count already moved; these three assertions had not.
2026-08-08 23:46:33 +02:00
Marc-André Bombeck 5aa03674a5 test(e2e): click the always-present vaccination add button
The capture helper branched on an instant isVisible() read to pick between the
header add and the empty-state add. Right after a navigation that read races the
client render and loses, so it fell through to the empty-state button, which is
gone once a record exists, and the click timed out. The header add renders in
both states; clicking it directly lets click() auto-wait for hydration.
2026-08-08 23:23:15 +02:00
Marc-André Bombeck 999206767f Merge remote-tracking branch 'origin/main' into feat/vaccinations-phase-2 2026-08-08 23:01:36 +02:00
Marc-André Bombeck 3ad8332e66 test(vaccinations): prove the managed-profile and scoped-grant record paths
Two record-scope properties through the real routes and a real Postgres. A
Guardian standing inside a managed profile writes a dose against the resolved
record — the profile's rows, never the Guardian's own — and reads it straight
back. A delegate holding a profile READ grant on an ordinary record lists and
reads the doses but is refused the PATCH with a 403, the escalation stopped at
the manage check before the row is looked up, and the row is left untouched.
2026-08-08 23:00:39 +02:00
Marc-André Bombeck a6a65719eb test(vaccinations): cover the immunization log end to end
Five Playwright flows over the built app, each asserting stable data-slot
attributes rather than viewport text: transcribe a catalogue pick with a lot
into its antigen group, a combination dose rendering under each of its three
component groups, the booster prompt minting a Vorsorge reminder that shows on
checkups and moves its due date when the next dose is logged, the module-off
redirect with the nav entry gone, and an axe pass over the list and the form.

The catalogue option gains a data-catalog-slug hook so a flow can pick an exact
antigen deterministically. The spec runs in a single project and serial, and
clears its own rows before each test, so a grouped verdict counts only what the
test wrote.
2026-08-08 23:00:29 +02:00
Marc-André Bombeck 0ecaa6beb9 Merge pull request #750 from MBombeck/fix/polish-batch-a
Polish: mood slider, form focus, settings order, sharing scope and expiry
2026-08-08 22:48:05 +02:00
Marc-André Bombeck 958f3bc50a test(vaccinations): reconcile the structural guards with the new surfaces
- freeze the booster-mint and upload-suggestion routes into the sharing
  surface guard with their why sentences; delegable-write and mutation
  inventories move by the two routes they add
- inventory the two new routes as module-exempt data routes (SURFACE-gated,
  like the medications posture)
- give the booster-plan audit action its own owner-facing verb in six locales
- register the dose delete as a destructive control; route the vaccination
  success toasts through the outcome module
- move the report leaf counts (structured 15→16, all 92→93) and the history
  group count in the panel; regenerate the OpenAPI selection bound
- seed the immunization rows in the export-route mock so the aggregator no
  longer throws for a fully-selected report
2026-08-08 21:43:28 +02:00
Marc-André Bombeck 4db70d3eb1 feat(vaccinations): name the catalogue in six locales
- the ~35 antigen and combination display names, medical orthography per
  locale, umlauts intact end to end; disease and antigen names only, never a
  trade name
- the three clinical proper nouns whose written form is identical across
  locales (Hib, Hepatitis A/B in Spanish) are recorded as legitimate matches
2026-08-08 21:24:00 +02:00
Marc-André Bombeck 2da0159577 feat(vaccinations): add the immunization history to the doctor report
- IMMUNIZATIONS report leaf in the history group, gated both ways: the
  vaccinations module and the leaf selection each exclude independently
  (WR-7 seen red on the selection gate, reverted by content hash)
- collector loads the whole live history (reference data, not windowed, like
  allergies) with server-resolved series positions; the PDF renders a compact
  per-dose table — date, vaccine, dose, lot — with no due-status or gap analysis
- added to the default template so a new report offers it; stored selections
  and frozen share links never widen
- leaf label and section copy in six locales
2026-08-08 21:21:12 +02:00
Marc-André Bombeck f6a4acf779 test(sharing): follow the invite form's new scope default and one-line copy
The access options render as a row with an info affordance rather than a
wrapping label, the scope question preselects nothing, and the write and
manage detail moved behind the (i). Point the consent-copy and form-reset
guards at the shipped bundle for the detail text and at the unset scope
default.
2026-08-08 21:20:57 +02:00
Marc-André Bombeck e0692efba8 fix(sharing): widen the grant db slice for the expired-row sweep
The pre-create sweep in inviteGrant writes an audit row when it closes a
lapsed grant, so the transaction slice it accepts now covers auditLog
alongside accountGrant. Point the module and route test fakes at the
same shape: they stub updateMany to close nothing, so the audit branch
stays unreached in the unit fixtures.
2026-08-08 21:14:23 +02:00
Marc-André Bombeck 9b58394724 feat(vaccinations): link documents to doses, with the upload suggestion
- from the record: a document link picker on the capture form, gated on the
  documents module (blanked when off, never post-filtered)
- from the upload: a VACCINATION scan offers to file against a dose recorded
  within the shared ±7-day window; a single candidate pre-selects, two offer a
  picker with nothing pre-selected (WR-8 seen red on the pre-select rule,
  reverted by content hash), zero shows nothing, and it never blocks the upload
- the suggestion rule reuses the visit moment's window constant rather than
  forking it; it registers with the shared filing module when that lands
- suggestion and link copy in six locales
2026-08-08 21:11:21 +02:00
Marc-André Bombeck ae2b82b1d9 docs: note the polish fixes under Unreleased 2026-08-08 21:10:26 +02:00
Marc-André Bombeck ba4ec67812 fix(sharing): shorten the scope option copy to one line each
The write and manage levels each carried a paragraph of capability text
under their label, stacking into walls of text on the invite form. Cut
each to a single consent sentence inline and move the full enumeration
behind the info affordance at the option-heading height — what exactly
write may add, and the fence manage does not reach. The consent line
stays inline where it has to be read; the detail is one tap away for
anyone who wants the whole list. Six locales.
2026-08-08 21:09:52 +02:00
Marc-André Bombeck 97e75fd098 fix(sharing): stop preselecting a scope when inviting someone
The scope question defaulted to whole record, which reads as the form
nudging the choice. Preselect neither option: an untouched fieldset now
blocks the form with a quiet hint instead of falling through to a
whole-record grant. The wire contract is unchanged — scope-absent still
means the entire record on the server, so the unset state deliberately
does not omit scope, it blocks the client until the owner picks. The
empty-selection and manage floors stay fail-closed as before.
2026-08-08 21:05:10 +02:00
Marc-André Bombeck de83954a7f fix(sharing): let an expired grant be re-granted instead of colliding
The live-pair uniqueness is a partial index (WHERE revoked_at IS NULL),
which cannot read the clock: an expired but never-revoked grant kept
occupying the slot, so re-inviting the same person after expiry always
failed as a duplicate though they had no access. Close the lapsed row at
the moment of re-invite — conditionally, the expiry state in the WHERE —
so revocation still never deletes and the fresh invitation mints its row.
The revoker is stamped GRANTOR because the paired revoked-by check
requires both columns set and the enum has no expiry member. An audit row
records the close. Proven against the real index: the guard was watched
fail with a duplicate before the fix landed.
2026-08-08 21:01:50 +02:00
Marc-André Bombeck b5ce44628a feat(vaccinations): mint the booster reminder a logged dose suggests
- rung 2: a prefilled, user-confirmed, editable, declinable prompt writes an
  ordinary VORSORGE reminder keyed on the dose's primary antigen; the
  published origin enum and reminder DTO are unchanged
- idempotent by antigen — a second confirmation re-anchors the existing
  reminder rather than minting a second (WR-9 seen red on the reminder count,
  reverted by content hash)
- rolling day cadence so logging the next dose re-anchors the due date through
  the Phase 1 satisfy matcher; the whole loop proven through real routes
- booster prompt copy in six locales, plural-aware
2026-08-08 21:01:25 +02:00
Marc-André Bombeck ee561eaa23 fix(settings): move password reset to the end of the security section
Security now reads authenticator, then security keys, then passkeys,
then the password — the password card was mounted first. Keep it outside
the factor-status conditional so a stalled MFA read never takes it down;
it just renders last instead of first. A source-order guard pins the
sequence, since this class of ordering regression is easy to miss.
2026-08-08 20:57:40 +02:00
Marc-André Bombeck e344ebb781 fix(settings): drop the score pillar group headings for a flat list
The score-composition settings grouped its topics under domain headings
(Heart and metabolism, Activity, Sleep, Body shape, Wellbeing). Remove
them and list the individual topics one under another with hairline
dividers, the way the health profile lists its facts. Each row keeps its
domain data attribute, so the flattening preserves the registry order and
tests still address a pillar by its domain. The now-orphaned domain-label
map and its six-locale strings go with it.
2026-08-08 20:56:50 +02:00
Marc-André Bombeck 955ef6c6b6 fix(ui): keep the sheet scrollbar off the right-aligned labels
The desktop dialog body was the lone scroll port and carried no
horizontal padding of its own — the vertical scrollbar rendered flush
against its right edge, exactly where a slider's right-aligned high
anchor sits, so an overlay scrollbar painted over the last characters of
labels like the mood endpoints. Reclaim a 12 px gutter from the dialog's
own padding (-mr-3 pr-3): the scrollbar now sits beside the text, content
alignment unchanged. Universal to every ResponsiveSheet dialog.
2026-08-08 20:54:25 +02:00
Marc-André Bombeck 2e5061337b fix(ui): give date and time fields the standard focus ring
DateField and TimeField carried a divergent focus vocabulary — a hard
`ring-2 ring-offset-2` that painted a 4 px ring outside the field's
border box, so the highlight was visibly wider than the div and shifted
on focus. Pull both onto the Input vocabulary: a soft 3 px ring hugging
the box, no offset. Also match Input's `text-base md:text-sm`, so a
sub-16 px input no longer triggers iOS Safari's focus auto-zoom. Every
DateField and TimeField in the app inherits the fix.
2026-08-08 20:53:35 +02:00
Marc-André Bombeck 271e6f5db6 fix(mood): make the slider clear affordance an icon, not a text label
The clear-action button sat as muted text beside the value, so a set
slider read as one phrase — the number fused with the word next to it
(a value of 4 next to "leeren" showed as "4 leeren"). Replace it with
an icon-only X that carries the same label as its accessible name, so
the value readout stays the bare number in every locale at once.
2026-08-08 20:52:20 +02:00
Marc-André Bombeck f540298521 feat(vaccinations): render the catalogue's sourced schedule text
- compose rung-1 sentences from the seed's series length, booster interval and
  category over a handful of i18n templates, with the per-entry source as a
  verbatim footnote; nothing personal, no age or history conditioning
- surface it in the picker's chosen-entry detail and behind the antigen group
  header's info affordance
- schedule templates in six locales, plural-aware
2026-08-08 20:45:46 +02:00
Marc-André Bombeck ff72917833 feat(vaccinations): add the dose capture and edit form
- one sheet for create and edit, saving with a date and one identity arm
  (catalogue pick or free text); nothing else can block the save
- catalogue picker searches localised names and generic synonyms over the
  static antigen list, never overwriting the free-text arm
- optional dose/series, lot, site, practice combobox, visit suggestion and
  note, all reusing the encounter-form primitives
- write hooks fan out through the dose dependent-keys and the reminder reads
- form/site/sheet copy in six locales
2026-08-08 20:40:40 +02:00
Marc-André Bombeck 1d07204293 feat(vaccinations): group the log by component antigen with resolved series
- read the immunization log through the query-key factory, unwrapping the
  envelope; the series arrive resolved per component antigen from the DTO
- render one group per antigen, a combined dose appearing in each of its
  component groups with that component's own position; free-text and dead-slug
  rows fold under their verbatim name
- neutral cards, meta in muted, no due status on the page
- add the dose-list dependent-keys bundle, evicting the preventive-care root
  alongside the dose list so a satisfied booster never lingers on checkups
- series/lot/error copy in six locales
2026-08-08 20:32:05 +02:00
Marc-André Bombeck eefc151617 feat(vaccinations): add the immunization log route, nav entry and shared-record family
- register /vaccinations in the clinical nav spine, module-gated on
  vaccinations (default-on) and part of the shared record
- join /vaccinations to the profile shared-record route family so a scoped
  profile grant can present the page it is allowed to read
- add the page shell: authenticated, module-gated, with the standard
  module-off redirect the medications surface uses
- add the nav label and the surface title/subtitle/empty copy in six locales
2026-08-08 20:24:42 +02:00
Marc-André Bombeck 11a6bc40c0 Merge pull request #748 from MBombeck/feat/vaccinations-phase-1
Vaccinations: the record, the catalogue and their carriers
2026-08-08 19:52:52 +02:00
Marc-André Bombeck 4f2dd51390 Merge remote-tracking branch 'origin/main' into feat/vaccinations-phase-1 2026-08-08 19:35:18 +02:00
Marc-André Bombeck c32b40b23c Merge pull request #749 from MBombeck/release/v1.37.2
Release v1.37.2
2026-08-08 19:04:20 +02:00
Marc-André Bombeck 594898d350 Anchor the document visit-suggestion on a full instant
The suggestion anchored on the document's own date, which the DTO carries
as a date only. The suggest endpoint takes a full instant, so every
document asked the question as `2025-10-14` and got 422 back; the field
then rendered nothing and no document ever offered the visit its date
falls near. Lift the date to noon UTC before asking, the shape the two
lab moments already send.

The e2e that should have caught it never authenticated: the visits spec
carried no storage state, so its `page` redirected to login and its
`request` reads answered 401. It also asserts a global verdict — one
visit in the document's window — so clear the account's visits before
each test, run the file serially, and keep it to one project, since two
projects mutating the shared account would leave two candidates in the
window.

The accessibility mock lagged the same feature: the detail sheet reads
`encounterLinks` off the document and the mock omitted it, so the sheet
threw before it painted. Add the field the server always sends.
2026-08-08 18:46:55 +02:00
Marc-André Bombeck 9456b18497 Carry the owner's full name through the account-access round trip test
The account payload gained a full-name field; this integration test
built its expected entries without it, so the exact-match assertions
disagreed with the response. The fixtures name the field now, null for
an owner who set no full name.
2026-08-08 18:02:21 +02:00
Marc-André Bombeck 08d3cd2c31 Split the ECG cap and one provenance entry off their label maps
The /insights overview crept a kilobyte over its ceiling: the ECG
teaser imported its overview cap from the classification module, which
dragged that module's label map and helpers into the eager page, and
the Health Score card pulled the whole metric-provenance map for its
one citation. The cap now lives in a value-only module and the single
provenance entry is split out, so the overview imports the bare number
and citation it renders. Both routes are back under budget. The
aggregate ceiling rises to hold the six-locale copy the new encounter,
mood-context, mood-prognosis and practitioner surfaces added, which the
whole-build sum counts independently and no single route downloads.
2026-08-08 17:56:40 +02:00
Marc-André Bombeck e1a4b7631c Merge branch 'main' into feat/vaccinations-phase-1
The visit stage's second half landed while this was in flight and both
touched the same three places. Resolved as one set: the link facade
carries the reverse document-to-visit direction and the new dose pair
side by side, the sharing literals hold both sets of admissions with the
count re-added on top, and the language bundles take the shorter module
description the trunk settled on.
2026-08-08 17:07:58 +02:00
Marc-André Bombeck fa402f2f72 test(vaccinations): drive the four new admissions through the manage matrix
A frozen tag is a promise about code; the matrix is the one that proves
behaviour. Each of the four vaccination mutations now has its own
driver: a manager with a live grant changes the owner's record and the
audit row names both people, the same person under a lesser grant is
refused with nothing moved, and a caller who was never granted anything
gets the same refusal.
2026-08-08 16:47:50 +02:00
Marc-André Bombeck 0a9917a09d docs(changelog): drop a stray blank line 2026-08-08 16:22:59 +02:00
Marc-André Bombeck 102845c64a chore(release): v1.37.2 — the mood forecast, doctor visits, and a settings polish 2026-08-08 16:21:39 +02:00
Marc-André Bombeck 8347c39319 Merge pull request #746 from MBombeck/fix/settings-ekg-polish
Settings tree, list rhythm and the ECG surface
2026-08-08 16:18:49 +02:00
Marc-André Bombeck 4c2dfa57b4 Merge remote-tracking branch 'origin/main' into fix/settings-ekg-polish 2026-08-08 16:17:40 +02:00
Marc-André Bombeck 3d6190568d Merge pull request #747 from MBombeck/feat/encounter-phase-2
Visits become reachable: capture, incidental linking, and the report leaf
2026-08-08 16:12:54 +02:00
Marc-André Bombeck f28c6df861 Merge branch 'main' into feat/encounter-phase-2 2026-08-08 16:11:50 +02:00
Marc-André Bombeck 57cc52dfe2 Merge pull request #744 from MBombeck/feat/mood-prognosis
The mood module can say what a day would have looked like on your own past patterns
2026-08-08 16:09:59 +02:00
Marc-André Bombeck 650ac6189c docs: note the owner full name and the ECG teaser cap under Unreleased 2026-08-08 16:07:34 +02:00
Marc-André Bombeck e33700c7a9 feat(sharing): name a record's owner in full to whoever they share with
The switcher and the banner named a shared record's owner by their greeting
name — the value they typed at onboarding for "how should HealthLog address
you". When an owner has set a full name, that is what a delegate should see:
entering somebody's record, you read whose it is by who they are.

- the account-access resolver publishes the owner's `fullName` alongside the
  greeting name and the username
- `accountLabel` prefers fullName, then displayName, then username. Optional
  on the argument so the grant-view and actor shapes that never carried it
  keep the old two-field behaviour untouched
- the closed presentation schema carries `fullName` and its parity matcher
  compares it, so the two published views of the active record cannot name
  the same owner differently
- the OpenAPI contract regenerates with the additive field

This deliberately discloses the owner's full name to every delegate, read-only
included — it was patient-identity data behind a MANAGE-gated export until now.
That is the intended behaviour, documented at `accountLabel` so it is not
mistaken for a leak and tightened back. The resolver, the schema parity, the
label fallback and a read-only delegate's banner are each pinned by a test.
2026-08-08 16:07:25 +02:00
Marc-André Bombeck 73ea1b03f3 fix(scripts): drop the retired research-mode columns from the demo rebuild
The demo edge01 rebuild copies the users table by an explicit column list,
and three of the names in it — research_mode_enabled and its two
acknowledgment stamps — were dropped from the schema when Research Mode was
retired. The COPY and its matching SELECT both targeted columns that no
longer exist, so the rebuild would fail on the first users row. Removed from
both lists, which stay aligned.
2026-08-08 16:07:06 +02:00
Marc-André Bombeck 8f3e4b6387 fix(insights): cap the ECG teaser, never the ECG page
The five-strip cap belonged on the overview teaser — a glance on /insights —
not on the surface a user opens to read their history. It was living in the
shared EcgSection, which the dedicated /insights/ecg page reuses, so an
account with many recordings could only ever reach the newest five there and
the older strips became unreachable with no pagination behind them.

The cap is a prop now. The teaser passes ECG_OVERVIEW_LIMIT; the page passes
nothing and lists every recording. The constant lives in the React-free
classification module so the overview page can pass it without pulling the
dynamically-loaded ECG component into its bundle.
2026-08-08 16:06:57 +02:00
Marc-André Bombeck 5d6bc73cdc test(encounters): guard the batched link redaction on the visit list
The per-family withholding of a link's label and date from a scoped delegate
was proven on the detail read and not on the list read. The two resolve links
through different functions — the list through the batched loadEncounterLinksForMany,
added when links moved onto the list — and a batched read that dropped the
redaction would leak a lab analyte and its date to a delegate the single read
withholds them from, with no assertion on the detail path to notice.

Three legs, mirroring the detail coverage against the list route: an
entire-record delegate sees every name, a profile-only delegate sees the shape
of all three links and the name of none, and a profile-plus-labs delegate sees
the lab name and neither of the other two. The entire-record leg is the control
that stops the redaction assertion passing against a read that redacts
unconditionally.
2026-08-08 15:54:19 +02:00
Marc-André Bombeck ab40fe6a6e Merge branch 'main' into feat/vaccinations-phase-1 2026-08-08 15:51:57 +02:00
Marc-André Bombeck 0a543abd18 refactor(vaccinations): drop the dependent-keys bundle nothing consumes yet
The dead-code gate is right: a bundle with no caller is dead code. The
capture surface brings it back with the mutation that needs it, and the
key module says what that bundle will have to evict.
2026-08-08 15:51:54 +02:00
Marc-André Bombeck 0bf3f5c8d9 Merge remote-tracking branch 'origin/main' into feat/mood-prognosis 2026-08-08 15:41:13 +02:00
Marc-André Bombeck 75c43c74bc docs(mood): state the validation's real leak boundary, drop the unused weekday floor, correct two comments
Four honesty fixes with no behaviour change to the math.

The validation header claimed more than it proves. The ridge FIT is
out-of-sample and no training fold sees ahead — that holds. But feature
SELECTION and per-user standardisation both run over the whole window
before the split, a small documented optimism (measured at about one
part in sixty on the error). The header now says exactly what is and is
not leak-free, and says to nest the screening if the feature set ever
grows or the optimism is ever measured larger.

The per-weekday observation floor had no consumer: no weekday board is
built on this fit, the forecast only publishes seasonalUnlocked and
leaves the weekday view to the insights page, which has its own floors.
Removed rather than left as a number nothing reads, with a note to bring
it back alongside such a board.

Two comments were wrong and are now true: the route's parameter is
declared for the exported type, not to steer a method check the wrapper
resolves from the Next.js request with a GET fallback; and the label
surface imports the key parser from feature-keys.ts, not features.ts.

And the write-surface guard now states its own structural blind spot,
the way the session-surface guard does: the wipe path deletes this table
through a dynamically-resolved delegate the literal matcher cannot see,
which is why that deletion is correctly not counted as a writer.

The Coach staleness fixture moves above the forecast floor, because the
read path now refuses below it: a one-entry account correctly gets an
absence rather than the present forecast that case exercises.
2026-08-08 15:30:38 +02:00
Marc-André Bombeck d58edc5deb fix(mood): floor the fit on complete rows, not only on rated days
The ladder gate counts days carrying a rating. But a day missing one of
the fit's selected features is dropped rather than imputed, so a
sparse-context account can clear thirty rated days and be fitted on far
fewer complete rows — a forecast "built from twenty days" past a floor
meant to say thirty. n beside the value and a wide band on a small fit
keep it from being dishonest, but the floor should still hold.

The number of complete rows the fit actually used now has to clear the
same threshold as the rated-day count; below it the account gets the
absence shape, and the read path then reports "not enough of a pattern
yet" rather than a value resting on a handful of days.

Watched red with a fixture of forty rated days carrying the driving
feature on only the twenty-five most recent — enough to screen the
feature in and to score the recent days, so the refusal is about the
complete-row count and nothing else. Before the floor it wrote n=25.
2026-08-08 15:30:20 +02:00
Marc-André Bombeck 9a47b4db49 fix(mood): refuse a forecast below the data floor on the read path, not only in the job
The job clears a below-floor account's rows nightly, but the read path
trusted whatever row was on disk between passes. So for up to a day
after an account deleted entries back under the floor, GET
/api/mood/prognosis returned present:true with a value the account no
longer had the data to support — and worse, under a stage the row
implied ("insufficient" / "learning") that is not in the published enum,
which fails a strict client decode of the whole payload.

The read path now re-reads the ladder and returns the absence shape
below the floor, exactly as the job would, so the two agree and no
out-of-enum stage can reach the wire. The present type's stage is
narrowed to the three rungs that carry a value, so the compiler enforces
it too.

The integration case that missed this ran the job before reading, which
is precisely why it was silent. The new case deletes entries back into
the learning band and reads WITHOUT running the job, with the row still
proven on disk, and asserts present:false with no stage. Watched red:
before the fix it returned present:true with a predicted value.
2026-08-08 15:30:00 +02:00
Marc-André Bombeck dd04931c9d chore(query-keys): restore the visit invalidation bundle with its consumers
The bundle landed a release before the surfaces that read it and was removed
on trunk as dead. Both mutation hooks in this branch use it, and the merge took
trunk's deletion, so it comes back here together with the writes that need it.
The comment now names its consumers, so the next dead-code sweep can see them
without reading two files.
2026-08-08 15:22:13 +02:00
Marc-André Bombeck 65a3d91b6e docs: record the settings and ECG polish under Unreleased
The mobile-consistency spec follows the change-password card to Security —
same claim, new address.
2026-08-08 15:17:05 +02:00
Marc-André Bombeck 95988ee843 fix(nav): drop the access-level line from a record-switcher entry
Three lines in a 240 px menu: the name, the access level, the kind of
record. The middle one truncated more often than it read, and it is what
the warning banner states in full once you are inside the record, where it
governs what the page lets you do. Two lines left, and the level stays on
the row as `data-access-level` for the browser journeys.

The switcher's own "Read only" / "Can add entries" strings had no other
reader and leave all six bundles.
2026-08-08 15:17:05 +02:00
Marc-André Bombeck dc56f70961 fix(insights): give an ECG recording its own page and quiet the list
The ECG surface opened with three lines of muted text saying what HealthLog
does not do, before a single strip. Two of them said the same thing — one
from the page's explainer slot, one hand-rolled beneath it — and the third
repeated it under the list. The device attribution on the recording itself
already carries that claim where it means something, so the three go and the
page opens on the recordings.

- the device's verdict rides the timestamp as a tag instead of taking a line
  of its own beneath it. It qualifies the recording; it is not a second fact
- a recording is a route now, `/insights/ecg/[id]`, with the back link ABOVE
  the heading exactly like a workout detail. The detail used to swap itself
  into the list card with its back button under the page title, and the
  recording had no address at all: nothing to deep link, nothing for the
  browser's own Back to return to. It reads by id, so a cold link works
- the list paints the five most recent strips. A watch that records every
  morning turns an unbounded list into a scroll, not a history

`ecg-classification.ts` holds the verdict label map the list, the detail and
the cross-link card each used to carry a copy of.
2026-08-08 15:17:05 +02:00
Marc-André Bombeck 0160052289 refactor(settings): retire Research Mode — the switch governed nothing
Research Mode was the opt-in behind the estimated GLP-1 drug-level curve:
turn it on, read a disclaimer, get the chart. The chart stopped consulting
the flag several releases ago and has painted for every account since, so
the switch on Settings → Advanced changed no screen in either position. An
inert control that promises to hide a chart is worse than no control.

The curve is simply part of the medication page now. Gone with the switch:
the acknowledgment dialog, `/api/auth/me/research-mode`, the shared status
DTO and its gate helper, the disclaimer-version stamp, the query key, and
the three user columns the acknowledgment wrote (migration 0321). The
Privacy page's second button pointed at the retired control and goes too.

Settings → Advanced is now what it reads as: reset the data, delete the
account.
2026-08-08 15:17:05 +02:00
Marc-André Bombeck beb070c0a0 fix(settings): cut five module rows back to one sentence
Environment, external assistant access, Documents, mental wellbeing and
nutrient intake ran 120-165 characters in German where their thirteen
neighbours sat at 30-75. Every one of the five carried the same second
sentence, "off by default", which restates what the switch beside the row
already shows.

The mental-wellbeing row also named two screeners where the module ships
four, and its second sentence held the one statement in the app about what
happens to the answers. That statement moves to the mental-wellbeing page
itself, where somebody is about to answer them.

A guard holds every module row to one sentence in all six locales, and
under the 120-character guideline in English and German.
2026-08-08 15:17:05 +02:00
Marc-André Bombeck 13b4a0be0b refactor(settings): thin the Account tree down to the profile
Two cards on Settings → Account were asking questions that already have a
home somewhere else.

- cycle tracking is a module, and the Modules hub carries the switch that
  drives the same `cycleTrackingEnabled` column. The Account card was a
  second door to one decision, so it goes, and the "manage in Account"
  deep-link beside the module switch goes with it. That link pointed at a
  `#cycle-tracking` anchor no element ever rendered, so it never landed
  anywhere in the first place
- changing a password belongs with the second factors and the passkeys.
  The card moves to Settings → Security and leads that page. It renders
  before the factor status resolves: it is now the only way to change a
  password and must not depend on a read it does not need

Account keeps the profile, the photo, the identity fields and the AI
context. The `settings.cycleTracking.*` strings leave all six bundles.
2026-08-08 15:17:05 +02:00
Marc-André Bombeck 0b09eb6b1e test(settings): pin that a flush card drops its gap, not only its padding 2026-08-08 15:17:05 +02:00
Marc-André Bombeck ebf0c9d632 fix(settings): close the dead space above every row of the Appearance list
The Appearance hub paints its modules as one divide-y ledger inside a
settings card, and the card dropped its padding without dropping its gap.
The gap survived between the rows as unclickable space the first row does
not have: 24 px on desktop, 16 px on a phone, measured. Rows read a step
apart from the top of their own list.

- SettingsCard grows a `flush` variant that drops padding AND gap, naming
  the shape `<InsightSectionCard flush>` already names on the Insights side
- the geometry sweep gains a fourth claim: in a divided list card nothing
  sits between two rows but the divider, and the first row starts at the
  card's inner edge
2026-08-08 15:17:04 +02:00
Marc-André Bombeck bfdc2ae025 Merge remote-tracking branch 'origin/main' into feat/encounter-phase-2 2026-08-08 15:08:17 +02:00
Marc-André Bombeck 2d69842994 fix(encounters): the visit list carries its links
Two defects behind one omission. The card counts what a visit produced, so a
list that dropped the links made every card read zero for a visit with three
documents. And the edit sheet seeds its pickers from the row it was handed: an
edit opened from a linkless list row would save a replace-set of three empty
arrays and silently unfile everything the visit had collected.

The links now ride the list, resolved in three grouped queries for the whole
page through the batched arm of the same service the detail uses, with the same
per-family redaction from the same predicate. The single-visit read hook had no
caller and is gone with it — the list is where the surfaces read from.

Both defects get a test that would have caught them: the card counts assert
against a populated links object, the draft asserts the arrays survive a round
trip through draftToBody, and the integration file asserts the list response
itself carries every family.
2026-08-08 15:06:10 +02:00
Marc-André Bombeck bdfea7dd85 test(encounters): the Phase 2 surfaces against real Postgres, and end to end
Three properties here cannot be answered by a mocked client, and each has a
shape that would pass a weaker assertion while being wrong:

- filing a visit against a due checkup twice satisfies it ONCE. Phrased as
  "the second call returned 200" it proves nothing, so the assertion is that
  lastSatisfiedAt did not move — and the instant is captured once, because two
  calls milliseconds apart are two different filings and the forward-only guard
  correctly advances on the later one.
- a lab commit writes one link PER RESULT ROW. A test that asserted "there is
  a link" would pass on one link for a three-marker panel.
- the visit list's condition filter runs in SQL. With one visit in the account
  a filter and no filter return the same list, so there are always two.

The bulk arm gets per-entry tolerance over a hundred documents, one unknown id
reported as one failed row with the rest filed, and a foreign visit refusing
the whole batch before anything is written.

The e2e spec proves the incidental-linking promise once, addressing stable
data-slot attributes rather than viewport text: a visit saves with a date and
nothing else, and a document dated inside the window offers that visit,
pre-selected because there is exactly one, and files itself against it.
2026-08-08 14:51:56 +02:00
Marc-André Bombeck b97988279e feat(vaccinations): wire the query keys, the contract and the consent copy
- a query-key module and a dependent bundle that also evicts the
  preventive-care root, because logging a dose settles a booster and the
  checkups list goes stale in the same tick
- the OpenAPI module publishes the resolved series with the contract
  written into the description: render text from these numbers, never
  recompute them
- the health-background consent sentence now names the immunization
  history in all six languages, so the widening is stated where it is
  agreed to rather than inferred from a code comment
- no server-side cache helper: nothing cached reads a dose, and a sweep
  over caches nobody reads would look like coverage without being it
2026-08-08 14:43:59 +02:00
Marc-André Bombeck 4d2f706dad feat(doctor-report): a report can mention a visit, and know why it exists
The VISITS leaf ships in the release that made a visit possible, because a
selectable checkbox that produces nothing is worse than no checkbox. Leaf,
collector and PDF renderer land together, and the leaf carries no LEAF_MODULE
entry — like ALLERGIES beside it — because a visit is core and the whole report
is already gated by doctorReport. The absence is commented at the map so a
later reader does not read it as an oversight.

The rows print the date, the practice with its specialty, the kind, the reason,
the outcome and the conditions the visit was filed against. The two encrypted
columns decrypt at render, fail-soft, and never enter the stored selection. A
condition the person has since deleted is not named: the link row survives a
soft delete, and printing a label they withdrew would put it in front of a
doctor.

No FHIR resource type is added. That deferral is already written at the
Encounter model, and the bundle builder now says so at the point a reader would
look for the missing section: FHIR splits the future from the past across
Appointment and Encounter, which is a serialisation question this release does
not answer.

Two properties are free and worth stating: a stored selection never grows
(unknown ids drop) and a clinician share link's sections are frozen write-once,
so no existing report and no already-shared link gains a section.

The panel also offers a booked visit as the report's reason — one query, one
prefilled window end, one dismissible offer that names its own source and never
applies itself. A window control that moves on its own is what makes an export
panel untrustworthy.
2026-08-08 14:38:26 +02:00
Marc-André Bombeck 82982038cb feat(vaccinations): let a logged dose clear the boosters it answers
- the dose is expanded to its component antigens first, so one Tdap
  entry settles a tetanus booster and a pertussis booster at once;
  matching the preparation's own slug would leave both standing
- it runs inside the create transaction and nowhere else: no cron, no
  ingest hook, and an edit never re-runs it, so correcting a typo in a
  date cannot move a reminder
- forward-only, which is what makes transcribing an old record safe: a
  page from decades ago never clears a booster that is due now
- a free-text-only dose matches nothing; a name string is not evidence
  about what was in the syringe
- an ordinary preventive-care reminder carries no antigen key and is
  structurally out of reach
2026-08-08 14:36:08 +02:00
Marc-André Bombeck 7ac81f3eed feat(vaccinations): publish the routes, classify them, gate the module
- four route files: list and create, read and edit and delete, restore,
  and the link pair; every delegable one is classified as health
  background, in each leg of the sharing guard, with its reason written
- link and unlink stay bare, consistent with the document and visit link
  routes; the three are revisited as one decision
- vaccinations becomes the nineteenth module key, default-on and
  surface-gated like medications: the data routes stay exempt so a
  restore keeps working and re-enabling finds every dose intact
- a delegate's dose entries get their own sentence in the owner's
  activity view rather than reading as a generic change
2026-08-08 14:27:36 +02:00
Marc-André Bombeck 4dc3b1aa27 feat(vaccinations): add the wire schemas and the resolved DTO
- a dose needs a day and one way of naming what it was, and nothing
  else; a required catalogue pick would make an old Pass line unloggable
- the write path refuses a future date and a slug the catalogue does not
  offer, while storage stays tolerant so an older backup restores whole
- the DTO publishes the practitioner, the visit, the linked pages, the
  catalogue entry and the derived series already resolved, in numbers
  rather than localised text
- a linked page's name and date are withheld from a delegate whose grant
  does not reach the vault, and the withholding says so rather than
  looking like a page with no name
2026-08-08 14:09:52 +02:00
Marc-André Bombeck c47122ccfe feat(encounters): the lab moment, the condition side, and closing a checkup
A lab panel files itself against the visit it came from, and never has to. The
OCR review and the manual form both offer the suggestion through the one shared
field, anchored on the draw date rather than on now, so backdating a reading
moves the offer with it. The commit writes one link PER RESULT ROW, which is
why the join is m:n: a marker re-run on a different day belongs to its own
visit. Best-effort by design — the readings are the write that matters and must
not be lost to a link that could not be made.

The condition side gets a Visits about this card with an action that pre-links
the episode. From the episode side only, and that is a decision: an episode
spans weeks and a visit is a point, so matching the other way would be wrong
often enough to teach a person to ignore every suggestion in the product.

A due checkup gains a second action beside erledigt. Filing the visit as done
satisfies the checkup through the same forward-only, idempotent primitive the
checkbox uses, so doing both is one satisfaction and no error. The two actions
answer different questions — one says it happened, the other says where.

An appointment now appears where a person looks, and NEITHER surface relaxes
the reminder-table exclusion that keeps it out of the preventive-care lists.
Both read the visit table: a quiet line under the dashboard checkup block for
anything inside two weeks, and one rail item for today or tomorrow. A diff in
either that touches origin is the wrong fix.

A visit write now also refreshes the reminder reads. Closing a checkup moves
its next-due date on three surfaces that would otherwise keep showing it due
until their own poll.

OpenAPI regenerated in the same commit.
2026-08-08 14:08:09 +02:00
Marc-André Bombeck e22c7ddfcc feat(vaccinations): teach the link facade the dose-to-document pair
- one new source and one new pair; the module's invariants carry over
  unchanged, so ownership, idempotency, the batch cap and the
  soft-delete refusal need no new code
- each invariant gets its own case against the new table, because every
  one of them is a where clause on a different table and a pair wired to
  the wrong column would pass all the existing ones
- the ceiling is written down and asserted: the vaccination source owns
  exactly one pair, and asking for a second is refused loudly
2026-08-08 14:05:58 +02:00
Marc-André Bombeck 01f94df60b Merge pull request #745 from MBombeck/fix/encounter-orphan-exports
Drop the two visit exports nothing consumes yet
2026-08-08 14:03:50 +02:00
Marc-André Bombeck e44b1615e1 feat(vaccinations): derive the series position per component antigen
- one pure function resolves "dose N of M" over a person's whole
  history, so the number rides the DTO already computed and no client
  re-derives it
- a combined dose counts into every antigen it contains, at whatever
  position each of those series is at: one Tdap line is a tetanus
  booster and a first pertussis dose in the same act
- the Pass's own dose number wins over the count, and the record's own
  series length wins over the catalogue's
- a seasonal dose has no series to be part of, so nothing reads as a
  booster on a length it never had
- interval adjudication is deliberately absent; this is arithmetic on
  what a person wrote down
2026-08-08 14:00:39 +02:00
Marc-André Bombeck e190c32c77 feat(vaccinations): seed the antigen-level vaccine catalogue
- 35 entries across the childhood, standard, later-decade, indication
  and travel sets, so a Pass covering a whole life has somewhere to land
- ATC-coded from the WHO J07 subtree, component-aware so one combined
  dose counts into every antigen series it contains, and each entry
  cites the document its numbers come from
- no manufacturer column and no trade name in any shipped string; the
  one place a trade name belongs is the person's own transcription
- the resolver is the only lookup path and answers null rather than
  throwing, so a slug a later release drops still renders as what the
  person wrote
2026-08-08 13:58:17 +02:00
Marc-André Bombeck 6926caa11d feat(vaccinations): carry the immunization log through export and restore
- a new backup section reads the dose and its document link through
  their own delegates and writes both ends in one file, the arrangement
  the visit section already uses
- the practitioner and the visit remap to the rows the same restore put
  back; the booster reminder never travels, so its reference resolves to
  null and the drop is reported rather than swallowed
- the antigen slug restores verbatim: a slug the catalogue has since
  dropped still says what a person was given
- the round trip seeds a dose with every optional column filled and
  reads each one back, so a returning row count cannot stand in for a
  returning record
2026-08-08 13:54:24 +02:00
Marc-André Bombeck 7981c34cc7 Drop the two visit exports nothing consumes yet
The timezone resolver and the dependent-keys bundle shipped ahead of
their consumers, and the dead-code gate rightly went red on the trunk.
The surfaces that need them arrive with the next visit stage and bring
them back together with their callers.
2026-08-08 13:48:14 +02:00
Marc-André Bombeck be9c79974f feat(documents): a document can say which visit it belongs to
Every arm here is the same shape as the one that already exists for
conditions, because the vault's filing model is settled and a second shape
would be the thing to explain rather than the thing to use: encounterIds on
upload and on PATCH with replace-set semantics, linkEncounter / unlinkEncounter
beside the episode pair in the bulk action, and an encounterId list filter.

Both directions ride ONE table. The visit's sheet writes encounter_document_links
from its end and the document reads it from the other, declared as a second
direction in the link service rather than a fourth table. A visit's kind
crosses the wire as the enum constant rather than a rendered name: unlike a
condition label, which is the person's own words, a kind is one of eight closed
values whose human name the reader's own bundle owns.

The suggestion is offered where the document is being looked at, resolved by
the shared rule rather than by this surface: one candidate pre-selects with an
undo, two offer a picker with nothing pre-selected, none offers nothing at all.
It resolves with no AI provider configured, and it renders nothing once the
document already names a visit.

The bulk verb has a caller — the vault's selection bar files a whole selection
against a visit, mirroring the condition verb and hiding itself on an account
with no visits. Nothing here is one-ended.

OpenAPI regenerated in the same commit.
2026-08-08 13:41:42 +02:00
Marc-André Bombeck 1bd97de943 feat(vaccinations): write the backup, wipe and rotation verdicts
- both models are backed up and claimed two-ended: an immunization
  history has no other copy once the paper Pass has been transcribed
- the document link is wiped ahead of the dose, and the dose ahead of
  the practitioner it points at with SetNull, so the audit row's
  per-model counts stay truthful
- the dose note joins ENCRYPTED_COLUMNS and the rotation walk; the batch
  code and the other structured columns stay queryable plaintext
2026-08-08 13:39:06 +02:00
Marc-André Bombeck f28658c611 feat(vaccinations): add the immunization record and its document link
- VaccinationRecord holds one administered dose: date, catalogue slug or
  the Pass's own wording, dose and series numbers, batch code, site, and
  optional links to a practitioner, a visit and a booster reminder
- VaccinationDocumentLink keeps the scanned Impfpass page beside the dose
- MeasurementReminder gains a nullable vaccination_antigen match key so a
  logged dose can clear a booster without a second reminder engine
- migration 0330, additive apart from that one nullable column
2026-08-08 13:35:03 +02:00
Marc-André Bombeck ed1438230c feat(encounters): visits and the address book become reachable
/checkups gains a second section rather than a nav entry. The page already
owns the right sentence — when do I have to do what, where — and is
deliberately not module gated, which is the same reason a visit carries no
module key of its own: what a visit may point AT follows the modules that own
those things, so the gate sits on the three link pickers and blanks the block
rather than rendering an empty one.

A visit saves with a date and nothing else. No required practitioner, no
required kind, no required link, and the only thing that can disable Save is a
date that will not parse. The status is derived from the date on a new visit
and only becomes a field on an existing one, because somebody booking an
appointment should not also have to tell the app that it is in the future.

The address book is record content, not configuration, so it sits under
/checkups rather than in Settings — and it inherits that page's route-family
classification with it. Deleting an entry says in one sentence that the old
visits stay, because a person deleting a doctor has every reason to fear
otherwise.

Two defects closed on the way:

- /checkups carried sharedRecord: true and appeared in neither route family,
  so a scoped grant could not present it at all. It was invisible while a
  whole-record grant admitted every path; the visits section makes it load
  bearing, and the page is now listed under both domains whose content it
  shows. Deduplicated, or a grant holding both would offer the page twice.
- the address-book search read the name only, so looking a practice up by the
  name on the door returned nothing and read as "not in the book".

The practitioner search description in the OpenAPI module moved with it.
2026-08-08 13:21:43 +02:00
Marc-André Bombeck 8d48e3e262 Merge remote-tracking branch 'origin/main' into feat/mood-prognosis 2026-08-08 13:00:02 +02:00
Marc-André Bombeck 467e83d639 feat(encounters): one suggestion rule for every filing moment
A document arriving in the vault and a lab panel being committed both ask the
same question — does this belong to a visit? — and the answer has to be the
same question asked once. The rule lives in one module with one exported
window constant: the caller's live DONE or PLANNED visits within seven days of
an anchor date, resolved into a verdict rather than a list.

One candidate pre-selects, visibly, with one undo. Two or more offer a picker
with nothing pre-selected: pre-selecting the first of two is what teaches a
person to stop reading suggestions, and the return type has no field on that
arm a caller could mistake for a choice. Zero offers nothing.

Cancelled visits and no-shows are not candidates. Neither happened, so neither
produced the letter or the panel being filed, and admitting them would widen
the set with rows that are wrong most of the time — which pushes the honest
single match into the picker branch.

The verdict is served over HTTP because all three moments live in the browser.
Handing the client a windowed list and letting it decide would put the rule in
two places, and the copy in the browser is the one nobody re-reads.

- suggest-window.ts with the window as an exported constant, not a literal
- GET /api/encounters/suggest, profile domain, reviewed into the frozen literal
- OpenAPI regenerated
- fixtures are relative to the run instant; a fixed date slides out of a
  relative window and rots the test into a false green
2026-08-08 12:43:51 +02:00
Marc-André Bombeck 84dae1668a docs(mood): say what the seasonal floor gates, and what it deliberately does not
It gates the flag the forecast publishes, so a surface asking whether the
history supports a weekday claim about THIS comparison asks one place.
It does not retro-gate the weekday board the insights page has carried
for releases — that board is built from the entry aggregates and has its
own floors, and hiding it from accounts under ninety days would take a
surface away from people already reading it to enforce a rule about a
different calculation. And it does not justify building a second one.
2026-08-08 12:38:27 +02:00
Marc-André Bombeck 46dc31d10e fix(notifications): offer no completion action on an appointment nudge
An appointment reminder rides the same MEASUREMENT_REMINDER event type as a
checkup — one engine, deliberately — so every channel attached its Done /
Later affordance to it: the Telegram inline keyboard and the APNs category
whose actions the iOS app registers. Both resolve the reminder by id, and
every by-id reminder surface refuses an ENCOUNTER-origin row, so each button
could only answer "not found".

The producer knows the origin, so it says the dispatch carries no action and
each channel drops its own affordance rather than re-deriving the rule. The
reminder id still rides the metadata: it identifies the nudge for the
client-managed suppression tag, and what is withheld is the offer to act.

- suppressActions on the notification payload, documented where it is declared
- Telegram builds no measurement keyboard for a suppressed dispatch
- APNs withholds the category and strips the reminder id from the iOS payload
- a negative control keeps a checkup nudge actionable
2026-08-08 12:37:21 +02:00
Marc-André Bombeck 13d808ccff fix(mood): bound the fit's read, and show the day as a date
Two small things the first pass left rough.

The fit's window read had no row cap. A year holds 365 days and the fold
keeps one entry per day, so the cap only bites on an account that logs
many times a day — but an unbounded read in a nightly job is a table
scan waiting for the account that has years of history. The rows now
arrive newest first under a cap, which also puts the loss on the right
end: an account over the cap loses its oldest days, never the recent
ones a forecast is written for.

And the card showed the raw day key. It goes through the account's own
date-order preference now, pinned to UTC like every other day key in the
app, so this card cannot show a different day from the list beside it.
2026-08-08 12:37:14 +02:00
Marc-André Bombeck 09bf0a1947 fix(openapi): publish the sharing refusal on the prognosis read
Every delegable operation states, in the contract, that it can refuse a
delegate — and the guard over the document caught this one publishing
only its module gate. One status, two reasons: the module gate's own
sentence first, the shared refusal spliced on the end, which is the
shape every other gated delegable route already uses.
2026-08-08 12:30:13 +02:00
Marc-André Bombeck f599eba671 Merge pull request #743 from MBombeck/feat/encounter-phase-1
Add the visit record, its carriers and the appointment arm
2026-08-08 12:25:16 +02:00
Marc-André Bombeck a83be074ca Merge branch 'main' into feat/encounter-phase-1 2026-08-08 12:22:04 +02:00
Marc-André Bombeck 5c25bde822 Pin the orphan sweep in both directions
The sweep that retires an appointment reminder no visit claims had no
test of its own. Two now, because the rule has two halves and only one
of them is obvious.

It reaps a live row nothing points at, and it must leave a row whose
only claimant is a soft-deleted visit. That second half is the subtle
one: the sweep matches on the relation and does not read the visit's
tombstone, so a deleted visit still owns its nudge and restoring the
visit finds it intact. A future change that "tidied" the predicate by
also excluding tombstoned visits would destroy that on the next
unrelated write, and nothing else would notice.

The visit is tombstoned directly rather than through the delete route,
which retires the reminder deliberately and would have proven nothing.
2026-08-08 12:20:19 +02:00
Marc-André Bombeck d45cedcf5d docs(changelog): note the mood comparison and its refusals 2026-08-08 12:15:44 +02:00
Marc-André Bombeck c33f7f9f6a feat(mood): let the Coach read the deviation, and publish the resolved forecast
The snapshot gains the day's two readings with the age of the second
one, through the same reader the page uses, so the page and the
assistant cannot disagree about what today's comparison is. The
freshness rule is the shared one: a comparison about the day before
yesterday carries the date it is about and an instruction not to state
it as today. Absence is a present field rather than a missing key —
a model told "there is none yet" says so, and a model told nothing
estimates one. The wording rule travels with the values, because a model
handed a number and no instruction writes the sentence its training
suggests, and about a forecast that sentence is a causal one.

The contract publishes the resolved value: the expected figure, the
band, the count, the deviation against the band, the age, and the
contributions that carried weight. Nothing is left for a client to
re-derive — two clients deriving the same figure about somebody's health
record is how they start disagreeing about it. The description carries
the observational wording and the display rule: the count goes wherever
the value goes.

The end-to-end proof runs against real Postgres and reads the table
rather than a return value: nothing written a day short of the
threshold, a banded and counted row on the day it crosses, the
provisional label dropped at sixty days, the rows cleared when the
module goes off, the rows cleared when entries are deleted back below
the threshold, and an older pass's row replaced rather than left beside
a fresh one. A delegate holding only the mind section is refused, and
the assertion is on the response bytes.
2026-08-08 12:15:18 +02:00
Marc-André Bombeck f48afed82d feat(mood): show the day's own rating beside what the account's days imply
Two readings, side by side, never merged. The person's own rating leads
— larger, first, and returned exactly as it was stored — and the
comparison sits beside it with its range and the number of days it was
built from. The deviation is measured against the range, not against its
midpoint: inside it is a day that went as the account's own past days
suggest, and only outside it is worth a sentence.

The sentence is a counterfactual and says so. Never "your mood is 5.4",
always "a value around 5.4 would have been expected". The explanation
names what the comparison weighted for that day, out of what the job
stored for that day, in the words the capture sheet already uses — a
person reads "Workload" here because that is what the slider they moved
was called.

The route declares the whole record rather than the mind section, and
the reason is written at the declaration: the comparison reads the day's
context AND the figures the sleep, activity and recovery modules hold,
and it names them, so a delegate holding only the mind section would
receive a derived view of sections the owner declined to share. A scoped
grant is refused outright rather than served a contribution list with
the linked features quietly removed, which would read as "only the mood
fields mattered" and be false.

The causal-verb ban is a test now rather than a review habit: the copy
guard reads all six bundles and fails on a causal construction in any of
them, and on a statement that quotes a value without the days behind it.
Both halves were watched failing.
2026-08-08 11:43:58 +02:00
Marc-André Bombeck 244e8ffbc7 feat(mood): rebuild the forecast rows nightly, and clear them when they stop being true
A job, never a route. A forecast written as a side effect of opening a
page is a function of browsing rather than of data, and the prognosis
also has to be a value the person cannot overwrite — so one file writes
the table and a guard holds it there.

The cohort is the union of two sets and the second one carries the
weight: accounts with enough recent rated days, plus every account that
already holds rows. Without the second, an account that deleted its
entries would fall out of the sweep and keep last month's answer under a
fresh-looking date, with nothing on the surface to say so.

A pass replaces rather than accumulates. Every account it touches ends
holding exactly the rows that run wrote, or none: below the threshold,
module off, no pattern in the data, no recent day carrying everything
the fit needs — every one of those clears what was there. Per-account
failures are counted and the pass continues; only an all-accounts
failure fails the job.

Runs at 04:35, after the inputs have settled and clear of the geo
backfill on the hour's fortieth minute. The arithmetic is a ridge
regression and nothing else: no provider, no key, no egress, no consent
gate, and the module says so at the top so nobody wires one that does
not apply or assumes one that is not there.
2026-08-08 11:31:39 +02:00
Marc-André Bombeck 64c077f7ac feat(mood): build the day matrix and fit it without letting it see ahead
The target is the day's own pleasantness; the inputs are the other four
self-ratings, the numbers and closed vocabularies of the day's context,
and the figures the sleep, activity and recovery modules already hold.

Nothing is imputed. A day missing one of the selected inputs is a day
the fit does not see, and a feature nobody recorded on most days never
becomes a column in the first place — the coverage floor is what keeps
the complete-case rule from quietly emptying the matrix. A day with no
context row contributes no work-status column at all, rather than a zero
that would read as "worked a regular day".

Columns are standardised against the account's own window, so a person
whose stress never passes six does not have six read as the maximum.
Candidates are screened with the machinery the rest of the product
already runs — Pearson at the shared paired floor, Benjamini-Hochberg at
the shared FDR, the shared effect-size floor on the shrunk estimate —
because a sweep over sixty features at raw p < 0.05 finds three things
that are not there.

The fit is a ridge solved in closed form, validated on expanding windows
in date order. The training range ends exactly where the validation
range starts, asserted on the fold indices and on the day keys, not on
the resulting error: a leaking split passes an error check whenever the
leak is small, which is when nobody looks. The band is the central 80%
of the validation residuals, so it widens when the model is bad instead
of staying confidently narrow.

The window read is the linked resolver's own engine, extended to answer
many days in one query rather than growing a second opinion about what a
Tuesday looked like.
2026-08-08 11:25:34 +02:00
Marc-André Bombeck 339e815527 Keep an appointment reminder inside the visit that owns it
Review of the visit work found the appointment arm leaking in both
directions: rows the visit routes could strand, and a reminder surface
that would act on one as though it were a checkup.

An edit could orphan a live reminder. Pointing a still-booked visit at
the checkup it closed walked the foreign key off the visit's own
reminder, and the next reschedule then minted a second one, because the
re-anchor path asked the key what the visit owned instead of asking the
engine. An orphan fires: the cron reads the reminder table, not the
visit list, so it pushed for an appointment nobody could see, edit or
cancel, and deleting the visit did not reach it. The edit arm now
refuses the contradiction the create arm already refused, ownership is
resolved through the relation, deletion retires the row it owns rather
than the row it points at, and a sweep at the end of every visit write
retires anything left armed that no visit claims -- so the state is
unreachable rather than merely unlikely.

The by-id reminder routes never excluded appointments, and that was the
larger hole. Marking one done committed the satisfy and THEN failed on
the mapper, so every appointment push a person acknowledged answered 500
after the write had landed. An edit could give a spent one-shot a
cadence and turn it into a permanent nudge that appears in no list, or
switch a cancelled one back on. The delete is a hard delete, so somebody
holding only the measurements domain could destroy a row belonging to a
visit in the health background. All five refuse in the lookup now -- an
appointment is not addressable there at all -- and the chat buttons that
mark a reminder done or postpone it refuse it the same way. Nor is an
appointment satisfied by a lab result: the auto-satisfy matcher used to
resolve any free-text reminder from any panel, which would have marked
next month's cardiology appointment attended.

A visit is a seam between four domains, and names were crossing it. The
values never did, but the title of a discharge letter is itself the
sensitive part, and a grant that opened only the health background was
never consent for it. Link labels and dates now follow the target's own
domain; the link is still listed, so a delegate learns the visit
produced a lab result without learning which analyte. Closing a checkup
follows the same rule: it re-anchors a preventive-care cadence, which is
a measurements write, so a health-background delegate files the visit
and the closure is reported as skipped rather than performed in silence.

Three smaller repairs. A checkup now closes at the visit's own instant
rather than at the moment it was typed in, which anchors a backdated
entry correctly and makes correcting a mis-filed visit the no-op it
should always have been. A window ending before today no longer widens
back out to today. And the fallback in a push notification was the raw
enum constant, so a lock screen could read a schema value; it reads the
record owner's own language now, in all six.
2026-08-08 11:24:08 +02:00
Marc-André Bombeck 0aeb63cbeb feat(mood): the minimum-n ladder, as constants with boundary tests
Five rungs — nothing at all below fifteen entries, descriptive hints to
thirty, a provisional forecast to sixty, a plain one to ninety, weekday
and seasonal comparisons above it — plus the occurrence floor a value
must clear before it may be named at all.

Every floor is an exported constant and every one has a test on both
sides of its own boundary, because the failure here is invisible: a
forecast built from eight days renders exactly like one built from
eighty, and nobody reading the screen can tell. Each assertion names the
threshold it is about, so a red says which floor moved.

Absence carries its reason and the count rather than being a bare false,
so a surface can say how far along the account is instead of showing an
error. Two numbers are deliberately not minted here: the paired-value
floor stays `MIN_PAIRED_N` in the correlations module, and the
occurrence floor is the crosstab's own, taken by assignment. A test
reads the file back and fails if either turns into a local copy.
2026-08-08 11:15:00 +02:00
Marc-André Bombeck a118d4810d feat(mood): add the prediction table, with one writer and no writer yet
`MoodPrediction` holds the expected value of a day beside the day's own
rating: one row per account per local day, with a band and the number of
days the fit used. Two tables rather than four columns on the entry,
because the point of the second value is that the person cannot correct
it into agreement with the first — the distance between them is the
finding, and a value the edit form can write is not a second reading.

The table stays out of the disaster-recovery backup and the reason is
written where the completeness guard reads it: every row is recomputable
from the entries, the contexts and the linked modules, and carrying one
would restore a forecast made by a model version that may no longer
exist against data the restore has just moved. It is in the wipe plan,
because a derived row is still a day-by-day statement about somebody.

The write-surface guard lands red on purpose and names what is missing:
`lib/jobs/mood-prognosis-refresh.ts` does not exist yet, so the writer
set is empty where it should hold exactly that one file. The job closes
it. The rest of the guard is green now — no route, page or component
writes the table, and the matcher proves itself against a call broken
across lines, an aliased client, a read and a different model.
2026-08-08 11:10:25 +02:00
Marc-André Bombeck 779b7bcaf1 Merge pull request #738 from MBombeck/feat/mood-level-b
Mood entries carry the day around them
2026-08-08 10:58:03 +02:00
Marc-André Bombeck 61c220b7b8 Merge branch 'main' into feat/mood-level-b 2026-08-08 10:57:59 +02:00
Marc-André Bombeck bcad15c7e1 perf(insights): defer the mood breakdowns and the icon map off first load
/insights/mood was on its 460 KB ceiling. The route paints a calendar, a line
chart, a target card and an assessment; under them sit a dozen breakdown cards
— both tag axes, the influence board, the two crosstabs, the day-context
comparison, four Recharts mini-charts, the correlation cards — and every one of
them was a static import, so a cold mount paid for all of it before painting
anything.

The cluster is its own module now, loaded through next/dynamic with a skeleton,
the way the insights mother page already treats its below-the-hero blocks. It
takes the resolved aggregate as a prop rather than running a second query, so
it cannot draw a different snapshot from the regions above it.

The better-days card follows, for one specific reason: it resolves catalogue
tag icons, and that resolver statically imports about a hundred and sixty
lucide icons. The card sits a screen down and the map now rides the same lazy
group as the breakdowns.

Only mood-only modules moved. Deferring the shared target and assessment cards
was tried and reverted: it bought ten kilobytes on this route and cost
thirty-three on the whole-build total, because both are imported by a dozen
other insight routes and a route-local lazy group duplicates them.

  /insights/mood  459 -> 451 KB gz  (budget 460, unchanged)
  total client JS 3296 -> 3297 KB gz (budget 3310, unchanged)

The payload shape and the section card frame move to a shared module both
halves import; the two structural tests that read the old file now read the
union of the two, so a guard cannot go quiet by pointing at the wrong half.
2026-08-08 10:54:59 +02:00
Marc-André Bombeck ff8b1a61b0 Merge pull request #741 from MBombeck/feat/workout-series-enrichment
Attach a heart-rate series to a workout the server already stores
2026-08-08 10:41:48 +02:00
Marc-André Bombeck 0a3811c7a4 Drop the vocabulary exports nothing consumes
The six per-section type aliases and the inverse-orientation list had
no consumer; the schemas read the key arrays directly and the workLoad
orientation is stated where the rating fields are declared.
2026-08-08 10:28:47 +02:00
Marc-André Bombeck b4051e6db3 Merge branch 'main' into feat/mood-level-b 2026-08-08 10:11:13 +02:00
Marc-André Bombeck b0627cfc5e Merge branch 'main' into feat/workout-series-enrichment 2026-08-08 10:09:47 +02:00
Marc-André Bombeck ed5941d313 fix(mood): read an edited entry's linked day in the entry's own zone
The hook always sent the browser's zone while the route's comment said the
detail view sent the entry's stored one. Nothing was red, because nothing
asserted it: correcting an entry logged in another country looked its day up
under whichever zone the correction was being made from, and the night shown
beside it could be hours out with nothing on screen saying so.

The edit dialog passes the entry's `tz` now. The capture sheet keeps the
browser's and passes no third argument, which is correct rather than an
omission: the entry does not exist yet and will be anchored to that zone.

A legacy row with no zone falls back to the browser's rather than to
Europe/Berlin — the server owns that legacy rule and a guess sent from the
client would override the one place it is written down.

The resolution is a pure helper so both branches can be asserted, and both
call sites are pinned structurally, because the resolution being right is
worth nothing if the dialog never hands it the entry's zone.
2026-08-08 09:59:06 +02:00
Marc-André Bombeck eac40e79d6 fix(api): a bad dimension skips its own bulk entry, as the contract said
The doc comment beside `a1`..`a5` promised that an out-of-range value marks
THAT entry skipped and never the batch, while the fields sat in the batch
schema and answered 422 for all five hundred. The words were right and the
code was not, and a phone draining a year of local history lost the year to
one row.

The five now parse per entry, the same way the day context does; a bad row
reports `invalid_dimensions` and the rest of the batch lands.

The split buys the tolerance and costs a second copy of "0 to 10", so a guard
offers the same value to both schemas and makes them agree at both ends of the
scale and one step outside each.
2026-08-08 09:58:50 +02:00
Marc-André Bombeck 1853a71b18 fix(mood): ask the ownership table who owns a linked metric, and pick one source
The resolver hand-wrote the map and got it wrong in both directions. It gated
steps and active energy on `workouts`, which gates workout SESSIONS and not
ambient movement, so the mood sheet hid a figure every other surface shows. It
called resting heart rate and heart-rate variability core with no owner, while
the table has assigned both to `recovery` since v1.30.22 — including the RMSSD
fallback, pinned there so a ring-only account cannot reach through it. An
account with recovery switched off was served the domain it had switched off,
which made the release note's own promise false.

Both directions now resolve through `moduleForMeasurementType()`, the table the
MCP wire, the correlations reader and the Coach snapshot already share.

Steps, active energy and the two vitals also run through the canonical-source
picker now. Without it a phone and a watch reporting the same day summed twice
and the sheet showed a walk nobody took; the vitals answered whichever row was
latest rather than the picked stream's.

A guard pins the three ownership claims, including that the two vitals share
one module — the block carries one availability flag for the pair, so the day
they diverge that flag becomes a lie and the block has to be split first.
2026-08-08 09:58:37 +02:00
Marc-André Bombeck 88f83104e0 fix(mood): the linked day read crosses sections, so it declares record
The route answered sleep minutes, steps, active energy, resting heart rate,
heart-rate variability and an illness day-log with its symptom keys, and it
declared `mind`. A delegate given only the mind section could walk arbitrary
dates through the one URL and read two sections the owner had declined to
share; no mood entry had to exist for any of those dates.

`record` is the convention for a read that crosses sections, and a scoped
grant never reaches one, so the scoped delegate loses the linked block rather
than receiving a filtered day. A block that silently dropped the sections a
grant does not cover would show a day that looks empty where the truth is that
it is none of the reader's business.

The reason is written at the declaration and in the frozen surface entry,
whose previous justification held only for whole-record grants.
2026-08-08 09:58:22 +02:00
Marc-André Bombeck 3510043eba Merge pull request #742 from MBombeck/fix/backfill-taken-at-slot
Record a backfilled dose at its slot's own time
2026-08-08 09:53:55 +02:00
Marc-André Bombeck 4f3a790ce7 test(workouts): pin the losing side of a concurrent enrichment
Two requests can probe the same workout, both find no heart-rate series,
and both mean to attach one. The unique index on `workout_id` picks a
winner; the loser has to report the duplicate it turned out to be rather
than claim an attach the database never made. Nothing could catch that
arm going wrong: the unit fake echoes every row back as landed, and the
race suite carries no series at all, so replacing the status with a
constant `enriched` left the whole suite green. Two concurrent posts of
the same enrichment now assert one `enriched` against one `duplicate`
and a single stored series.

The published contract also says now what the counters mean, instead of
leaving it in a comment: an entry reported as `enriched` counts towards
`duplicates`, because the top-level counters count workout rows and an
enrichment writes none. Field descriptions on the response and on the
per-entry status and reason, OpenAPI regenerated.
2026-08-08 09:53:09 +02:00
Marc-André Bombeck f3c84018f9 Record a backfilled dose at its slot's own time
Marking an older missed dose as taken from the Verlauf pinned the
right slot but stamped the intake with the current moment. The body
builder is a pure helper now, anchored on the slot instant, matching
both the optimistic paint and the skipped-to-taken flip that already
behaved this way.
2026-08-08 09:38:30 +02:00
Marc-André Bombeck 21a14ea679 docs(workouts): drop the version guess from the enrichment notes
The release these land in is not cut yet; naming one in a code comment
would be a number nobody verified.
2026-08-08 09:28:12 +02:00
Marc-André Bombeck 508d44633e fix(workouts): one series, one enrichment, when a batch names a workout twice
Two entries carrying the same external id and both a `samples` array
reached the enrichment arm one after the other, and both read the same
landed workout id back, so the response claimed two attaches where the
database had written one. The second entry now takes the duplicate arm:
a workout is claimed by the first entry of the batch that reaches it.
2026-08-08 09:26:24 +02:00
Marc-André Bombeck 008de4fc6c Merge pull request #740 from MBombeck/fix/drop-workout-why-button
Drop the coach launch button from the workout detail
2026-08-08 09:23:06 +02:00
Marc-André Bombeck d24dfd89a9 Drive each new visit mutation through the sharing matrix
The v1.37 matrix demands an executable driver per admitted mutating
handler, not just a line in the inventory: it runs the real route as a
delegate, asserts the effect landed once, and asserts the audit row
names the acting delegate rather than the owner. Eight admissions came
with the visit API, so eight drivers land with them.

The visit fixture is deliberately in the past. A planned future visit
mints an appointment reminder, and a driver that asserted one effect
while producing two would be checking the wrong thing.
2026-08-08 09:19:06 +02:00
Marc-André Bombeck 3d55289ba3 feat(workouts): attach a heart-rate series to a workout already stored
A batch entry matching a stored workout stays first-write-wins for the
workout row. What it can do now is hand over a heart-rate series the
stored workout does not have yet: the series is attached, the row itself
is not written at all, and the entry reports back as `enriched`. A
workout that already carries a series is a no-op, so a client can walk
its whole history as often as it likes.

- The pre-flight probe now answers both questions at once, whether the
  row exists and whether it already has a series, and carries the id so
  the attach addresses the stored workout without a second round trip.
- The attach rides the same child write as a fresh workout's series.
  RETURNING names the rows that landed, so a workout that gained a
  series between probe and write reports as the duplicate it is instead
  of claiming an attach that never happened.
- A `samples` array that fails validation is refused per entry with
  `reason: "invalid_samples"` rather than failing the batch. One
  unusable session out of a hundred must not stall a history sweep the
  client cannot repair by retrying; every other validation failure keeps
  failing the batch.
- The wide event and the audit row tally enrichments. Counts only, the
  series never reaches either.
- `enriched` is the one contract movement: additive on the per-entry
  status, request shape unchanged. OpenAPI regenerated.

Integration coverage against a real Postgres pins the attach, the
repeat as a no-op, the refusal of a bad series alongside entries that
land, a mixed batch reporting each status, and the stored workout row
compared whole before and after, `updated_at` included.
2026-08-08 09:15:44 +02:00
Marc-André Bombeck b61b53263e Drop the coach launch button from the workout detail
The page ended on a "Why?" button that opened the coach with a
prefilled question about the session. It leaves on the maintainer's
call; the coach remains reachable from its own surfaces. The two
strings it carried leave all six locales with it.
2026-08-08 09:07:38 +02:00
Marc-André Bombeck f91eedb6bb Merge pull request #739 from MBombeck/fix/mood-block-name
Name the mood sliders for what they ask
2026-08-08 08:50:19 +02:00
Marc-André Bombeck d1fa0d9d52 Name the mood sliders for what they ask, not how many they are
The capture section and the insights card called the five sliders
"Five scales", a count where a name belongs. They now carry the
state-of-mind wording in all six languages, with Spanish diverging
from the first slider's own label so the block and the mood slider
stay distinguishable.
2026-08-08 08:34:53 +02:00
Marc-André Bombeck 4a1bca0761 Publish the visit contract and name visits at the point of consent
Query keys land in the central factory before any surface reads them,
because the lint rule that bans a bare array means the first component
listing visits cannot compile without a slot. There is deliberately no
server-side cache invalidator beside them: nothing cached reads a visit
yet, and a sweep over caches nobody reads would look like coverage
without being any. The module says so at the place a reader would go
looking.

The OpenAPI table publishes seven paths with everything resolved — the
practitioner as an object rather than an id, each link with its label
and date, the appointment's next due instant computed. What it does not
publish is the reminder origin enum, which still reads with two members:
the third value exists in storage and reaches no response, because every
preventive-care read excludes it. Keeping that contract closed is why
the exclusion is worth a guard.

Classifying visits under the existing health-background domain widens
what that domain grants. Somebody who shared it so a relative could see
an allergy list now also shares every appointment and the address book.
That is stated where it is agreed to rather than left in a code comment:
the consent screen's sentence names visits and practices, in all six
locales, and the activity feed gains a verb line for each of the eight
new delegated actions so an owner reads what was done rather than
'made a change'.
2026-08-08 08:11:54 +02:00
Marc-André Bombeck 7b1a44e799 chore(mood): account for MoodContext in the four whole-schema guards
- the wipe plan names it before its parent, so the confirmation screen's count
  is the number of rows that existed rather than zero
- the backup plan classifies it as carried and two-ended, and the round-trip
  registry seeds one, which is what makes that claim provable
- the sharing surface admits the linked-day read with the reason it may answer
- CHANGELOG for the release
2026-08-08 08:10:15 +02:00
Marc-André Bombeck f158494def Add the visit and address-book API, and the appointment arm
Nine visit routes and five practitioner routes, all classified under the
existing profile domain and each reviewed into the frozen sharing
literal with the sentence that argues for it. An address book of a
person's own doctors is record content, not account configuration: it
names no credential, no integration and no notification channel, which
is the fence that classification turns on. The eight sharing domains are
unchanged. Link and unlink stay bare, matching document link and unlink,
and the pair is revisited as one decision later.

Nothing is a required field. A visit saves with a date and nothing else.
Every id a body may carry is re-narrowed to the caller before anything
is written, and an unknown link id never blocks a save.

A booked visit mints exactly one reminder on the existing engine with
the new origin, and the appointment half is the part worth reading
twice. Both cadence columns stay null, which is the schema's one-shot,
so the first due instant is stamped directly and the never-nag property
is structural rather than guarded: after it fires, the cadence helper
has no occurrence to return. Rescheduling re-anchors that row and never
mints a second, which the tests assert by counting rows rather than by
checking the date moved.

Filing a visit as done closes the checkup it was filed against, on the
transition rather than on every later edit. Writing the test first found
that: satisfying is forward-only, so re-saving a completed visit was
pushing the checkup's next due date out again as if the person had been
a second time.

An appointment must appear on no preventive-care surface, and that is
four separate reads, one of them in the assistant tooling. Each carries
the exclusion, a guard proves all four by source text with a non-zero
match count, and the reminder mapper refuses such a row outright — so a
read site that loses its filter fails loudly instead of showing an
appointment as a checkup. The published origin enum is untouched.
2026-08-08 07:51:29 +02:00
Marc-André Bombeck 8f263e4767 feat(api): publish the mood dimensions and the day context on the wire
- /api/sync/changes carries a1 to a5 and the day context under the same keys
  the write path accepts, so a client reads back exactly what it can post
- BulkMoodEntry accepts both, all optional; a1 stays server-derived from the
  five-point label, so a build that sends only a label still writes a complete
  row and needs no change to stay correct
- the batch parses each entry's context on its own: one row carrying a value
  the vocabulary does not name is skipped and the rest of the batch lands
- docs/api/openapi.yaml regenerated alongside
2026-08-08 07:46:14 +02:00
Marc-André Bombeck 93495af788 feat(mood): compare the day context against the day's mood, with counts
- one comparison per context value, reusing the Welch test, the day floors and
  the Benjamini-Hochberg family the tag board already runs; a wide sweep
  filtered on a raw p < 0.05 would surface one-in-twenty noise as a finding
- two entries on one day count as one day
- every statement names how many days it compared, on the same surface as the
  claim, and says it shows a connection rather than a cause
- the assistant snapshot carries the same rows with that constraint written
  out beside them
2026-08-08 07:40:07 +02:00
Marc-André Bombeck 0474b7161d feat(mood): four context sections that cost nothing while closed
- work, contacts, leisure and one notable event, each a closed accordion with
  a count badge, on both the capture sheet and the edit dialog
- sleep, activity, vitals and the illness journal render read-only beside
  them, each row naming where its figure comes from and offering a way in to
  change it there
- the body line links into the illness module and captures nothing
- six locales for every label and every anchor
2026-08-08 07:30:26 +02:00
Marc-André Bombeck ba21c3a9bc Put both link families behind one service
Three narrow link tables landed with the visit record, which is a step
away from the one-shared-service direction the polymorphic-linking work
argues for. This bounds that step to a single module: every caller now
speaks one vocabulary — a source, a target kind, a list of target ids —
so replacing the storage underneath later is a change in one file rather
than a sweep across every route that files something.

The document-condition links move behind the same signature, so there
are two families and one call surface. Behaviour is unchanged and the
existing vault tests are the proof; where a test double had to follow
the new query shape, it says why in the diff.

The rules that used to live at each call site now live in the module and
are proven against real Postgres rather than a fake that ignores a
where clause: both ends re-read scoped to the owner before a row is
written, a repeated link is a success that changes nothing, a call is
capped at a hundred targets, and a tombstoned record is not linkable on
either end. Unlinking one deliberately still works after a delete, or a
filing nobody can clear would be left behind.

Reads return a resolved label and date rather than a bare id, so a
client rendering a list never re-derives what the server already knows.
The restore is the one documented exemption and writes the tables
directly: it rebuilds an account rather than filing something in one.
2026-08-08 07:26:14 +02:00
Marc-André Bombeck 1f609d42e0 feat(mood): resolve sleep, activity, vitals and symptoms at read time
- one resolver reads the day's figures from the modules that own them; nothing
  is copied onto the mood row, so correcting a sleep session corrects it here
  in the same moment
- absence answers { present: false } rather than zero, because a night nobody
  recorded and a night of no sleep are different facts
- a module switched off blanks its whole block instead of filtering down to an
  empty one
- keyed by the local day so the capture sheet can ask before an entry exists
2026-08-08 07:22:33 +02:00
Marc-André Bombeck 8eb36da228 feat(backup): carry the mood day context through export and restore
- the completeness guard now binds a third model, MoodContext, to a named
  select; the four omitted columns each carry the reason the backup is right
  to drop them
- the disaster-recovery arm carries the ciphertext, the portable arm the plain
  text, and every other column rides in both
- the restore rebuilds the context after its entry, inside the same
  transaction, and a file written before contexts existed restores without one
- the round trip asserts the restored row by value, zero included
2026-08-08 07:14:04 +02:00
Marc-André Bombeck 24425e9aff Add the visit record and the carriers that keep it
A person's whole 'which doctor' history was one free-text column on a
reminder: they typed the practice name once and could reach nothing else
that happened there. This turns that string into a record.

Five tables in migration 0320, all additive: an encounter that happened
or is booked, the account's own address book of practitioners, and three
links from a visit to the documents, lab results and conditions it
produced. The encounter is slim on purpose — the diagnosis stays on the
linked condition, the address on the linked practitioner, and the reason
each field was kept or cut is written at the model. No module gate, and
the schema says why rather than leaving the absence to be read as an
oversight.

Every carrier lands with the tables rather than after them. All five are
classified as travelling both ways and are proven doing it: a seeded row
of each goes out through the real export builder, the account is deleted
so the schema's cascade decides what survives, and the rows are counted
back through the real restore route. Two references deliberately do not
survive and are named instead of dropped quietly — the reminder a visit
points at is not in the backup, and a link whose far side a portable
export does not carry cannot resolve. The wipe plan deletes the links
before the lab results and documents they hang off, or the audit row
would report zero for rows that existed. The three encrypted columns are
registered for key rotation, without which dropping a legacy key would
make those notes permanently unreadable.

Widening the reminder origin enum is a type error at the reminder DTO,
which is the right outcome: the mapper now refuses an appointment row
outright rather than relabelling it as a checkup.
2026-08-08 07:14:02 +02:00
Marc-André Bombeck a25ec211cd feat(mood): capture and persist a mood entry's day context
- moodContextSchema derives every enum from the vocabulary, so a value it does
  not name answers 422 through returnAllZodIssues rather than being dropped
- the context is written in the same transaction as the entry and its links; a
  failure rolls the entry back rather than leaving a client retrying a 5xx
  into a duplicate
- an entry with nothing filled in stores no row, and a context that says
  nothing removes the one that was there
- the create, list, detail and edit reads answer the context with its lists
  decoded and its note decrypted; the ciphertext never leaves the server
2026-08-08 07:07:03 +02:00
Marc-André Bombeck dbfc0d8145 feat(mood): the closed context vocabulary and its six locales
- one module holds the four sections, their key lists and the rating fields;
  the Zod enums, the capture UI and the analytics all read it, so a value the
  vocabulary does not name cannot be stored
- labels state facts, never judgements, and the contact circles are groups of
  people rather than a score
- a pair guard binds the arrays to all six bundles in both directions, because
  the reverse-coverage matcher sees a `mood.context.` template and stops being
  able to tell a live label from a stale one
2026-08-08 06:57:36 +02:00
Marc-André Bombeck 7a4ee19c68 feat(mood): add the MoodContext sub-row and its encrypted note
- migration 0311 creates mood_contexts, keyed by the entry, cascading from
  both the entry and the owner
- work, contacts, leisure and one notable event; every field nullable, and an
  entry with nothing filled in gets no row at all
- notes_encrypted registered in ENCRYPTED_COLUMNS and in the rotation script,
  so a key rotation cannot strand it
2026-08-08 06:51:42 +02:00
Marc-André Bombeck 2f68b3dc79 Merge pull request #737 from MBombeck/release/v1.37.1
Release v1.37.1
2026-08-08 05:54:20 +02:00
Marc-André Bombeck 035ec054da chore(release): v1.37.1 — five mood values and the range the lab report printed 2026-08-08 05:38:56 +02:00
Marc-André Bombeck 89a749b811 Merge pull request #730 from MBombeck/refactor/settings-admin-one-piece
Settings and admin, one piece
2026-08-08 05:36:10 +02:00
Marc-André Bombeck c6246092ff Merge branch 'main' into refactor/settings-admin-one-piece 2026-08-08 05:20:04 +02:00
Marc-André Bombeck 9e89f3ec5d Merge pull request #736 from MBombeck/ci/e2e-shards
Run the browser suite as two shards
2026-08-08 05:18:30 +02:00
Marc-André Bombeck ea4d284cc9 ci: carry the report per shard and point the guard at the running job
The determinism guard reads the job that runs the browser, which is now
the shard matrix rather than the gate that only carries the required
check name. The report artifact is named per shard so the two uploads
cannot clobber each other.
2026-08-08 04:45:04 +02:00
Marc-André Bombeck 8045540b7e Merge pull request #735 from MBombeck/feat/mood-level-a
Five dimensions behind the mood check-in
2026-08-08 04:29:27 +02:00
Marc-André Bombeck 8494557a3a ci: run the browser suite as two shards
The single job passed at about eighteen minutes against a twenty-minute
cap, and the settings geometry measurements pushed it over, so the run
died at the timeout with everything to that point green. Same remedy as
the integration suite, split rather than raise: two Playwright shards,
each with its own database and production build, and a gate job carrying
the exact name branch protection requires that fails when any shard
failed or was cancelled.
2026-08-08 04:22:13 +02:00
Marc-André Bombeck 1e72b24477 Merge remote-tracking branch 'origin/feat/mood-level-a' into feat/mood-level-a 2026-08-08 04:02:53 +02:00
Marc-André Bombeck 5e1f5aa9ea refactor(mood): keep the trend windows in one place
The dead-code sweep found the window type exported and unread. It was
unread because the surface that offers the choice carried its own copy
of the same three numbers: the chart could not import the calculator's,
since that module reaches the database client two hops down and a client
component pulling it in would ship Prisma to the browser.

Both now come from the dimension table, which is pure by construction
and which the chart already imported. One declaration of 7 / 30 / 90,
read by the calculator that averages over them and by the control that
offers them, so the two cannot drift.
2026-08-08 04:02:34 +02:00
Marc-André Bombeck fec15e8fed Merge pull request #734 from MBombeck/fix/wipe-geo-truths
The admin wipe wipes, geo stays on the host, and two docs tell the truth
2026-08-08 03:54:02 +02:00
Marc-André Bombeck bd787daf8b Merge branch 'main' into feat/mood-level-a 2026-08-08 03:29:52 +02:00
Marc-André Bombeck cbf949d43a Merge branch 'main' into fix/wipe-geo-truths 2026-08-08 03:29:51 +02:00
Marc-André Bombeck 6dd70f532a Merge branch 'main' into refactor/settings-admin-one-piece 2026-08-08 03:05:27 +02:00
Marc-André Bombeck 9da876686d Merge pull request #725 from MBombeck/chore/transparency-ci
Scheduled CodeQL, Trivy and Scorecard workflows
2026-08-08 03:05:25 +02:00
Marc-André Bombeck 3dd79ec734 fix(mood): one spelling on the wire, one day-key helper, one written decision
Three small things the audit named together.

The mood reads spread the whole row, so adding the wire keys shipped
every level-A value twice — once as the column name and once as the key
the write path accepts. A client would have picked one and been stuck
with it. The column spelling is stripped now, and the create response's
key set is asserted so it stays stripped. The published contract is
unaffected either way; these routes are not in it.

The dimension series carried its own copy of the day-key subtraction
that the freshness module already exports. One copy now.

And the reason a stale dimension ships with a notice instead of being
dropped the way the status surfaces drop one is written at the builder:
a one-line card has nothing left to say about a value it cannot narrate,
while an open conversation can say when the value is from — and silence
there would leave no way to tell an unanswered dimension from one nobody
has looked at in a week.
2026-08-08 03:03:38 +02:00
Marc-André Bombeck 4db0f3a62a fix(mood): say which age governs a claim about a dimension
The snapshot stamps every metric block with an asOf built from the
newest reading in it, which for mood is the newest ENTRY on the 1-5
axis. Somebody who taps a face each morning and opens the sliders once
a week therefore carries a block stamped as current and a stress
reading six days old, and a reader taking the block stamp as covering
the dimensions states last week's answer as today's.

The block now names the precedence in one line beside the dimensions,
and each dimension keeps its own age. Present only when there are
dimensions to explain.
2026-08-08 02:57:40 +02:00
Marc-André Bombeck 0a39d50b05 fix(mood): stop offering to clear a value that cannot be cleared
An entry always carries a five-point label, so it always implies a
pleasantness value: the create path derived one from a null and the
capture sheet still showed a clear control for it, which meant a button
the server undid on the way to the database.

One rule on both routes now — a null asks for a value that cannot exist
and gets the derivation, on create and on edit alike — and the control
is gone for that field. The other four are genuinely optional and keep
theirs.
2026-08-08 02:55:08 +02:00
Marc-André Bombeck aa56246ba2 fix(backup): the restore states a level-A value only when the file has one
Matches what syncVersion, syncedAt and the row stamps already do a few
lines above: a key the file does not carry is a key the file predates,
not a key the file says is empty. Reachable when one file addresses the
same row twice, where the second entry now adds without erasing what
the first one set; an explicit null still clears.

Worth stating plainly, because the audit that asked for this expected it
to protect live rows from an older file: it does not, and it cannot. The
restore deletes the owner's whole mood partition before it rebuilds, so
by the time the update arm runs there is nothing live left to protect. A
test now pins that contract too, so nobody reads the omission as a
guard it is not.
2026-08-08 02:52:41 +02:00
Marc-André Bombeck d3577d2557 test(mood): cover the level-A blocks at the composition that ships
The staleness test rebuilds the block shape from the pure calculator, so
it proves the calculator and the freshness rule agree and nothing else:
hardcoding the freshness flag in the feature builder, deleting the
notice that goes with a stale value, or dropping the whole block left it
green. This calls extractFeatures against real rows instead.

Both failures were watched. With the flag hardcoded true the unit test
still reported four passing while this one named the six-day-old stress;
with the notice removed it named the missing instruction.
2026-08-08 02:48:53 +02:00
Marc-André Bombeck 370d703d03 Merge branch 'main' into chore/transparency-ci 2026-08-08 02:46:18 +02:00
Marc-André Bombeck 1c135dfe48 Merge pull request #726 from MBombeck/feat/lab-source-reference-ranges
Carry the reference range printed on the lab report
2026-08-08 02:46:16 +02:00
Marc-André Bombeck b9a6eeb1d7 fix(mood): a re-post no longer blanks the values it says nothing about
The single create's upsert restated all five columns on its update arm,
so a client re-posting an entry with only a label and a timestamp — the
phone, whose build has no sliders — cleared the stress, energy,
connectedness and stability somebody had answered on the web. The batch
and import paths already preserved them, so the two disagreed.

One answer now, and it is preserve: absence in a request means nothing
to say, an explicit null takes an answer back, and pleasantness still
follows the label because the request always carries one. The create
schema accepts the null that makes clearing expressible.

A re-post that omits a dimension is asserted to leave it standing, and
that assertion has been watched to fail against the old arm.
2026-08-08 02:45:31 +02:00
Marc-André Bombeck 94816d31a8 Merge branch 'main' into feat/lab-source-reference-ranges 2026-08-08 02:27:10 +02:00
Marc-André Bombeck abb0f2e82c Merge pull request #728 from MBombeck/fix/sync-range-validation
Sync writers refuse readings the app itself calls impossible
2026-08-08 02:27:08 +02:00
Marc-André Bombeck d764a084a7 Merge branch 'main' into fix/sync-range-validation 2026-08-08 02:08:02 +02:00
Marc-André Bombeck 3c6b1b7001 Merge pull request #727 from MBombeck/fix/mood-backup-completeness
The backup carries the whole mood entry
2026-08-08 02:07:59 +02:00
Marc-André Bombeck 5d98a98c21 refactor(mood): drop the orientation helper until something needs it
The inverse flag is read by the trend legend and by the assistant block;
the function that flips a value through it had no caller. It comes back
with the surface that needs a combined view, not before.
2026-08-08 02:07:21 +02:00
Marc-André Bombeck 0c017ba335 docs(changelog): note the five mood values 2026-08-08 02:05:50 +02:00
Marc-André Bombeck 30f35cfcaf Merge branch 'main' into fix/mood-backup-completeness 2026-08-08 01:48:51 +02:00
Marc-André Bombeck 77b3eaf10f Merge pull request #731 from MBombeck/fix/nanoid-advisory
Float nanoid past an infinite-loop flaw
2026-08-08 01:48:47 +02:00
Marc-André Bombeck 8084c97472 docs(score): state why daily mood stays out of the wellbeing pillar
The pillar reads PHQ-9, GAD-7 and WHO-5 and cites the papers behind
every threshold. A daily self-rated slider is now available on nearly
every mood row, so leaving it out reads as an omission unless the
reason is written down: the two are different kinds of evidence, and
averaging them would weaken the line that makes the figure worth
showing to a doctor. Recorded at the pillar and at the columns.
2026-08-08 01:44:50 +02:00
Marc-André Bombeck a6bb4f6577 feat(mood): give the assistant all five values, each with its own age
- the level-A blocks ride the mood aggregate the coach and the briefing
  already share, so the ages are fixed once in the data preparation
  rather than once per sentence
- every block carries its newest value, the day it belongs to, how old
  it is and whether that age still backs a present-tense claim, through
  the same freshness rule the vitals surfaces use
- a stale dimension carries the instruction in words as well as in a
  flag, because that is the sentence this exists to prevent
- the 1-5 scale line is untouched; the new axis describes itself, with
  the anchors resolved from the bundle the person read
- the trend page and the assistant run the same calculator, so a number
  in a sentence cannot disagree with the number on the chart
2026-08-08 01:43:32 +02:00
Marc-André Bombeck b4b39e9088 feat(mood): trend the five values on the insights page
- one engine: the dimension series is a sibling calculator of the mood
  aggregate hub and rides the same bounded read, so no second summary of
  mood can disagree with the first
- 7 / 30 / 90-day means per dimension, plus the daily series behind them
- a dimension nobody answered is named as not recorded rather than drawn
  flat through the middle of the scale, and a zero counts as an answer
- each line keeps the orientation the person answered in; the legend
  says which way the inverse one runs
- the card rides the existing module-gated aggregate read and query key
2026-08-08 01:34:59 +02:00
Marc-André Bombeck 42c2d8d140 Merge branch 'main' into fix/nanoid-advisory 2026-08-08 01:25:40 +02:00
Marc-André Bombeck 97582dedc0 feat(mood): capture the five values without lengthening the quick check-in
- the five faces are untouched: pick one, save, done in a tap
- a closed section below them opens onto five sliders; picking a face
  suggests a pleasantness value and moving that slider takes the
  suggestion over, while the face selection stays where it is
- an untouched slider writes nothing, and clearing one takes the answer
  back rather than leaving a middle value behind
- the list's edit dialog shows and changes the same five, so nothing is
  written on one screen and invisible on the other
- correcting an entry no longer re-derives pleasantness when the label
  did not move, which used to overwrite a hand-set value on any edit
- factor ratings are no longer offered on a new entry and nothing was
  deleted: existing ratings still render, edit and feed the crosstab
- six locales, and the dimension table's keys are declared dynamic
2026-08-08 01:24:04 +02:00
Marc-André Bombeck 1533afdc9d Merge pull request #733 from MBombeck/fix/cycle-test-evening-bomb
Pin the cycle fixtures' clock to the suite's clock
2026-08-08 01:18:34 +02:00
Marc-André Bombeck 7eaede257e feat(ui): add a slider primitive for bounded numeric entry
- Slider wraps the Radix control the way Switch and Progress already do;
  no new dependency
- SliderField adds the label, the value and the two scale anchors, which
  are what make a 7 mean anything
- a null value renders as unanswered rather than as the value the parked
  thumb sits on, and zero renders as the answer it is
- the announced text carries the scale, not only the number
2026-08-08 01:12:52 +02:00
Marc-André Bombeck 9e44c8754e feat(mood): carry the five level-A values through backup, restore and CSV
- the backup select and the payload carry all five, on both the portable
  and the disaster-recovery arm
- the restore writes what the file holds and nothing else: a file from
  before these columns restores them empty rather than deriving them
- the CSV appends them after the existing columns so nothing shifts under
  a spreadsheet, and an unanswered value is an empty cell rather than a
  zero, which is a real answer on this scale
- the round trip asserts each of the five by value, including a zero
2026-08-08 01:08:27 +02:00
Marc-André Bombeck cb12adcccf docs(security): correct the image publish trigger
The supply-chain section said the publish workflow runs on every push to
main. That trigger was removed in v1.4.34, when the squash-merge and the
release tag each kicked off their own build of the same SHA; the
workflow has fired on v* tags only since. Pull requests still build the
image, and do not publish it.
2026-08-08 01:06:24 +02:00
Marc-André Bombeck 0eac84aa95 fix(geo): read the offline databases first
The resolver queried the online provider first and read the mounted
GeoLite2 databases only when that missed. Every document describing the
feature said the opposite, including the self-hosting runbook and the
admin notification that tells an operator their login IPs are leaving
the server. So an operator who mounted the databases in order to stop
that egress kept all of it, and nothing said so: the location resolved,
the admin overview filled in, and the only difference was where the
address had been.

Now the local databases answer and the provider only ever sees an
address they could not place. A host with the City database mounted and
a hit makes no request at all — including when the ASN database is
absent, because reaching out for a carrier string would send the address
off the host anyway, which is the thing the mount was for.

IP_GEO_LOOKUP_DISABLED=1 remains the full off-switch: it disables the
online step only, so an offline hit still resolves and an offline miss
returns nothing rather than going online.

The wide-event warning on the fallback path named ipwho.is even when the
operator had pointed IP_GEO_LOOKUP_URL somewhere else; it now names the
host the runtime actually queries. The admin notification copy needed no
change — it fires only when the databases are absent, and then every
lookup does go online.

The two cases in geo-asn.test.ts that pinned the old order are the
watched red for this change.
2026-08-08 01:05:44 +02:00
Marc-André Bombeck ef35fe681d fix(admin): wipe every account's data, not nine tables
The admin "Delete all data" action carried its delete list inline. That
list named nine tables, which was most of the schema on the day it was
written, and it stayed at nine while the schema grew to a hundred and
twenty-two models. Laboratory results, documents, cycle logs, journals,
mood, workouts, sleep and Coach conversations all survived the wipe an
operator runs before handing a box on, and the toast said it was done.

The per-account wipe had the same defect and grew a derived plan for it.
The admin route now reads that plan: ADMIN_WIPE_MODELS is WIPE_MODELS
minus a single documented subtraction, so a model added to the schema
lands in both wipes at once.

- AccountGrant is the one difference, with its reason in the plan: it is
  the only access path to a managed profile, and this action preserves
  accounts by definition. Deleting every grant would leave records
  nobody can open, administer or delete.
- The audit history now goes with everything else. It is a record of who
  did what from where, which is exactly what clearing a box is for; the
  receipt written after the transaction commits replaces it.
- One transaction with the same budget as the account wipe. A
  half-applied wipe is worse than none, because the person is told it
  succeeded either way.
- The result line reports rows and tables instead of nine fixed names,
  which is how nobody noticed: it read the same whether the wipe had
  cleared nine tables or ninety.

Guards, both watched red before landing:
admin-data-wipe-completeness.test.ts fails when a user-scoped model
reaches neither the wipe nor a written exemption, and when the route
names a table inline again. The integration guard seeds every table in
the schema for two accounts, runs the route, and asks the database what
is left — drop one model from the plan and it names the surviving table.
2026-08-08 01:05:31 +02:00
Marc-André Bombeck 643d8a5a00 feat(mood): map existing entries onto the pleasantness scale
- the migration fills mood_a1 from the five-point label for every row
  that has none, and leaves the other four columns empty because there
  is nothing in a label to derive them from
- guarded on the column being empty, so re-applying the migration is a
  no-op rather than an overwrite of an answer somebody gave since
- the test reads the CASE arms back out of the .sql and compares them to
  the runtime map in both directions, so neither can drift alone
- rows are asserted by value after the statement runs, and again after a
  second run, including one hand-set value that must survive it
2026-08-08 01:03:05 +02:00
Marc-André Bombeck 0849d59ecf test(cycle): pin the fixture clock to the suite's clock
Two cycle suites compute their relative day keys with local Date arithmetic
under TZ=UTC while the routes resolve today in the user's zone, falling back
to Europe/Berlin when the fixture sets none. For two hours every evening the
two clocks disagree about the date and every day-of-cycle assertion is off
by one — the suite was red from 22:00 UTC to midnight and green the rest of
the day. The fixtures now carry an explicit UTC timezone so the test's clock
and the route's clock are the same clock at any hour. Reproduced red at
23:07 UTC, green with the pin at 23:19 UTC.
2026-08-08 01:02:08 +02:00
Marc-André Bombeck a1c78eceef feat(mood): derive pleasantness on every write path
- one helper resolves the level-A values for a write; the five writers
  call it instead of carrying their own copy of the derivation
- the create schema takes a1 to a5, and a value the user set wins over
  the derived one; the batch request shape is untouched
- both arms of both upserts restate the values, so a re-post cannot
  leave a stale reading beside a mood that has since changed
- the JSON import derives from the row's own label rather than the
  file's score, which is the one place the two can disagree
- correcting an entry's label re-derives pleasantness the way it
  re-derives the score; an explicit null takes an answer back
- a round trip through all five writers against real Postgres asserts
  the rows agree and that nothing invents the other four values
2026-08-08 00:49:15 +02:00
Marc-André Bombeck 4bbf4c6d10 ci: three integration shards, not two
Two shards cleared in about fourteen minutes on a quiet day, but with six
pull requests running side by side the larger shard hit the same 25-minute
guard the split was meant to escape. Three shards keep the biggest slice
around sixty files, which clears the guard with real headroom on the
slowest runner observed. The gate job is unchanged.
2026-08-08 00:38:51 +02:00
Marc-André Bombeck ad4f5c04f0 feat(mood): add the five level-A columns to the mood entry
- migration 0310 adds mood_a1, stress_a2, energy_a3, connection_a4 and
  stability_a5, all nullable, no table rewrite
- the schema comment states the four things a later reader needs: score
  keeps its 1-5 axis, the columns are queryable plaintext on purpose,
  stress is stored literally, and a read delegate sees them by design
- the backup guard is red until the carriers land alongside
2026-08-08 00:37:41 +02:00
Marc-André Bombeck 9a390aacea feat(mood): add the level-A dimension table and the A1 derivation map
- MOOD_DIMENSIONS carries the five self-state dimensions in capture order,
  each with its column, its label and anchor keys, its orientation and its
  0-10 bounds
- getA1ForMood maps the five-point label onto the pleasantness scale once,
  so the quick check-in stays a full-value capture path
- only stress is inverse-oriented, and a test pins that count
- the secret scan reads a dotted message key on a *Key field as a token;
  allowlist the dimension keys the way the existing message keys are
2026-08-08 00:36:09 +02:00
Marc-André Bombeck e532210b21 Merge branch 'main' into refactor/settings-admin-one-piece 2026-08-08 00:06:26 +02:00
Marc-André Bombeck e000556751 Merge branch 'main' into fix/sync-range-validation 2026-08-08 00:06:25 +02:00
Marc-André Bombeck 45cae42774 Merge branch 'main' into fix/mood-backup-completeness 2026-08-08 00:06:24 +02:00
Marc-André Bombeck 72c5181218 Merge branch 'main' into feat/lab-source-reference-ranges 2026-08-08 00:06:22 +02:00
Marc-André Bombeck aa1b875597 Merge branch 'main' into chore/transparency-ci 2026-08-08 00:06:21 +02:00
Marc-André Bombeck c2f67c96d4 fix(deps): float nanoid past an infinite-loop flaw
A fresh advisory names nanoid below 3.3.17: a custom generator can loop
forever when asked for a zero-size id. It reaches the tree only through
next and postcss, but the audit gate rightly blocks on a known HIGH with
a fix available. Bounded override in the established pattern; the audit
drops from one high to none.
2026-08-07 23:58:34 +02:00
Marc-André Bombeck 93980ac7a1 Merge pull request #729 from MBombeck/fix/integration-shard
Run the integration suite as two shards
2026-08-07 23:57:28 +02:00
Marc-André Bombeck fb8723ebb5 ci: run the integration suite as two shards
The suite outgrew its runner. The 25-minute guard was sized for 128 files
taking about 13 minutes; the sharing release took the suite to 180 files and
past the cap on CI runners, so every run died at the timeout with every test
to that point green, reported as cancelled. The guard's own rule applies:
split, don't raise.

The files run as two vitest shards, each with its own Postgres testcontainer.
A gate job carries the exact name branch protection requires and fails when
any shard failed or was cancelled, so a half-green matrix cannot satisfy it.

vitest is invoked directly because pnpm passes the -- separator through to
the script literally: the flag never applied through the script form, and
both "shards" ran the full suite. Proven by paired local runs: the script
form ran 180 files twice, the direct form splits 90/90 with 927 plus 689
tests, all green.
2026-08-07 23:39:12 +02:00
Marc-André Bombeck 8eb9408813 fix(settings): give the Layout sub-pages the back-link they were built with
Measuring the seven `/settings/layout/<child>` routes was meant to pin the
back-link spacing. It found there was no back-link to pin.

`SettingsHubBackLink` and `settings.sections.layout.backToHub` have existed
since the sub-pages were split out, and the only thing that mounted them was
the shell's slug FALLBACK — the branch that runs when a page passes no
`heading`. These pages pass an explicit one, so the fallback never ran and no
child route has painted a back-link since. The component was written, the
string was written, the reverse-coverage guard saw a call site and was
satisfied, and the way back to the hub was not on the page. Two ends, no pipe.

It now comes from the page, where the heading it belongs to comes from.

The geometry spec grows the seven routes and a second family. A route with a
back-link carries an extra row above the title, so it is taller by
construction; comparing it against a plain route would report structure as
drift. Each family is checked for its own constant heading top, and the step
between the back-link and the title is asserted at 6 px — `PageHeader`'s
documented `space-y-1.5`, which is what the shell's hand-rolled `space-y-6`
would have drifted back to.

Measured, both languages: plain routes 24.0 px, back-link routes 51.0 px,
spread 0.0 px in both families, step 6.0 px on all seven.

The back-link is also painted twice, once per breakpoint, so the measurement
picks the copy with a box — `querySelector` returns document order, which on
a desktop width is the hidden mobile one, and reading it reported no
back-link at all.
2026-08-07 23:39:05 +02:00
Marc-André Bombeck 272c426bea fix(ui): close the holes the audit found in this work's own guards
Every item here is a check that could pass while the thing it checks is
broken, or a margin the sweep's codemod could not reach.

Guards:

- The access-payload matcher accepted `.level` on ANY object. A chart's zoom
  level or a log record's level would have satisfied it and reported a
  consumer that does not exist. It now names the bindings the entry actually
  arrives under; a third binding is a deliberate edit rather than a silent
  widening. Re-falsified: rename both readers, it goes red.
- The `pl-7` sweep skipped any line CONTAINING `//`, so a class string sharing
  a line with a URL was waved through. Only the part after a real line-comment
  marker is exempt now. Proven by putting `pl-7` on a line with an
  `https://` comment: caught.
- `LEGIT_IDENTICAL` in the English-leak guard had no staleness check, unlike
  both of its siblings, and carried two dead keys — one from a removal long
  before this work, one from the duplicated version fields that came off
  `/admin`. Both pruned, the check added, falsified with a made-up key.
- `split-description.mjs` split inside `z. B.`, `d. h.`, `u. a.` and `p. ex.`
  and produced a head ending mid-abbreviation. Both halves have to be caught,
  which is why the rule is a shape (single letter + stop) rather than a list,
  and the merge re-tests its own tail. Exercised against eight cases including
  the ones that used to break.

Margins the codemod could not see, because the child lives in a different
component from the card that spaces it: six form roots under managed record
settings (one of which also carried the banned `space-y-5` step), the
low-stock status line, the avatar card's explainer, and the backups restore
report. Each was adding a margin on top of the card's own gap.

Two facts the text diet cut too close, both restored inside the guideline:
that an excluded injection site wins over a medication that prefers it, and
that the privacy card's second button leads to a full health record.
2026-08-07 23:20:39 +02:00
Marc-André Bombeck 23eae2823e refactor(i18n): shorten the five descriptions the gate could not see
The gate the diet shipped with matched `<SettingsCardHeader` in three
component folders. That is not where every card description lives, so five
real ones were outside its reach — including the full backup's, which the
sweep's own shortlist had named and which stayed at 351 German characters
across three sentences while the guard reported zero violations.

Two ways in were missing. A card header can sit in a folder the walk never
entered (`labs`), and a description can be FORWARDED to the header by a shell
— `ExportCardShell`, `ImportCardShell` — where the prop is on the shell's tag,
not the header's. The gate now matches both, over seven roots, and the
"finds what it is meant to check" floor moved with it.

`SubPageShell` is deliberately not included, with the reason written at the
list: its description renders as `text-foreground text-sm`, the body tier,
where the standards allow prose. Gating it would enforce a rule §3 does not
make for that tier.

The five, all six locales:

- full backup — the twelve-item enumeration was the description. It is now
  the card's opening body paragraph, where a list of what is in the file
  belongs; the description is one sentence.
- local OCR — the how-it-works sentence stays in the slot; "less accurate,
  review every value" is safety copy and reads foreground in the body.
- CSV import, dose-history import — second sentence to the body.
- the ECG page — the "does not interpret the waveform" claim gets its own
  paragraph rather than riding the page explainer.

Proven by reverting the full backup's text: the widened gate reports it as
both two sentences and over length, at the call site, in both languages. The
old gate could not see the key at all.
2026-08-07 23:20:12 +02:00
Marc-André Bombeck ff61aec51f fix(e2e): repair the two integration-card assertions the sweep left behind
Both ends of the divider removal were green and the pipe between them was
never run. The `<hr>` came out of every integration card, all three unit
tests were updated to expect none, and this browser spec kept asserting nine.
It is the same shape as the failure this project keeps rediscovering: two
correct halves and nothing exercising the assembly.

The cost was not just a red spec. The Pixel-5 horizontal-overflow assertion
sits AFTER it in the same test, so `/settings/integrations` had no proven
mobile-overflow check for the whole sweep — the test never reached it.

The second assertion read a sentence's bytes and broke on the text diet while
the thing it was about — the card rendering its explainer at all — never
changed. `SettingsCardHeader` now names its description slot
(`data-slot="settings-card-description"`) and the spec targets that: the slot
is present, non-empty, and not a raw i18n key. The product name stays
assertable because a proper noun is not prose. The wording itself is pinned
where it belongs, in the unit test that reads the same bundle it renders from.
2026-08-07 23:19:24 +02:00
Marc-André Bombeck 2941d56238 fix(sync): enforce the plausibility domain on every provider write path
Every interactive path, every import, MCP and Telegram checked an incoming
measurement against VALUE_RANGES before storing it. The provider sync writers
did not, so a decode slip or a glitched sensor landed a row the application
itself calls impossible, and every mean, median and personal band derived from
it inherited the impossibility. Filtering the read side hid the row. It kept
landing.

The gate is one module reading the domain the app already declares, applied at
two kinds of seam. reconcileExternalMeasurement is the shared identity writer
for Polar, Oura, WHOOP, the Withings sleep leg, the Apple export importer and
the batch endpoint, so gating there means a provider added later inherits the
refusal rather than having to remember a check it never knew about; the new
rejected_range verdict carries no row, which is what makes the compiler force
every caller to handle it. The five writers that hold Prisma themselves gate at
their entry, before the existence probe decides insert versus overwrite, so an
impossible reading can no longer replace a good stored value.

An out-of-band value is dropped. Not clamped, because a clamp invents a reading
nobody took. Not stored behind a flag, because a quarantined row is still a row
and every consumer would have to learn the flag. Not fatal to the batch, because
one bad sample must not strand the run's other readings behind a held watermark.
Absence reads as absence.

A silent drop, though, is indistinguishable from a provider that sent nothing,
so every drop is tallied on the wide event under measurement.range_rejected with
the metric, the provider and the edge it broke. Counts only: the reading itself
is health data and never enters the log line, and the direction plus the
metric's own declared bound is what a diagnosis actually needs. The tally
accumulates rather than replacing, because a provider gates once per resource
leg and the reconciler once per row. One warning per provider lifts the event to
warn so a drop does not hide inside a green line.

A structural guard enumerates all twenty measurement writers with the reason
each is allowed to write, so a new one has to answer the question before it
ships. scripts/diagnose-implausible-measurements.ts reports the rows already
stored, aggregated per metric and source with no value beyond the bucket's own
extremes. It repairs nothing: whether a stored impossible row is a decode slip
or a band that is too narrow is not a call a script gets to make.
2026-08-07 22:19:43 +02:00
Marc-André Bombeck 5a103ea096 test(e2e): measure that Settings and Admin read as one surface
Thirty-four routes, both consoles, English and German, desktop and phone.
The claims this program makes are geometric, so they are checked with
geometry rather than by looking at screenshots.

What it found, which is the reason it exists:

- `SettingsCard as="section"` sat one spacing step tighter than its
  neighbour on every desktop width. The `<Card>`-backed variant inherits
  `gap-4 md:gap-6`; the landmark variant wrote a flat `gap-4`. Seventy-five
  of eighty-six cards measured 24 px and eleven measured 16 px, directly
  above and below each other. The expected value in the spec is a function
  of the viewport for exactly this reason — a constant would have agreed
  with whichever half it was written against.
- One German page subtitle wrapped to a second line where English fit on
  one. Shortened in all six languages.

After both: heading top 24.0 px on every route, spread 0.0 px, in both
languages and at both widths — that is the no-jump claim, measured. Card
header-to-body distance equals the card's own gap on all 86 cards, and no
card body sits off the card's inner edge.

The header's HEIGHT is pinned only where one line is achievable. At 393 px a
70-character sentence needs about 380 px of column, so most explainers wrap
there; the spec asserts the wrap away at desktop width and only forbids a
third line on a phone. The alternative is truncating the sentence, which is
the defect this program removed.
2026-08-07 22:16:31 +02:00
Marc-André Bombeck 8c5ed74bc0 docs(changelog): note the mood restore fix 2026-08-07 21:51:30 +02:00
Marc-André Bombeck 9388f1d032 test(backup): round-trip a mood entry through the real restore
Seeds an entry with a ticked tag, a rated factor, an encrypted note, a
non-Berlin timezone and a sync counter above zero, exports through the real
builder, restores through the real `POST /api/admin/backups/[id]/restore`,
and reads the row back out of Postgres. Values, not a payload shape: this
repository has already proved that asserting a `moodEntries` key stays green
with the restore call excised.

Two more cases beside it. A hand-written payload in the shape files were
written in before the note, zone, counter and tag keys rode along — the
compatibility floor, and the only way to know it holds is to send one. And a
ticked tag this instance cannot resolve, which has to come back named in the
skip report rather than silently absent.

Seen red three times on the way in: re-adding the tag-link filter loses the
ticked tags, dropping `tz` from the restore write loses the zone, dropping
the note ciphertext from the payload loses the text. Each reverted and the
file's hash checked back to its recorded value.
2026-08-07 21:44:01 +02:00
Marc-André Bombeck fd2bd67ff3 feat(labs): keep the reference range a report prints beside a value
A lab runs its own method on its own device, so the window a physician
evaluates a value against is the one printed next to it on that report,
not a catalog band averaged over every lab. Reading a report pulled the
value and dropped that range: the extraction asked for it, the commit
handed it to the biomarker resolver, and the resolver only uses it when
it mints a NEW marker. For every analyte the user already had — the
normal case after a first panel — the printed range was read and then
thrown away.

Add `sourceReferenceLow` / `sourceReferenceHigh` / `sourceReferenceText`
to `LabResult` and carry the range from the report to the reading. The
text is stored whether or not numbers can be read out of it, because
"bis 5,0" and "negativ" state a window too; a range that could not be
parsed is kept verbatim, never replaced with invented bounds.

`resolveEffectiveReferenceRange` is the one place the precedence lives:
the source window wins for that single reading, and the catalog stays
the net for readings without one. A printed string with no derivable
bound does not displace the catalog. Every surface that judges a
reading routes through it — the API verdict, the doctor report, the
insights blocks and per-marker assessment, the coach snapshot, the MCP
read and the FHIR `referenceRange` — so a value cannot read in range on
one surface and out on another.

The API keeps `referenceLow` / `referenceHigh` as the window in force,
so a client that reads only those two renders the right range and the
right verdict with no change of its own; the catalog band, the source
window, its origin and a divergence flag ride alongside for clients
that want to show both.

Read side: the chart draws the source window as a second, visually
distinct band with the reading it came from named beneath it, the
reading rows name the printed range and the catalog band where the two
disagree, and the doctor-report PDF prints the report's own string with
a footnote naming the saved range. Entry side: one optional field on
the lab form, folded away until asked for, and the printed range is
editable on the scan review screen.

The range parser covers the notations German and English reports
actually print — two-sided, one-sided, comma or dot decimals, thousands
separators, trailing units — reads units without ever converting them,
and refuses to guess on anything ambiguous.
2026-08-07 21:40:41 +02:00
Marc-André Bombeck 18edd34c33 fix(backup): restore the mood note, zone, counter and binary tags
`moodEntrySchema` gains `note`, `noteEncrypted`, `tz`, `syncedAt`,
`syncVersion`, `createdAt`, `updatedAt` and `structuredTags`; every one of
them optional or defaulted, so a backup file written before this parses
unchanged and restores exactly as it did.

The restore writes them. The note follows the measurement pair: ciphertext
verbatim when the file carries it, a portable file's plaintext re-encrypted
on the way in, legacy column null either way. `tz` absent still means the
legacy Europe/Berlin reading, which is what those rows meant. `syncVersion`
comes back at the value the file recorded — restoring at the default handed
the next round to any paired device holding a higher number, and the device
would then overwrite the recovered entry with what it had.

The link rebuild re-creates both arms: rated factors from `factors`, ticked
tags from `structuredTags` with a NULL rating. An unresolvable tag key is
reported under its own `moodTag` family, beside the rated one, because an
operator needs to know which of the two an entry lost.
2026-08-07 21:37:06 +02:00
Marc-André Bombeck 222047e0d4 fix(backup): carry every mood column and both tag arms
The disaster-recovery payload dropped the free-text note, the row's
timezone and the last-writer-wins counter, and the tag-link read filtered
`rating: { not: null }` — which is the definition of a BINARY link, so
every present/absent tag a person picked was missing from the file too.

Both arms now mirror the measurement pair: the recovery arm carries the
note ciphertext verbatim plus `tz`, `syncedAt`, `syncVersion`, `createdAt`
and `updatedAt`; the portable arm carries the decrypted note, `tz` and no
ciphertext.

BINARY keys ride in their own `structuredTags` array rather than as a
nullable rating inside `factors`, because a restore resolves `factors`
against RATED tags and names what it cannot resolve — a rating-less entry
there would collide with both. Absent means empty, so a file written
before this parses and restores exactly as it did.

The two link arms partition the links exhaustively: a malformed link comes
back named as unresolvable instead of falling between them.
2026-08-07 21:13:42 +02:00
Marc-André Bombeck 1bdc5ea4ee test(backup): bind MoodEntry to a named backup select
The mood read was an inline `include`, so nothing could compare it to the
model the way `measurement-backup-completeness.test.ts` compares the
measurement select. Name it — `MOOD_ENTRY_BACKUP_SELECT` and
`MOOD_ENTRY_TAG_LINK_SELECT` — and add the sibling guard that binds both
to `prisma/schema.prisma`.

The mapper's parameter is spelled `moodEntry` rather than `e` because the
guard proves a column reaches a payload by matching `: moodEntry.`, and `e`
is also the intake-event mapper's parameter one section above: a matcher on
`: e.` would match across both and could never fail.

The guard is red as it stands, and names the defect: `note`,
`noteEncrypted`, `tz`, `syncedAt`, `syncVersion`, `createdAt` and
`updatedAt` are selected and written to no payload. The fix follows.
2026-08-07 20:57:58 +02:00
Marc-André Bombeck ba0cd63cf5 refactor(i18n): a description is one sentence, in all six languages
Measured before the sweep: 317 description and hint strings under the
`settings` and `admin` namespaces, median 83 characters, 113 of them two
sentences or more. The rule the design standards now carry is one sentence,
guideline 120 characters, and this is the sweep that makes it true.

Almost nothing was retranslated. A second sentence is already written in
every language — it is just in the wrong slot. `scripts/split-description.mjs`
cuts a description at its first sentence boundary in all six bundles at once
and either drops the tail or files it under its own key; the twenty-one keys
that moved now render in the card body as foreground `text-sm`, which is
where multi-sentence prose belongs and where a reader can actually read it
(the slot is muted `text-xs`). Eight tails were dropped outright, because
"Off by default" under a switch, "Topics and frequency are adjustable" above
the topic switches, and "Only admins can create invitations" on an
admin-gated route are not information.

Twenty-eight keys are gone: the privacy page's intro, which was a table of
contents for the four cards under it; two About descriptions that listed
verbatim the labels and the buttons beneath them; a card description that
repeated its own title; the API-token sentence that said what the paragraph
below it said with the actual instruction; and the eight integration
secondary sentences. Six descriptions were rewritten shorter in all six
languages where trimming was honest rather than lossy.

On the strings that changed: 4391 characters of English down to 2290, and 32
multi-sentence descriptions down to zero.

The rule is now a gate. `card-description-length.test.ts` reads the keys that
actually reach a card header's description slot — statically, from the JSX —
and checks them in EN and DE, because a rule that only holds in English
produces a slot that wraps to two lines in half the locales. Its exception
list is empty and carries a reason requirement plus a test that removes a
stale entry. Verified by putting a second sentence back: it fails.
2026-08-07 20:53:05 +02:00
Marc-André Bombeck b713ed8c34 Score the supply chain against the OpenSSF criteria
Most of what Scorecard looks for this repository already does: Actions
pinned by commit SHA, a security policy with a private reporting path,
Dependabot with auto-merge, keyless signing on the release image, a
branch-protected trunk. The value is not the score, it is that the checks
keep running after the person who set them up has moved on, and that
anyone evaluating the project can read the result without being given CI
access.

publish_results is on, which is what makes the score citable. It reads
repository metadata and the workflow files; nothing about the code or its
contents goes anywhere. The token is an OIDC exchange, the same mechanism
the release workflow already uses to sign the image.

No badge in the README yet. The public API has no entry for this
repository until the first run publishes one, and the badge URL currently
renders 'invalid repo path'. It goes in once there is a score behind it.
2026-08-07 20:14:04 +02:00
Marc-André Bombeck 460049bf67 Scan the lockfile with dev dependencies and the published image, daily
Two questions the existing scans cannot answer.

The dependency audit runs with --prod, which is the right scope for a
blocking gate but leaves a gap: a dev dependency can still ship. pdfjs-dist
is the case that made this concrete. It sits in devDependencies, and
rasterize-pdf.ts imports it at runtime, so standalone output tracing copies
it into the production image where the prod-scoped audit has never looked.
Trivy reads 627 packages out of pnpm-lock.yaml without --include-dev-deps
and 1455 with it; pdfjs-dist is only in the second set. Trivy's help text
lists the flag as npm/yarn/gradle only, but it works on the pnpm lockfile
too, which is worth knowing before someone deletes it as a no-op.

The container scan builds the image from the current main. Nobody runs
that image. What self-hosters pull is the one built from the last release
tag, and an advisory published after the tag lands against an image
nothing is about to rebuild. So the second job scans ghcr.io/mbombeck/
healthlog:latest instead of a local build.

Schedule only, no push or pull_request trigger, because the change-
triggered half is already covered and would just run twice. The lockfile
job reports into code scanning without failing: widening to dev
dependencies surfaces transitive tool advisories by the dozen, and a red
badge from day one gets muted inside a week. The image job fails on
CRITICAL, after its own report has been uploaded by a separate step.
2026-08-07 20:13:54 +02:00
Marc-André Bombeck dde45c76a6 Run CodeQL against the TypeScript tree
Static analysis was the one class of check the pipeline had no answer for:
lint catches style, the type checker catches shape, the tests catch
behaviour, and nothing walked the data flow from an untrusted input to a
sink. This is GitHub's default setup written out as a workflow file, so the
query suite, the excluded paths and the schedule sit in the diff rather
than behind a settings toggle.

Pull requests and a weekly run on the default branch. No push trigger:
everything reaches main through a pull request that was already analysed,
and the weekly run is what keeps the Security tab current.

src/generated is excluded. Extracting the 9 MB Prisma client costs minutes
and can produce nothing anyone would act on, because the fix for anything
found in there is to regenerate it.
2026-08-07 20:13:39 +02:00
Marc-André Bombeck 8a1585a391 Merge pull request #723 from MBombeck/fix/cycle-correctness
Cycle correctness: overdue verdicts, backfills, deletes that leave no torso
2026-08-07 19:58:39 +02:00
Marc-André Bombeck 330f60115a refactor(admin): the console speaks the Settings vocabulary without an accent
Twenty-six of twenty-eight admin files already used the Settings card and
header. What made the console read as its own system was everything on top of
that: three hand-rolled cards, a header slot that meant five different things,
and a heading the frame took but never painted.

- `SectionFrame` drops `title` and `subtitle`. Seventeen call sites passed
  both into a component that has rendered neither since v1.18.6.1 — the shell
  reads the same keys itself. A prop contract nothing honours is a promise the
  next reader believes.
- The invite card, the four host-metric headers, and the `/admin` welcome
  card stop hand-rolling `bg-card border rounded-xl` shells with their own
  padding steps and their own heading weights. `text-sm` as a card title on
  the first card of a page, directly above a correct one, was the first thing
  the eye landed on.
- The header status slot carries status. The backups run, the invite create,
  the danger-zone wipe, and the user filters come out of it; the app-log
  refresh stays but reads as the secondary it is.
- Loading states paint their card and header. Encryption returned a bare
  spinner row and then a card, so the section jumped when the status landed —
  the fix `coach-feedback-section.tsx` already carried, applied where it was
  missing. Same for the notification-status card.
- One label/value tile. `StatusItem`, the encryption section's private `Stat`,
  the user-management inline panels and the backups upload box were four
  fills and three paddings for one role.
- The overview stopped printing the running version, build SHA and build time
  twice, thirty pixels apart. The version tile owns build identity — it is the
  one that checks for a newer release; the snapshot owns what is running.
- `ai-server-key` had three paragraphs stacked in a muted `text-xs` slot;
  one sentence stays there and the two that carry information move into the
  body as foreground. The central-codex consent copy moves the same way, and
  its disconnect is `variant="destructive"` — which `ConfirmButton` refused to
  accept, so every destructive confirm in the tree had been hand-tinting an
  outline instead.
- Leftovers: the `-mt-2` correcting the card's own rhythm, two alpha hovers on
  text, `text-[10px]` badges, the redundant `space-y-6` wrapper, the empty
  state repeating the header's CTA, and the `mt-6` a card added inside a
  frame that already spaces its children.
2026-08-07 19:55:47 +02:00
Marc-André Bombeck b2e1aa0cde refactor(settings): one header, one action row, one integration card
The sweep that follows from the primitives. Nothing here is new behaviour;
every change removes a second way of saying something the surface already
said one way somewhere else.

Headers. The two collapsible security cards stop rebuilding
`SettingsCardHeader` by hand to carry a chevron — the chevron rides inside
the title button, and the description moves out of the collapsed region, so
the first paint is no longer a bare title. The import card shell, the export
and import section headings, and the four free-standing group headers stop
inventing their own type scale: a heading above a GROUP of cards is
`SectionHeading` (`text-base`), a card title is `SettingsCardHeader`
(`text-lg`), and the step between them is what says which is which. The
targets card gets a title instead of a naked icon.

Actions. Every card-level row is `SettingsCardActions`. The primary action
comes out of the header's status slot in six cards (password, web push,
pillar order, coach memory, and the two danger-zone triggers) and out of the
middle of the card in three more; the reset that hung in the dashboard-layout
header joins save as a secondary in the same row. Result and status lines
move ABOVE the row — sources' cross-link, the invite form's two status lines
— because nothing follows a card's actions. Revoking a share link is
`variant="destructive"` rather than an `outline` hand-tinted red in two
different ways. The import row had four variants for four buttons; it has
two. Export downloads are the card's primary, not an outline link.

Integrations. One description sentence with the setup-guide link inline: the
second paragraph was byte-identical across six of eight cards, which is the
tell that it said nothing about the provider it sat under. The `<hr>` under
the header — which existed only in this folder — is gone. So is the hint that
pointed at a guide 40 px above it, and the second format for "not
configured". Connect is one button everywhere: primary, `sm`, in the action
row, instead of primary-and-small in three cards and outline-and-large in
four.

Plus the standards leftovers the audit listed: two `pl-5` list gutters, one
`scroll-mt-20` anchor, a purple header icon, `text-[10px]` badges, four
hand-rolled callout shells that `SettingsInfoTile` already paints, and the
two inline buttons that never had the mobile tap floor at all.
2026-08-07 19:39:11 +02:00
Marc-André Bombeck 3778e70ff5 Merge pull request #720 from MBombeck/fix/handover-p1-batch
Four data fixes: backfilled doses, impossible readings, stale today-claims, sleep units
2026-08-07 19:32:40 +02:00
Marc-André Bombeck ce9b2814e6 feat(dashboard): reach shared records from the account switcher, not a card
The "looking after" block sat directly under the greeting and above this
account's own day, permanently, for anyone with a single shared record. The
dashboard is this account's day; other people's records are a destination,
and the account switcher in the top bar and the sidebar already is that
door — with the same access level and record kind on each entry.

Drop the card, its test, and the five strings only it used, across all six
locales.

The access-payload consumer guard named that one component as the reader of
`level` / `sections` / `recordKind`, so it went red on the deletion, which is
what it is for. It now names the surfaces that actually adopt those fields —
the presentation resolver and the switcher — and matches the property access
rather than one variable name, so a rename of the binding cannot make it
match nothing and pass. Verified by removing every reader: it fails.

Adds `scripts/i18n-key-tool.mjs` for dropping or rewriting a key across all
six bundles in one go.
2026-08-07 19:24:46 +02:00
Marc-André Bombeck 5445bfc1f1 refactor(ui): give Settings and Admin one card rhythm and one page header
The two consoles used the same primitives and still read as two systems,
because everything without a primitive had drifted: the header-to-body
step existed in three competing techniques at once (`mt-4` on the first
body child, `space-y-4` on the card, `mb-4` on the header), the body
started either at the card edge or 28 px in, and both shells hand-rolled
the page title instead of calling `PageHeader`.

Move the decisions into the primitives so a call site cannot re-open them:

- `SettingsCard` is gap-based like `Card` (`flex flex-col gap-4`). The
  header-to-body step is the container's, not a margin somebody remembers.
  A dense card still overrides the gap on the card itself.
- The body starts at the card edge. `pl-7` is gone — off the spacing scale,
  and it mis-aligned action rows against their own forms wherever two
  neighbouring cards disagreed about it.
- The card header's description slot loses its `space-y-1`. That was the
  licence call sites used to stack explainer paragraphs into a muted
  `text-xs` slot; the slot holds one sentence.
- New `SettingsCardActions`: one action row, trailing edge, last thing in
  the card. `align="start"` spells the one exception, a card whose only
  actions are links out.
- New `StatTile` replaces four hand-rolled label/value boxes in Admin.
- `SectionHeading` moves from `insights/` to `ui/`. It is the heading above
  a group of cards, which is what Settings needs; Settings had been using a
  card header with no card, which reads as a card that failed to paint.

Both shells now render their heading through `PageHeader`, which gained
`headingAs="div"` for the second copy each shell paints (mobile above the
nav strip, desktop inside the grid) so only one is a real `<h1>`. The
page explainer is muted everywhere: the primitive said foreground, the
standards and every hand-rolled copy said muted, so pages disagreed with
each other. Medications, Vorsorge, the labs / custom-metric / illness
detail pages and the clinician view drop their hand-rolled title blocks
too, including the mid-word truncation on the medications subtitle.

Tests pin the parts that can be checked exactly: the card's gap, the
description slot's missing rhythm, the action row's two alignments, the
`<h1>`-free shells, and a sweep asserting `pl-7` stays gone.
2026-08-07 19:05:15 +02:00
Marc-André Bombeck 1f4b8f43dc Merge pull request #721 from MBombeck/feat/workout-hr-profile
Show the whole workout heart-rate profile
2026-08-07 19:01:51 +02:00
Marc-André Bombeck 7669868479 refactor(measurements): drop the entry-unit helpers nothing calls
`hasEntryUnitConversion` and `canonicalValueToEntry` shipped beside the
hours-to-minutes conversion for an editing surface that does not exist and has
no ticket. Neither has a caller, so both were only two more things to keep
true, and the dead-code gate is right to say so.

The module comment claimed the inverse was there so a future surface could not
land on a different answer. It says what is actually true now: one direction,
one place. The git history keeps the rest if that surface ever arrives.
2026-08-07 18:32:38 +02:00
Marc-André Bombeck 626ec203ac Merge branch 'main' into fix/cycle-correctness 2026-08-07 18:24:37 +02:00
Marc-André Bombeck 61501500b9 Merge branch 'main' into feat/workout-hr-profile 2026-08-07 18:24:35 +02:00
Marc-André Bombeck 384992bb15 Merge branch 'main' into fix/handover-p1-batch 2026-08-07 18:24:33 +02:00
Marc-André Bombeck 00e8d05235 Merge pull request #724 from MBombeck/fix/handover-ui-batch
Dialog overflow, a coach dot with nothing behind it, and six smaller surface fixes
2026-08-07 18:23:44 +02:00
Marc-André Bombeck 092edced9f test(e2e): open the mood sheet's full form before measuring it
The mood sheet opens on the five-face quick check and reveals the rest of
the form, timestamp row included, once a face is picked. The dialog-overflow
spec measured the quick check instead, found no date field, and failed on
its own readiness gate rather than on the layout — a guard that cannot reach
the state it is about proves nothing either way.

It now picks a face and waits for the annotate panel, which is the state the
report describes.
2026-08-07 17:14:41 +02:00
Marc-André Bombeck 381a07a134 Merge pull request #722 from MBombeck/fix/e2e-goto-race
Wait for the record switch to land before driving the next page
2026-08-07 17:12:23 +02:00
Marc-André Bombeck 190941944c fix(insights): let the lab-comparison card age out, and give its delta the row's tier
Two things about the card that shows what changed since the last panel.

The comparison had no expiry. Someone whose newest panel is years old was
still reading "since your last panel" about a draw from another year — not
stale UI state but a stale sentence, and one the app kept repeating on the
overview every day.

The window is a year, applied to the data rather than to a per-user
dismissal. A year because routine panels are commonly drawn annually, so a
shorter window would hide a comparison that is genuinely the newest thing
somebody has for months out of every year, while past a year the wording
cannot be defended at all. Doing it on the data means nothing to
acknowledge, nothing to persist, no housekeeping asked of anyone, and one
answer for every client through the existing absent contract — the card
already un-mounts on it, and so does anything else reading that route.
Verified in both directions over the real endpoint.

The delta on the right was muted at the smaller size, the same typography
as the meta line under the analyte, so it optically hung off that lower
line and the row read as bottom-aligned even though it measures centred to
the pixel at every width. A delta is the number the row exists to report,
so it takes the content tier, and the cell states its own centring rather
than inheriting it.

The existing cases pinned their clock at the same time: fixed fixture days
against a relative window is a test that passes until a date in the future
and then fails for reasons unrelated to the code.
2026-08-07 16:52:24 +02:00
Marc-André Bombeck 41faf165ee refactor(anamnesis): give each lifestyle entry a proper action row
The three entries stacked two full-width buttons under the value — a
disabled grey Save above a red-outlined "Remove smoking status" — so each
one read as a slab of controls with the same weight as the field it
belonged to, and scanning them ran the two labels together.

Each entry now ends in one right-aligned action row: the quiet destructive
first, the primary Save last, both at the mobile tap-target floor. The
remove control drops the field name from its visible label, which the
Label directly above already carries, and keeps the full phrase as its
accessible name and in the dialog it opens — so three of them side by side
stay distinguishable to a screen reader. Six languages.

Follows the card action-row convention: primary bottom right, secondary
beside it, nothing after the row.
2026-08-07 16:45:17 +02:00
Marc-André Bombeck d7a95874c2 fix(coach): centre the composer text in its input pill
On a phone the placeholder sat noticeably low. The composer row was
bottom-aligned so the send button would stay beside the last line as the
textarea grows, but that also bottom-aligned a single-line textarea against
a 44 px touch target: 7 px of space above the text and 1 px below.

The row centres its textarea now and the controls keep their own bottom
alignment, so both properties hold. Measured empty, one line and four
lines, phone and desktop: the single-line gap goes 7/1 to 4/4 on a phone
and 2/1 to 2/2 on desktop, and the multi-line case is unchanged with the
send button still level with the last line.
2026-08-07 16:39:50 +02:00
Marc-André Bombeck c60aa6f9b1 refactor(settings): fold the profile-photo format line into its description
The accepted formats and the size limit were a caption of their own under
the upload buttons, so the card read as an explanation, a control, and then
a second explanation. They now finish the sentence that says what the card
does, which is where someone looks before choosing a file rather than
after. Same two strings, six languages unchanged.
2026-08-07 16:39:50 +02:00
Marc-André Bombeck 72cd21352c refactor(mental-wellbeing): shorten the intro and drop the mood-history link
The intro listed all four instruments with their subject in brackets and
then explained itself, which ran to two lines on a desktop header and five
or six on a phone — a paragraph to read before reaching the four cards that
say the same thing. It keeps its opening claim and the one caveat that
matters, and loses the enumeration the cards below already carry: one line
on desktop in all six languages, measured at 1280 and 1440.

The pointer to mood history at the foot of the page is gone. The link on
the mood page pointing here stays, because that direction earns its keep:
someone logging a mood may not know the screeners exist, while someone who
came here for a screener knows where their diary is.
2026-08-07 16:36:31 +02:00
Marc-André Bombeck 06dd7343c2 fix(settings): point the empty delivery-status card at a place, not a direction
The card told people to add a channel "below". A position is only true
while nothing above or below it moves, and the same card already reads as
the first thing in its group, so "below" says less than the group's own
name does. It now names Delivery channels, which stays true wherever the
card is rendered.

The card's title and its per-channel description were still English in
Spanish, French, Italian and Polish while the strings around them were
translated; they are translated now too. Six languages.
2026-08-07 16:31:10 +02:00
Marc-André Bombeck 82490870e5 fix(coach): make the launcher's dot mean a message you can read
The Coach button showed its unread dot over an empty conversation, and
opening the Coach neither showed anything nor cleared the dot.

Two paths fed one indicator. The nightly sweep flipped a "remind me"
reminder from active to due and stopped there — no conversation, no
message, and `surfaced` had no writer at all. The launcher lit its dot off
a second query that asked only whether anything was due. So the dot
promised content that was never written, and because opening the Coach
clears the message-based signal and not the reminder one, the only way out
was to resolve the reminder in Settings, which nothing on the badge
suggested. A reminder minted for a plan review put a user who had never
typed in the Coach in exactly that state.

The sweep now writes the reminder into the user's Coach thread as a real
assistant message and marks it surfaced in the same transaction: no
message, no status change, and nothing to point at. The badge derives from
that message like every other proactive one, so opening the Coach shows the
note and clears the dot. The launcher's second query is gone.

Reminders an older build left stuck on due are picked up by the same pass,
so an indicator that has been sitting on an empty conversation resolves
into the message it always implied.

No provider call and no push: the body is a deterministic localized
template around the user's own note text, six languages.

Proven end to end against Postgres — the row exists, the badge reads that
row, opening clears it, a second tick writes nothing, and a failed write
leaves the reminder untouched with the badge dark. All five fail against
the previous sweep.

The second indicator in the report, under the bottom bar's overflow entry,
is the active-route marker for that group and not a badge.

Refs #715
2026-08-07 16:29:58 +02:00
Marc-André Bombeck eb5c8a91fb fix(ui): keep date/time pickers inside their dialog
The add and edit surfaces could be scrolled sideways and the time picker
sat past the right edge: measurements, mood, the medication intake editor
and the cycle log sheet all showed it, so the cause is in what they share.

Two mechanisms, both in shared primitives.

DateField and TimeField wrap a text input. A flex item's min-width:auto
resolves to a content-based minimum, and for a text input that is its
intrinsic size attribute — 20 characters, about 180px. Neither field could
render below ~230px whatever width the parent offered, so the date + time
row demanded ~470px inside a 400px dialog body and pushed the clock button
58px past the edge. min-w-0 on the field box and on the overlay input
releases that floor; the row now fits at every width from 360px up.

The scrolling body only declares overflow-y. CSS promotes the other axis
from visible to auto, so every deliberate outward bleed in the tree turned
the form into a pannable surface — SheetSection's trigger row was 8px wider
than its own container for no benefit (a focus ring already draws outside
the box), and Switch's hit-target pseudo reaches 13px past the track. The
bodies and the dialog surface now state overflow-x explicitly, the section
trigger no longer bleeds, and the dialog's grid column is pinned so an
over-wide child cannot drag the surface out with it.

Measured before and after on the four reported surfaces at 360 / 390 / 430
/ 768 / 1280 / 1440: the date/time row spilled 83px on every width from
640px up and none of it remains.

An e2e spec asserts the two harms directly — the surface is not a
horizontal scroll container, and no focusable control lies outside its
visible box — with a canary that proves the reachability check can fail.
2026-08-07 16:23:31 +02:00
Marc-André Bombeck 34be5b4554 test: wait for a record switch to land before navigating away from it
Entering or leaving a record is a server write followed by
window.location.assign, so the click that starts it returns long before
the document it produces exists. The switcher helper returned there, and
everything a test did next raced the app's own navigation.

Both ways of losing that race are silent. A goto issued into the gap is
cancelled when the assign commits, which Chromium reports as
net::ERR_ABORTED and which is what CI saw twice. Or the goto wins, and
the page it lands on belongs to the caller's own record, where a route
that is ungranted in somebody else's record is simply granted: /coach
opened in that gap issued all four of the protected reads the test
asserts never happen. The second is the worse outcome, because the
assertion was reading the wrong record and could as easily have passed
there.

Neither is visible in the DOM the click leaves behind, which is why
waiting on the banner cannot settle it: the document on its way out
already shows whatever the next assertion looks for, so the wait returns
at once and proves nothing. A marker on window can settle it, because a
document replacement is the one thing that destroys it. If the navigation
never happens the wait fails, which is what a switch that did not land
should do.

Both helpers use it now, so the retry that was added downstream of
leaving a record has nothing left to absorb; it stays, because the claim
there is that the record survives the round trip rather than that one
navigation attempt wins.

Reproduced before fixing, under CPU contention at CI's worker count:
three of six runs flaked, showing both faces. Six of six clean at the
same contention afterwards, then twenty consecutive runs of the file and
the whole sharing set, none flaky.
2026-08-07 16:15:54 +02:00
Marc-André Bombeck 85240e96b1 fix(cycle): route the new save signals through the shared affordances
Two repo-wide guards caught the additions rather than a reviewer, which
is what they are for.

The success toasts reached for sonner directly. The success affordance
belongs to the outcome module, which binds it to the success key and
nothing else, so a surface cannot raise a green toast for a write that
wrote nothing. They go through toastWrittenOutcome now.

The sheet's date header formatted a day key in the browser's zone. A
cycle day key is a calendar day, not an instant, so it is anchored at
noon UTC and rendered in UTC, the same anchor the domain's day
arithmetic uses. Otherwise a reader east or west of the browser zone
could see the sheet name a different day than the one it writes to.
2026-08-07 16:14:28 +02:00
Marc-André Bombeck 8e3834f38d fix(cycle): count the cycle day from the logged start, not the grid window
The day count was the length of the labelled run inside the calendar
grid, so the same day read as day 11 over a month and day 23 over three:
the run was cut off at the window's edge rather than at the cycle's
start. That was a latent contract question while every caller asked for
the same ninety days, and it stopped being latent when the month grid
began reading its own month, which is thirty days by construction.

The verdict now anchors on the period start the record holds and falls
back to walking the grid only when no caller supplied one, so the ring's
arcs stay grid-derived (they are about what can be drawn) while the day
is about what the person logged. The overdue ceiling then measures the
real elapsed count too.

Covers D-list edge 15, both shapes: a window that clips the run and a
window that excludes the cycle start altogether.
2026-08-07 15:57:21 +02:00
Marc-André Bombeck 47d41a13f4 docs(cycle): say why the fertile window is seven days, not six
The constants make ovulation minus five through ovulation plus one, and
the comment above them claimed a six-day window. Wilcox's six days are
the five before ovulation plus the day itself, measured against a KNOWN
ovulation day. Ours is estimated, usually by back-calculating a luteal
length from a median cycle, so a window drawn tight to the estimate
loses its last day whenever the estimate lands early, and the ovum stays
viable for most of a day after release besides.

The direction is decided by who reads the window. It is surfaced to
people trying to conceive and to people avoiding it, and for the second
group a window one day short is a window that misses. The constants keep
the conservative reading and the comment now states it, with the note
that changing either one is a coordination matter because the iOS client
reimplements the same spec.

The width is pinned by a test rather than left to be re-read off the
numbers the code already uses.
2026-08-07 15:53:55 +02:00
Marc-André Bombeck 30cf1da1d3 chore(cycle): add a read-only report for records the module stopped reading
Two defects put a record into a state that looks, from the app, like no
period was ever logged. Both are fixed going forward; neither repairs
the rows already made, and neither is visible from the surface it broke.

A closed torso is a live cycle carrying an end date with no live cycle
after it. A cycle is closed by its successor, so closed with no
successor means the successor is gone, and a record whose last cycle is
closed has no open cycle for the engine to forecast from. The signature
is exact and needs no audit trail.

A period with no cycle row is bleeding that only ever existed as a
day-log, from the flow chips, the bulk drain or an import. The engine
reads cycle rows, so the record holds periods and reports none.

The report imports the bleeding-day rule from the write path rather than
restating it, so it and the app cannot drift on what counts as a period
start. Checked against seeded records: it names the torso, names the
three flow-only starts while passing over a day two and a spotting day,
and says nothing about a healthy record.

Nothing is written.
2026-08-07 15:52:59 +02:00
Marc-André Bombeck 3596720905 fix(cycle): let a period logged as flow count as a period
MenstrualCycle rows were only ever written by the one-tap period
boundary. Every other way of recording bleeding wrote a day-log and
stopped there: the log sheet's flow chips, the bulk drain, an Apple
Health export full of menstrual-flow samples. The engine reads cycle
rows, so a person could log every period they had and the module still
held that none had happened. No cycle length, no forecast, an empty
chart, and an offer to log a first period. An Apple Health user who
never found the one-tap button had the whole module dead.

A first bleeding day now opens the cycle it belongs to, through one
shared seam in the day-log write helper, so the single capture, the
bulk drain and the Apple Health fold all infer a start the same way and
the one-tap boundary's own write lands on a date that already has a
cycle, which the rule declines.

The rule is conservative, because a false start corrupts every length
derived after it. Spotting does not open a cycle: it is as often the
tail or the herald of a period as its first day. Bleeding flagged as
between periods does not, since that flag exists to say so. Neither does
a bleeding day within the hard physiological minimum of an existing
start, which is what keeps day three of a period, or a forgotten day
two, from starting a cycle of its own without needing a contiguity
check. A genuinely short cycle is not inferred from flow alone; the
one-tap start still opens one on any date.

An edit is symmetric. Setting a flow opens the cycle; clearing it, or
flagging it as between periods, removes the cycle that day opened and
re-opens the one before it. A cycle that an edit can create and not undo
leaves the record holding a period nothing on the day says happened.

- the period route's start arm and the flow inference now share one
  boundary helper, so a start means the same thing however it is entered
- back-dating re-anchors both neighbours, as the one-tap start does
- integration: eleven cases through the real routes, of which five are
  about what must NOT open a cycle
2026-08-07 15:50:23 +02:00
Marc-André Bombeck 029edfa358 Merge pull request #719 from MBombeck/fix/pdfjs-cve
Umove the PDF renderer past a script-execution flaw
2026-08-07 15:29:12 +02:00
Marc-André Bombeck bd6089734d fix(cycle): let the month grid read the month it is showing
The page reads one window anchored on today, ninety days back and half a
year forward, and the month grid navigates freely past it. A month
outside the window came back with no days: the cells still rendered
(they come from the month, not the read) and still opened the log sheet,
and the write behind it still landed, because the period route is built
for back-dating and re-anchors the neighbouring cycles for it. What did
not happen is anything visible. Saving an April flow in August closed
the sheet onto a month the read never carried, so the entry looked like
it had not been made, and entering it again did not help.

The grid now reports the month it moved to and gets its own bounded read
for it. The anchored window is untouched, because every other surface on
the page means today and the route caps a span at 400 days, so a union
with a month two years back would simply be refused.

A write also says so now. Saving, deleting and both period boundaries
raise a confirmation; the sheet's inline strip already named a failure.
Between the invisible month and the silent success there was no way to
tell a save that worked from one that never happened.

The sheet header carries the date it is writing to, and the one-tap
boundaries drop the word today when the day is not today. It always
wrote to the selected date; saying otherwise made a correction read as a
mistake.

The gear beside the log button is gone. It was a second door to the tab
directly below it and no other page carries one in that corner.

- calendar days carry isCycleStart, so the delete dialog can say that
  removing this day removes the period start with it
- window arithmetic is a pure module with its own tests, including the
  400-day span the anchor cannot be widened past
- integration: a day 111 back is written, is absent from the anchored
  read, and comes back complete on a window over its month
- new strings in all six languages
2026-08-07 15:20:29 +02:00
Marc-André Bombeck ed274de0a0 fix(cycle): keep the cycle day when the phase band is withheld
The cold-start gate suppresses the calendar's phase band until three
cycles are observed, because a population-framed phase word off one or
two of them is not earned. The verdict read the day count off those same
labels, so the gate took the count with it: a record holding three
logged period starts resolved INSUFFICIENT_DATA and rendered an empty
ring under an offer to log a first period.

The count is not the claim the gate is about. It is the number of days
since a start the person entered themselves. The verdict now takes that
start from the cycle rows and falls back to counting from it whenever
today carries no phase, with the same overdue ceiling and no phase
claim. INSUFFICIENT_DATA is left for the case that really is one: no
period start on record at or before today.

The sheet's day header was already written for this state and could
never reach it — it renders a bare day number when no phase is
trustworthy.

- verdict round trip covers the still-learning day count and its overdue
  side through the real route
- unit tests pin the anchor path, the absent-from-grid path, and that a
  future-dated start is not a cycle anyone is in
2026-08-07 15:05:50 +02:00
Marc-André Bombeck 6db2f6f9ae fix(cycle): make removing a period start restore the neighbour it moved
Opening a cycle closes the one before it: the start write stamps the
previous cycle's endDate and lengthDays, and a back-filled start takes
its own end from its successor. Nothing undid any of that. Deleting the
start left the previous cycle as a closed torso holding an end date from
a cycle that no longer existed, and a record whose last cycle is closed
has no open cycle to forecast from — the prediction went away and there
was no way to bring it back from the app.

Both removal paths now re-derive the boundary from the cycles that
remain: a cycle ends the day before the next one begins, and with no
next one it is open again. That is a re-derivation rather than an undo
log, so it is correct for a history that came from an import or a
restore, and running it twice changes nothing the second time.

Deleting the day-log that opened a cycle now removes that cycle too.
The one-tap start writes both rows and the log sheet's delete is the
only way the web offers to take it back; leaving the cycle standing was
how the broken state survived the undo.

- soft-delete and re-anchor run in one transaction
- the audit row names the neighbour's moved boundary, the only part of
  the write the tombstone cannot reconstruct
- round trip through the real routes: photograph the cycle rows, log the
  start, remove it either way, compare field by field — including that
  the forecast comes back
2026-08-07 15:03:10 +02:00
Marc-André Bombeck c5a471f7fa fix(cycle): keep counting an open cycle past the predicted period start
The engine ended the open cycle's phase window at the predicted next
start, so the day after a missed forecast carried no phase at all and
the verdict resolver read that as today falling outside every known
cycle window. An ordinary three-days-late period therefore reported
INSUFFICIENT_DATA: no cycle day, no phase, an empty ring and the words
insufficient data, while the reminder cron was pushing a period-confirm
prompt for the same day. OVERDUE was only reachable when the engine
itself forecast a cycle longer than the grace window.

The open cycle now runs to the predicted start or through today,
whichever is later, and stops the moment the next start is logged. The
count is bounded on the far side where it already was: past the typical
length plus its grace window the verdict degrades to OVERDUE and says
how late the period is.

The extension pins the open cycle's ovulation anchor to the predicted
length. Left to the span, an unconfirmed ovulation is back-calculated
from the window's own length, so a window that grows with the delay
would walk the estimate and every phase boundary drawn from it.

- buildPhaseCycles, phaseForDate and buildPhaseDayMap take the user's
  today; the insights route and the coach snapshot pass it
- verdict round-trip covers the predicted start day, three days past it,
  past the grace window, and the case where a new start closes the run
2026-08-07 14:58:53 +02:00
Marc-André Bombeck cea330bf70 Say when a session has heart-rate figures but no profile behind them
The heart-rate card hid itself whenever the server resolved no curve.
That is right for a session with no heart rate at all, but wrong for the
common case it also covered: a ride logged from a chest strap through a
provider that reports an average and a peak and nothing in between. The
stats grid shows those two numbers, the card next to them renders
nothing, and the page reads as if it has no heart-rate section rather
than as if the shape behind the numbers is not on record.

Three states now. A curve when there is one; a named absence when the
session carries heart-rate figures without a profile; nothing at all when
nothing was ever measured, since there is no absence to report there and
an empty card would be a shell.
2026-08-07 14:51:13 +02:00
Marc-André Bombeck 0c99c27bfc Keep the workout heart-rate axis on the readings it plots
The min-to-max envelope shipped as a stacked pair: a transparent base at
the bucket minimum plus a `max - min` delta above it. Stacked series are
measured from zero — recharts derives a stacked axis domain from the
stack offsets, whose baseline is 0 — so a chart asking for `dataMin - 10`
resolved to -10 rather than to the bottom of the band. A session spent
between 120 and 170 bpm was drawn on a -10 to 180 axis and the shape of
the effort, which is the entire point of the curve, squashed into the top
quarter of the plot. It only happened on the dense sessions the envelope
gate lets through, which are the ones with the most shape to lose.

The band is now one range area over the bucket's own `[min, max]` pair.
No stack, so the domain stays on the bpm values that are in the data.

The axis domain is computed rather than inferred, because the session's
peak has to be inside it: recharts discards an out-of-range reference
line instead of clamping it, and a reported peak is a single reading
while the curve plots bucket means, so a peak marker over a data-derived
domain would go missing on most sessions that have one.

Adds that peak marker alongside the average one, both labelled, and reads
the envelope back in the tooltip as the spread it is. The mapping moves
into a pure module so the values the axis sees can be asserted without
mounting recharts.
2026-08-07 14:50:03 +02:00
Marc-André Bombeck 2f14379066 Carry the workout heart-rate curve to the end of the session
`durationSec` is a denormalised duration, and not every source reports
the elapsed one. Strava sends `moving_time` while the row's `endedAt` is
`startedAt + elapsed_time`, so a ride with twenty minutes of stops
carries a duration twenty minutes shorter than its own span. The curve
folded against that duration, which dropped every reading after the
moving-time mark: the tail of the session vanished with no gap and no
marker, and the detail page showed a complete-looking profile of an
incomplete session.

Fold over the span instead, with the duration as the floor for rows
whose `endedAt` is not after their `startedAt`. The bucket width tracks
the span too, so a stop-heavy ride keeps the same on-screen density as a
continuous one of the same length.

The reconstruction path also gets an integration suite over the real
route and a real Postgres. Two boundaries decide whether it is honest
and neither was provable against a mocked client: the query pads by five
minutes so a boundary reading still lands in the first or last bucket,
and a reading inside that pad must not extend the curve past the finish;
the measurement read is owner-scoped, and another account's pulse at the
same minute must not enter this curve. Both fixtures place a reading on
the far side with a bpm value no in-window reading has, so a leak shows
up in the numbers rather than only in a count. Verified by breaking each
boundary in turn and watching the matching assertion fail.
2026-08-07 14:41:24 +02:00
Marc-André Bombeck 315ca5e67c fix(deps): move the PDF renderer past a script-execution flaw
pdfjs-dist 6.1.200 and a transitive 5.6.205 both sit in the affected range
of a flaw that lets a crafted PDF run JavaScript inside the renderer. The
document vault feeds it every uploaded PDF, so pin the direct dependency to
6.2.108 and add a bounded override so the transitive copy lands there too.
The override stops short of pdf-parse's 5.4.296, which predates the flaw and
drives the local text-extraction path.

The runtime image ships every pdfjs-dist copy in the store, not just the one
that gets loaded, so an unused transitive copy still counted.

Hoisting in the image picked whichever copy the filesystem listed first, and
more than one copy reaches it, so the version named in package.json was not
reliably the one the renderer resolved. Carry the resolved version forward
from the build stage, select it by name, and fail the build when it is
missing rather than leaving another copy in its place.
2026-08-07 14:35:23 +02:00
Marc-André Bombeck d97e3c0976 fix(measurements): store a hand-entered night in the unit the field asks for
The manual sleep field is labelled in hours. The column stores minutes, because
that is what every sync source delivers and because a single stage segment is
only a few of them. The form sent the typed number straight through, so a night
entered as 7.5 was filed as seven and a half minutes and the list showed eight
minutes of sleep.

Nothing rejected it. Seven and a half minutes is inside the column's
plausibility band — a stage really can be that short — so the entry looked
accepted and the loss was silent.

Both ends were already right: the field says hours, the list formats minutes as
hours and minutes. The assembly between them was where the factor went missing,
which is why the round-trip test runs the whole of it — the form's conversion,
the shipped POST, the stored row, and the formatter the list paints with.

The storage unit stays minutes. The conversion sits at the entry boundary in
one place with its inverse beside it, so a future editing surface cannot land
on a different answer, and it rounds to whole minutes rather than storing
437.99999999999994 for 7.3 hours.

The value field also lost "7,5" outright. `type="number"` sanitises a decimal
comma away on the engines that do not localise the field, so the entry arrived
as an empty string with no explanation, and `parseFloat` would have read it as
7 on the engines where it survived. The field now takes the same shape the labs
and custom-metric fields use — a numeric keypad and a submit path that reads
the comma — so every decimal metric on the form gains it, not only sleep.

`scripts/diagnose-manual-sleep-hours.ts` lists the rows already stored this
way. It reports and does not repair: an eight-minute stage and a night typed as
eight hours are the same number in the same column, and only the person who
entered it knows which it was.
2026-08-07 14:30:10 +02:00
Marc-André Bombeck dfd9b4679b fix(insights): stop making claims about today out of older readings
The hero line said a pulse was well above its 30-day average today. Nothing
had measured a pulse for five days. The day-signals card flagged the same
reading, and the baseline-drift card said the value was above the usual range,
present tense, on a day that held no reading at all.

One class, and it sits in the data preparation rather than in any of the
sentences. Each surface was handed "the freshest stored value" with no notion
of when it was taken, so each of them assumed now. The age was reachable — the
aggregates carry `newestDaysAgo` inside their coverage object — but it read as
a statistics footnote rather than as the fact that governs the tense of every
sentence about the metric, and none of the three consulted it.

A reading is material for a claim about today when it comes from today or from
yesterday. One day rather than zero: a vital taken at 23:40 and read at 00:10
is the same reading it was half an hour earlier. Two is not, because by then a
whole day has passed with nothing in it and the sentence would be describing a
gap.

The rule now lives beside the data. The vital deviations carry the age of the
reading they were computed from, and the two deterministic consumers apply it:
the day-signals flag counts only current vitals toward its count, and the
baseline-drift card surfaces only current deviations. Stale vitals stay in the
list with their age, so the anatomy view still shows them and nothing silently
disappears; the dated level shifts were never today claims and are untouched.

For the narrated surfaces the same fact is stamped onto every metric block of
the Coach snapshot before anything reads it, so the age travels with the
numbers into the hero, the briefing, the Coach reply and the retrieval tools
instead of each of them guessing. A block narrated off a stale series also
lands in the wide event, which is where it should have been visible all along.
2026-08-07 14:24:13 +02:00
Marc-André Bombeck 4563bce5b3 fix(insights): keep impossible readings out of the personal band
The baseline-drift card reported a pulse in the hundreds of millions against a
usual range in the tens of thousands. Neither figure is a heart rate, and both
came from the same place.

The application declares a plausibility domain per metric, and every
interactive, import, MCP and Telegram write validates against it. The
derivation layer did not ask. So a single stored value outside that domain — a
provider unit-decode slip, or a row from a writer that never had the gate — was
folded into the day mean, carried by the median into the band, and then held
against itself as "currently". The two numbers in the sentence were wrong by
different amounts, which is why the line read as nonsense rather than as an
exaggeration.

Both readers now refuse a value the application has already declared
impossible: the per-day means behind the band, and the latest-day mean the
deviation reads. A day left with no plausible reading contributes nothing
rather than a fabricated point, and the vital drops out of the comparison — the
coverage floor already knows how to report an absent day. The rollup branch
applies the same rule to a bucket mean, since the rollup writer averages
whatever is stored. Everything downstream of `readDayMeanSeries` inherits it,
which is every consumer of the usual range: the band strip, the drift card, the
changepoint detector, readiness, trajectory, the coach read.

The card also printed raw doubles. Each figure now renders at the metric's own
decimal precision through the shared formatter, so a mean reads as a number
rather than as a float and follows the reader's number convention.

Left open, and recorded for a separate pass: the provider sync writers do not
enforce the domain on the way in, so the impossible rows keep landing.
2026-08-07 14:16:17 +02:00
Marc-André Bombeck 4e9e8649ec fix(medications): record the slot a backfilled dose names
Marking a missed dose taken from the Verlauf ledger showed the row flip to
taken and then fall straight back to missed, with the entry nowhere on the day
it was made for.

The ledger posts the displayed slot's own anchor as `scheduledFor` and means
"record THIS dose". The route resolved the slot by window band from `takenAt`
instead, which answers a different question: which slot the recording moment
falls into. Backfilling an older slot matches no band, so the write fell
through to the standalone insert and landed as an ad-hoc row anchored at the
recording moment. The named slot stayed unserved, the optimistic row was
overwritten by the authoritative refetch, and the dose sat under today with no
sign of where the user had put it.

A named instant that is a real slot of this medication now decides the binding,
validated against the same band anchors the "diesem Slot zuordnen" pin uses, so
an arbitrary client instant still records ad-hoc. A slot that lies ahead of the
take is still refused by the existing forward guard, so a late-morning dose
cannot consume the evening slot. When the naming and the clock disagree the
binding rests on the user's choice, so the row stores it as such and the read
ledger anchors it there rather than dropping back to ad-hoc; an ordinary
on-time take resolves to the same anchor either way and is untouched.

The tests drive the shipped POST and the shipped dose-history GET, and assert
the persisted row and the ledger read back from it.
2026-08-07 14:03:09 +02:00
Marc-André Bombeck d5f176ac4d Merge pull request #718 from MBombeck/release/v1.37.0
v1.37.0 — share part of a record, or keep one for somebody with no login
2026-08-07 13:45:19 +02:00
Marc-André Bombeck f49defbc34 fix(documents): do not check a close that deliberately kept its selection
Maximizing the Coach drawer hands the conversation to /coach and carries
?doc= with it, so browser-Back can rebuild the sheet. That is the one
close-shaped transition whose whole point is to LEAVE the selection where
it is, and the close path has always returned early for it.

The dropped-traversal check added beside that close did not know. It saw
a closed sheet and a selection still in the address bar, which is exactly
the state it exists to repair, and it repaired away the return URL a
quarter of a second after the close had deliberately preserved it.
Whether it won that race was a question about how fast the machine
navigated, so it surfaced as one flaky run on the narrow viewport rather
than as a broken feature.

Both sides read one named predicate now, and the check is skipped when
the close kept the selection on purpose. Proved by driving the grace
window to zero, which is the worst case the timer can have: before, the
maximize never even reached /coach, three attempts out of three; after,
it passes there and the whole documents family passes with it. Twenty
consecutive runs of that family on the narrow viewport are clean.
2026-08-07 13:15:23 +02:00
Marc-André Bombeck 9849a369a1 docs(changelog): record the stuck-hold fix
Half a minute on a spinner with two tabs open is a user-visible defect in
a release whose subject is exactly that surface.
2026-08-07 12:13:15 +02:00
Marc-André Bombeck 6ec78d2ec4 test: wait for the cached entry the disk-layer control asserts
The service worker writes its data-cache entry after the response has
been handed to the page, so a shell that is ready is not evidence that
the write has landed. Reading the cache once therefore sampled null on a
loaded machine, and the positive control failed saying there was no entry
about a cache that was about to have one.

Polled on the entry itself. It waits for the signal rather than for a
number of milliseconds, and it still fails if the entry never appears,
which is the whole reason the control is there.
2026-08-07 12:12:51 +02:00
Marc-André Bombeck 65531c359a fix(sharing): stop a switch mistaking its own reconcile for a foreign one
The scope mirror is watched so a switch this browser did not begin still
holds every shell until /me reconciles it: another tab on an older
bundle, the referential action behind an account deletion, an operator.
It recognised its own by comparing the mirrored scope against the scope
it was switching to, and that is not a true test. fetchMe mirrors
whatever record the server currently reports and it runs DURING a switch,
both when postSwitchWithReconcile reconciles a lost compare-and-set and
when a second tab reloads beside the initiator. At that moment the server
still reports the record being left, so the write did not match and was
read as somebody else's switch.

What followed was silent. A foreign write publishes a new transition id,
and every terminal call opens by checking the id it was handed, so the
commit that followed was dropped without a trace and the expected scope
was left naming a record no /me would ever confirm. Nothing could release
the hold, and both tabs sat behind the hydration gate until the stored
transition aged out thirty seconds later.

That is the intermittent browser failure that has been carried through
three rounds as a canary and never explained: a peer reload racing a
switch, a gate that never lifts, and a run forty-six seconds long made of
a fifteen-second wait and a thirty-second one. On the selection that
provokes it, eight runs failed three times before and twenty failed none
after, and the runs that used to take fifty-seven seconds now take
twenty-five.

A write is foreign only when nothing of this browser's own is in flight.
Ignoring it while held costs nothing, because a held browser is already
in the state that branch would install. The rule is a named function so
it can be checked in a suite that has no DOM, and the property the guard
exists for is pinned beside it: a response that disagrees with a
committed scope is stale and still must not release.
2026-08-07 12:12:39 +02:00
Marc-André Bombeck ad094cba4d docs(changelog): record the document-close fix
It is a user-visible defect in a release that ships the surface it lives
on, so it belongs in the entry rather than only in the commit that fixed
it.
2026-08-07 10:27:22 +02:00
Marc-André Bombeck 53ffbfdec4 test: give the two sharing probes instruments that cannot fail by themselves
Both failed on CI and neither failure was about the product.

The loading-state scan held /api/auth/me open with a fixed sleep in the
route handler. Three things follow from that and all three are wrong: the
hold ends 1500 ms after the first request whatever the axe scan is doing,
so the state being scanned is not the state the test names; every refetch
queues another sleeping handler, so how many are live is a property of
the machine; and a handler still sleeping when its request is cancelled
answers route.continue with "Route is already handled", which is what the
runner reported. It now holds on an explicit gate released at a point the
test chooses, counts what it held so a page that was merely slow cannot
pass for a page it held, and asserts the gate goes away on release, which
is the exit control the entry assertion never had.

The labs doorway proved that no OCR probe fires by waiting for that
request with a 500 ms timeout and expecting the rejection. An instrument
whose pass condition is its own failure has to be armed early and awaited
late, and in between it is an unhandled rejection that lands on whichever
test is finishing. Its window was wrong too: the timer started before the
switch was clicked, so on a slow runner it could expire before the labs
page existed. A request listener replaces it, covering everything from
before the click to after the record read landed, with the domain's own
read asserted in the same set so an absence cannot be a statement about a
matcher that stopped matching.
2026-08-07 10:26:41 +02:00
Marc-André Bombeck a5b6508961 fix(documents): check that closing a document consumed its history entry
Closing a card-opened document asks the browser to go back, so the entry
the selection pushed is consumed and the reader's next Back reaches the
page before it. A traversal is a request, not a guarantee: one asked for
while another is still settling can be dropped, and nothing raises when
it is. The sheet closes, React stays consistent, and the address bar goes
on naming a document nobody has open, so a reload or a shared link
re-opens the sheet that was just closed.

Pressing Escape straight after the browser's Forward button is exactly
that shape, and it reproduces: ten repeats across both viewports failed
two of twenty with the URL still carrying the id, and none of twenty once
the close verifies itself. The check is guarded by the document id, so a
traversal that landed on a different selection is left alone, and it is
cancelled the moment the sheet re-opens.

The browser test that found it could not say so. It asserted the sheet
was closed through a locator matched on the document TITLE, and the sheet
falls back to an untitled label while its detail read is pending, so the
assertion also passed on an open sheet showing a skeleton, resolved
immediately instead of waiting, and pushed the failure into a URL poll
ten seconds later. It now asserts the dialog role, which is what the
neighbouring deep-link test already does.
2026-08-07 10:26:25 +02:00
Marc-André Bombeck e2eea55b6e chore: drop two exports nothing reaches
The dead-code gate has been red on this branch since the sharing refusal
contracts landed. Neither name is new and neither was noticed, because
knip is not in the local gate.

consentRequiredResponse lost its last caller when every delegable route
started sharing one 403 description through recordRefusal(); the AI
consent sentence it wrapped is still used and stays, with a note at the
constant saying why there is no response object beside it any more.
mutateThenRestore was written with the sharing security fixtures and has
never been called.

No ignore entries: an export with no consumer is the thing the gate is
for.
2026-08-07 10:25:52 +02:00
Marc-André Bombeck c3c058074b chore(release): v1.37.0 — share part of a record, or keep one for somebody with no login 2026-08-07 08:25:17 +02:00
Marc-André Bombeck 2980cca200 docs: bring the sharing copy up to what the release ships
The operator page still said every grant is read-only, one release after
the write level shipped, and the table of what a grant cannot reach
predates both the manage level and managed profiles.

Rewritten against the frozen behaviour: the eight sections a grant can be
narrowed to and what each opens, the three levels and what each adds, the
step-up that is unconditional on a managed profile and conditional on an
ordinary invitation, and what a guardian may keep for a record that has no
login of its own. The AI row is corrected rather than dropped: a manage
grant reads insights that already exist, and no level causes an outbound
provider call.

Every claim on that page was read out of the code before it was written
down. The one about backups was cut instead, because it was not.
2026-08-07 08:20:08 +02:00
Marc-André Bombeck 6bb0360695 docs(api): publish the sharing request bodies as named schemas
Zod 4's .meta() is immutable: it returns a new schema carrying the
metadata and registers that one. Four request bodies in the sharing
family called it as a statement and dropped the result, so the route
table went on referencing the bare schema, the bodies were emitted
inline and anonymous, and the object-level descriptions never reached
docs/api/openapi.yaml. One of them carries the clause that scopes every
rule on the invitation endpoint to an invited grant, which is the
sentence that stops a reader carrying the step-up and the refusals
across to a guardian grant.

Bind each to a const, reference the const, and correct the level
boundary in the invitation's description while it is being published:
it still carried the blanket denial that stopped being true when the
anamnesis surface opened to a manage delegate.

The wire format does not move. Four named components appear and the four
bodies point at them; the fields, the types and the requiredness are
what they were. A new guard asserts every id this route table declares
reaches the built document, because the failing form looks exactly like
the working one.
2026-08-07 08:10:48 +02:00
Marc-André Bombeck 13701ff2b3 test: switch into a real record for the banner-geometry seam
The shared-record strip was forced by capturing /api/auth/me and serving
it back with the sharing block filled. That state is now proved across
the payload validator, the fence store and the transition machine at
once, so a single route mock cannot produce it and the two narrow
repairs both stop one step short of the shell.

So the spec stops faking it: its own login jar, a real switch into the
seeded whole-record READ grant, and a place on the list of files that
run in exactly one project, because a second project would drive the
same session row from two browsers. The viewport below md that project
used to cover is measured inside the desktop project instead, where the
shell picks its column layout from the same width-driven rules.
2026-08-07 08:06:05 +02:00
Marc-André Bombeck 24a98fe99f Merge the release reconciliation 2026-08-07 06:53:41 +02:00
Marc-André Bombeck a15c6fc553 fix: reconcile sharing migrations
Seven migrations, 0296 through 0302, apply to an empty database in order and
install both triggers. The allocation had been written down as four, and every
later document that quoted it inherited a range that had already moved.

`scripts/verify-v137-adversarial.ts` is the allocation as a runnable artifact
rather than a table somebody keeps in step by hand. It names all seven, refuses
a number allocated twice, asserts each trigger is in the migration that claims
it, and counts every release inventory against a written-down number instead of
against "more than zero" — a list that lost half its entries satisfies a
non-empty check and fails this one. It also refuses to report success when it
ran no checks at all.

It found two things on its first run. Eleven handler entries looked like
duplicates because the key ignored the action, and an `[id]` route carries an
update and a delete as separate contracts; the key includes the action now. The
journey-count leg was then falsified deliberately by expecting nine, which
failed on the count and exited non-zero.

The `push_attempts` principals are declared optional in the schema and NOT NULL
in the database, and that is deliberate rather than drift. The attribution guard
is a BEFORE INSERT trigger, so a write omitting both has them filled from the
legacy mirror before the constraint is checked; requiring them in the schema
would force every established self-delivery writer to name a pair it has no
opinion about, and relaxing the columns would let a partial pair reach the
table, which is what the trigger refuses. `migrate diff` reports the difference
because it cannot see triggers, so the reason is written at the columns and
names the test that proves the accommodation still works.

Measured rather than assumed: applying trunk's chain to its own empty database
reports the same classes of diff — truncated index names, timestamp precision,
foreign keys re-stated. The release adds eight lines to that, seven of them in
classes trunk already carries and one of them the deliberate pair above.
2026-08-07 06:21:55 +02:00
Marc-André Bombeck c043a77429 test: wire every release journey to the tests that carry it
The eight journeys were enumerated and one of them was wired. The other
seven existed as claims in a fixture file, which is the gap the enumeration
was written to close: a browser suite reports what it ran, never what it did
not, and a journey nobody wired reads exactly like a journey that passed.

All eight are wired now, and the list is checked in both directions — an
enumerated journey missing from the wiring fails, not just a wiring entry
naming a journey nobody declared. Before this, a subset was legal, so a
dropped journey and a not-yet-written one looked the same.

A journey names more than one file where more than one file carries it. J1
claims a grant runs through invite, accept, switch, expiry, revoke and a
direct URL; the browser proves the switch, what each level opens and the
direct-URL refusal, and the transitions either side are database facts
proved against real Postgres. Folding that into one file would mean a
browser spec driving expiry through the clock or an integration file
asserting what a page renders, and both are worse tests than the two that
exist.

Three journeys ride Playwright and five ride Vitest, so a green run of this
guard means all eight are claimed and here is which have executed in the
ordinary gate — never that all eight passed. The runner is derived from the
path rather than trusted, so it cannot become a label set to whichever value
made the split read better.

The extractor now reads `it(` as well as `test(`, and the parameterised
`it.each(table)("title")` form alongside the single-call one. It saw neither
before: five of the journeys are proved by Vitest files, every per-file leg
is over a matched set, and an empty match set satisfied them all. The
synthetic spec that proves the parse grew a Vitest half, and it is what
caught the parameterised form being invisible. What the matcher still cannot
see is written into its own doc comment.
2026-08-07 06:11:36 +02:00
Marc-André Bombeck 93a588cf6f test: observe the reminder dedup anchor where it is written
The cross-midnight test read `push_attempts` for a synthetic `DEDUP`
channel. Separating the scheduler's bookkeeping from delivery diagnostics
moved the anchor to `notification_events`, and nothing has written that
channel since. The query matched no rows, `findMany` answered the empty
list, and the assertion compared an empty set it had no reason to expect —
a check that could not fail whatever the tick did.

It now reads `notification_events` by record and event type, and asserts
the single row's `dedupKey`. Removing the claim from the tick fails the
dispatch-count leg above it; narrowing the key so it no longer names the
slot fails this leg on the key's own content, which is what makes it a
check rather than a comment.
2026-08-07 06:02:31 +02:00
Marc-André Bombeck b2e225470b test: read the account payload as the release publishes it
Four cases in the accountAccess integration test were written against a
contract this release rejected. They asserted an entry of seven fields and a
block of three, both of which gained one; and they asserted that a MANAGE
grant publishes `access: "manage"`.

It does not, by design. `access` is the v1.36.0 name and its union is
`read | write` — a client compiled against that release decodes it as a
closed set. MANAGE therefore publishes as `write` there and as `manage` on
`level`, and the entry schema raises a validation issue unless a manage
entry carries exactly legacy write access and whole scope. The expectations
move; the schema does not.

`recordKind` is required on an entry and on the block. Both are asserted
now, including the block-level value moving from `self` to `shared` across
a switch, so a value stuck on either reads as two cases disagreeing.
2026-08-07 06:00:29 +02:00
Marc-André Bombeck 5115dfe394 Merge main into the sharing release branch
Nothing to reconcile in the tree: main's dashboard-hydration fix is already
on this branch as an identical patch, and main's delegated-dose replay guard
predates the branch point. The merge records the ancestry so the release
branch cannot be read as behind trunk.

playwright.config.ts is the one file both lines touched. Main added the second
web server on 3100 that runs the shipped DASHBOARD_SSR_PREFETCH configuration;
this branch added the service-worker project and the per-spec project
exclusions that keep every session-moving spec in exactly one project. The
merged file carries both, and the only difference against main is those 49
added lines.
2026-08-07 05:55:20 +02:00
Marc-André Bombeck 2d3648610a Merge the sharing contract freeze 2026-08-07 05:51:06 +02:00
Marc-André Bombeck 4d86dceb99 docs: publish the last-Guardian refusal where it is actually raised
The floor was described on the one route that cannot reach it and left unsaid
on the two that answer it every time: withdrawing the last Guardian grant and
renouncing it both raise `managed_profile.guardian.required`, and both
published only 'that access had already ended'. Both 409s now name their two
codes, and the annotation on the removal route enumerates all four emitters
rather than three.

A guard closes the class rather than the instance: every route module that
raises the refusal must publish it on its own operation, with the emitters
discovered from the sources.

The freeze guard gains its containment leg — a module becomes delegable by
review, not by discovery, so every file contributing a fenced verb has to be a
member of one of the surface guard's frozen allowlists.
2026-08-07 05:43:06 +02:00
Marc-André Bombeck 84475ea2f2 test: read the Guardian grant id under its published name
The lifecycle suite took the invitation route's answer as an account-grant row
and reached for `id` and `expiresAt`. It answers with the roster's entry now,
so the id arrives as `grantId` and the expiry is read off the stored column,
which proves it was persisted rather than echoed.
2026-08-07 05:24:11 +02:00
Marc-André Bombeck 0da9040f2c test: enforce sharing client step-up
Freezes the authority split the third level ships with. A token exercises a
MANAGE grant, and a Guardian's authority over a managed profile, exactly as a
browser does — proved at the resolver, where neither had a Bearer case before.
A token cannot offer MANAGE and cannot create a managed profile at all, because
both gates resolve through the session cookie; the second had no test until now,
and it runs against a real database with a wildcard token to make the width of
the permission irrelevant.

The claim set is held together by a map naming, per claim, the file and the test
title that proves it, so removing any one of them fails rather than quietly
narrowing what a native client may do.

The fence's client-facing half is frozen beside it: the account payload publishes
the record context on a cookie session and null on a token, and the published
contract says so under the same header names the server matches on.
2026-08-07 05:11:02 +02:00
Marc-André Bombeck cc316a7b85 test: preserve sharing client compatibility
Runs the legacy whole-record decoder over the entries `resolveAccountAccess`
actually produces, rather than over the fixture objects that describe them: the
existing case proves both ends and never the assembly between them, which is the
shape of test this project keeps rediscovering. Whole READ and WRITE decode,
MANAGE decodes as write and never above the level it confers, a scoped grant is
refused rather than read as the whole record, and a stored scope the server
cannot parse reads as nothing on both ends.

The canonical readers are driven over the same server-built entry, so
`level`, `sections` and `recordKind` are proved to survive the trip to the
capability resolver. The account-payload guard gains the pair for
`recordSession`: a field whose only reader is the transport type is exactly
what that guard exists to catch.
2026-08-07 05:02:18 +02:00
Marc-André Bombeck 38766cd4ca docs: define sharing refusal contracts
Every route that resolves a record through the sharing fence can answer 403
`sharing.access.denied`, and until now that fact was published on the selector
header and on none of the 120 operations that produce it. All 120 carry it now,
byte for byte, from one constant: the refusal is deliberately indistinguishable
across a missing account, a missing grant, a scope that does not reach the
surface and a read grant on a write, so 120 paraphrases would invite a client to
tell apart what the server refuses to.

Where a delegable route already answered 403 for its own reason — a module
gate, the cycle gate, AI consent — the two share one description rather than one
of them going unpublished, since OpenAPI allows a single response per status.

The guard recomputes the delegable set from the route sources on every run and
classifies per verb, which matters: seventeen modules have a delegable read
beside a write that refuses a switch outright.
2026-08-07 04:56:56 +02:00
Marc-André Bombeck ec9d93aa24 docs: publish the managed-profile lifecycle routes
The contract already pointed at them: the Guardian roster names
`DELETE /api/managed-profiles/{id}/guardians/{grantId}` as the route its
`grantId` is for, and that route was not in the spec. Creation, deletion,
invitation and removal now are, with the two bodies moved to
`src/lib/validations` so the wire shape has one source.

Three things are stated rather than left to be discovered:

- the two refusals on the invitation that carry no `meta.errorCode`, and the
  order a client must resolve in because of them
- the last-Guardian 409 on the removal route, which nothing can elicit through
  that route today, published with the reason
- that the sentences on the ordinary invitation describe an invited grant only,
  so a client cannot carry its MANAGE rules across to a Guardian grant
2026-08-07 04:42:51 +02:00
Marc-André Bombeck 26fceca219 fix: answer the managed-profile Guardian routes in one shape
- publish the roster's entry from the invitation and `{ grantId, revokedAt }`
  from the removal, instead of the account-grant row Prisma returned
- drop the invitation's self refusal: it named a code no request can elicit,
  because a Guardian grant's grantor is the profile and never the caller
- name the duplicate grant error rather than catching every grant refusal into
  a sentence that would be wrong for any other one
- keep the rate limit and the unknown-identifier 404 free of an error code,
  as their siblings elsewhere are, and say why at the call site
2026-08-07 04:39:50 +02:00
Marc-André Bombeck eb9b03a788 Merge the managed-profile management surface 2026-08-07 04:20:57 +02:00
Marc-André Bombeck 8793bbf229 fix: close four small gaps around the managed-profile surface
- bound profile creation at ten an hour per account, the ceiling its
  guardian sibling has carried since it shipped
- distinguish a failed roster read from a slow one, with the way back
- cover the three caller states the roster read has to refuse: an
  unaccepted invitation, an expired grant, and MANAGE held elsewhere
- cover what deletion does to a guardian standing inside the record
2026-08-07 03:56:39 +02:00
Marc-André Bombeck 47c4560253 test: prove the banner names the kind of record, not just tags it
recordKindLabel chooses between two sentences that mean different things
and nothing could fail it: the journey asserted the data attribute, which
that function never reads, so inverting the arms left the suite green
while a guardian standing inside a managed profile was told it was an
ordinary shared record.
2026-08-07 03:56:30 +02:00
Marc-André Bombeck 7175db33f7 test: drop an assertion that could not fail
The pending-acceptance note renders unconditionally inside the invite
form, so asserting it after the invitation proved a string existed rather
than anything the journey did. The claim moves onto the pending row,
which the server has to produce. The note keeps its own leg in the unit
suite, where deleting the node makes it red.
2026-08-07 03:56:17 +02:00
Marc-André Bombeck 29940afb57 fix: name the step-up gate on the two acts that carry one
- deleting a profile and ending a guardian's access resolve fresh MFA,
  and both sit behind a confirmation, so the request that reaches the
  server is minutes old and routinely outside the five-minute window
- an account with no second factor is told where to set one up instead
  of being asked to confirm one it does not have
- the arm is scoped to those two acts: a 401 on accept, revoke or
  renounce is a lapsed session and must not read as a factor prompt
2026-08-07 03:55:25 +02:00
Marc-André Bombeck 217b0f41d8 fix: say what is wrong with a field where somebody will read it
- a refused field gets its own announced node in content contrast; the
  standing hint stays muted beside it, rather than being overwritten
- the timezone refusal is the only explanation for a submit button that
  will not press, so it leaves the picker's muted hint slot
2026-08-07 03:55:15 +02:00
Marc-André Bombeck e9084d9f17 test: cover the managed-profile journey
- drive creation, the switcher entry, the managed banner and the return
  trip in a real browser, plus the guardian roster and the floor stated
  before an invitation is accepted
- seed a guardian account with a second factor and refresh its step-up
  before the journey acts, since no fixture could reach a step-up-gated
  route before this
- tie the journey id to its test titles, so a marker that goes missing
  fails a check rather than vanishing from a run nobody counted
2026-08-07 03:22:51 +02:00
Marc-André Bombeck f62b2ab1a3 Merge pull request #717 from MBombeck/work/dashboard-hydration
Keep the dashboard the server streamed
2026-08-07 02:37:47 +02:00
Marc-André Bombeck e4870f3b5f fix: close two gaps the last audit round left open
- give the delegated-action inventory a leg that can falsify its level
  axis: the walked module set must strictly exceed the manage-only one,
  anchored on a route that never asks for manage
- declare AUDIT_LOG_RETENTION_DAYS and SESSION_COOKIE_SECURE in the env
  manifest, so the pre-deploy check reports the two settings operators
  are told to set, and hold manifest, compose whitelist and both example
  files in step
2026-08-07 02:26:29 +02:00
Marc-André Bombeck 6bfcccd755 feat: manage the guardians of a managed profile
- list who looks after a profile, invite another guardian and end an
  existing access from the profile's own row
- state the last-guardian floor from the real roster before the act, and
  say plainly that an invitation counts only once it is accepted
- give each of the invitation refusals its own sentence, branching on
  status for the two the route sends without an error code
- cover every call the card can make against the real routes
2026-08-07 02:22:30 +02:00
Marc-André Bombeck b3548f105e feat: delete a managed profile from its guardian's panel
- confirm before deleting, naming what goes and that it cannot be undone
- state how many people lose the record, taken from the guardian roster
  rather than assumed to be one
- say that deleting is the way out when you are the last guardian, since
  this route sends no last-guardian refusal
- announce a refused deletion on the profile's own row, retryable
2026-08-07 02:07:49 +02:00
Marc-André Bombeck 365ba8c2eb feat: list the guardians of a managed profile
- add GET /api/managed-profiles/{id}/guardians, cookie-only, refusing
  anybody who is not an active guardian of that profile with the same 404
  an unknown id gets
- disclose the grant id, the party block already shared between grant
  parties, the derived state and the two timestamps, and nothing else
- publish the route in the OpenAPI contract
2026-08-07 02:01:21 +02:00
Marc-André Bombeck 110511ff31 feat: create managed profiles from shared access
- add a managed-profile card to Settings -> Shared access, between the
  invitation card and the standing-state cards
- collect exactly the four fields the create route accepts, with the date
  of birth genuinely optional and never derived from a year
- refresh the account payload on success, so the new record reaches the
  switcher and the banner without a reload
- assert the section is reachable for an owner and refused for a Guardian
  inside a profile and for an adult manager
2026-08-07 01:53:26 +02:00
Marc-André Bombeck 466c9c906f Merge managed sharing activity and the manager-reachable record surface 2026-08-07 01:34:58 +02:00
Marc-André Bombeck 6ae0cc993f fix: close four small gaps around the record surface
The privacy dashboard re-implemented the audit-retention resolver with its own
default and its own floor. Two implementations of one disclosure, quoted to the
same person on two pages and by the purge job; it uses the shared resolver now.

The record-content branch in the settings gate matched a classification rather
than a page, so a second manage-writable destination would have rendered the
allergy and family-history managers under its own heading without anybody
choosing that. It resolves through a slug map, and the contract test fails if
the map and the classification disagree in either direction — a destination
cannot join the kind without somebody deciding what it renders.

The managed-profile nav filter assumed a guardian grant is always manage. It is
today, which is why the check was easy to leave out; an entry below that level
would have listed destinations the gate refuses.

Interpolation used a replacement string, and String.replace reads $&, $`, $',
$1 and $$ out of one. A display name containing $' rewrote the sentence around
it — and display names land in exactly the sentences that say who did what in
somebody's health record. A replacer function has no $ grammar at all, which
removes the class rather than escaping the members of it somebody thought of.
2026-08-07 01:00:02 +02:00
Marc-André Bombeck 5de488c35c docs: state the sharing boundary that is actually enforced
Two sentences promised that a manage grant reaches no settings at all. Both
were true when they were written and stopped being true when the anamnesis
destination opened, and both are in the worst places for a stale promise: one
is the access description generated into the public contract and read by the
native client, the other is the paragraph a delegate meets on a page sharing
does not cover.

Both now name the boundary the code draws — record content versus account
configuration — and say which part of the record a manage grant reaches. What
stays with the account owner is spelled out rather than implied: login, the
second factor, provider connections, tokens, notification routing, module and
threshold configuration, and who else has access.

A guard checks the copy against the classification rather than against itself,
so opening a second destination or closing this one moves the sentence with it.
The contract is regenerated.
2026-08-07 00:52:25 +02:00
Marc-André Bombeck c7e847a766 fix: bound the activity feed to the window it promises
The revoke dialog tells an owner that "who entered what" stays answerable for
N days, and the activity list prints the same number under its heading. The
query behind that list had no date filter: on an instance whose retention was
shortened it showed rows the sentence said were already gone, and the number
was a caption over an unbounded read rather than its limit. It is the filter
now, resolved once so the bound and the sentence cannot drift apart.

The list also stopped at a hundred rows and said nothing about it, which is the
more dangerous of the two silences — an owner who scrolls to the bottom reads
the oldest visible line as the beginning, and a busy household reaches the cap
in a fraction of the window. The response says which of the two limits it hit,
and the view states it only when it did: a caveat that is always on is one
people learn to skip.

The self-hosting page said an empty list means nobody opened the record. It
means nobody did so within the window. Corrected, with the row cap named
alongside it.
2026-08-07 00:48:58 +02:00
Marc-André Bombeck b1667ef692 fix: let the audit window an operator sets reach the container
AUDIT_LOG_RETENTION_DAYS is not only enforced, it is published: the
shared-access panel prints the window under the activity list, and the dialog
that ends somebody else's access states how long "who entered what" stays
answerable. Both read the value the server resolved. It was missing from the
compose environment: whitelist and from both example files, so an operator who
set 90 got 365 told to every user, in a sentence about their own data.

That block is a whitelist and Compose substitutes from .env regardless, which
is what makes the variable look configured while never arriving — the same
shape as the session-cookie flag in v1.5.2. A guard now covers the three places
an operator meets such a variable, and its control leg found that the cookie
flag itself is still absent from the production example. Documented there too.
2026-08-07 00:43:39 +02:00
Marc-André Bombeck f91f701e13 fix: say what a refused request actually was
Every delegable route files a breadcrumb when a request does not parse, and it
files it through auditLog on purpose: that helper is what stamps the actor, and
without the stamp a delegate's malformed request would read as the owner's own.
The rows are meant to be attributable. None of them had a sentence, so all of
them rendered in the owner's activity view as "made a change in your record" —
including one a view-only delegate can trigger by sending a query the route
cannot parse. Nothing had changed and nothing could have.

Thirty-three actions now have honest lines. A refusal says it was an attempt
and says it was refused; it never borrows the language of something that
happened. Two of them are filed by library modules the routes import — a
background import's completion row and a medication lifecycle reconciliation —
and a walk over route files alone could not see either.

The inventory guard was asking a different question from the feed. It kept only
awaited audit calls while the feed shows fire-and-forget rows identically, and
it read route files while the feed shows whatever the request reached. Both
criteria now match the feed's, the three rows the feed structurally cannot show
are excluded by name with the reason written down, and the exclusion list is
pinned at three. A leg asserts the shape of the sentence for every refusal, so
a future arm cannot map an attempt onto an ordinary verb and pass on coverage.

The whole round trip is covered against real Postgres: a view-only delegate
sends a malformed query, the row lands attributed to them under the owner, and
the sentence the owner reads is an attempt.
2026-08-07 00:40:40 +02:00
Marc-André Bombeck ef242f33bb feat: open the anamnesis record surface to managers
POST /api/allergies and POST /api/family-history have resolved
requireRecordAuth("manage", "profile") since the level shipped, while the only
form in the product that posts to either sat behind a Settings destination
classified unavailable. The write was admitted, audited and owner-scoped, and
nobody could reach it — the one-ended change this repository keeps
rediscovering, with the permission shipped and the surface left as a follow-up.

The destination now carries a classification that means what the routes mean:
reachable by everybody they already admit, which is a guardian inside the
profile they administer and an adult delegate holding manage. The four places
that decided visibility on the guardian-only literal were each updated
deliberately, and the shell that refused every settings path in an adult share
now admits exactly the destinations classified as record content. Record
configuration — modules, thresholds, notification routing — stays with the
owner at every level.

The page inside a record is its own component holding the two managers whose
routes answer for a delegate. Mounting the personal section would have put
three more forms on screen that refuse on submit. The family-history card says
whose statement the row is, which the route comment could not.

Both routes carried a long paragraph arguing the write was deliberately
unreachable. It is gone rather than left to send the next reader back to close
what this opens.

The integration coverage moves from the undeclared-mode refusal to a manage
contract: a manage delegate and a guardian each write and the row lands under
the owner with the delegate named as actor, while read and write delegates get
the insufficient-access refusal. Nothing exercised either route at manage
before.
2026-08-07 00:01:27 +02:00
Marc-André Bombeck 0cdfb97a45 test: cover sharing accessibility states
The shared-record accessibility suite had four tests for five states: success
and empty shared one, and neither of them ever entered an empty state. A
browser run reports what it ran and never what it did not, so a state nobody
wrote a test for produced exactly the same output as a state that passed.

The five states are enumerated in a fixture, each test names its state, and a
fast guard reads the spec back against the list — a state that loses its test,
its anchor, or one of its proofs now fails in the ordinary gate rather than at
the point somebody notices the spinner is silent.

Every state runs four proofs: an axe scan, the document reading order, either
a keyboard reach with a visible focus indicator or a live-region announcement
for the one state with nothing to press, and, where the copy is something a
person has to act on, that it renders as content rather than as muted meta and
clears the contrast floor. The retry control on the read-failure card gained a
stable slot so the keyboard proof targets the affordance rather than its
wording.

The eight release journeys are enumerated in the same fixture.
2026-08-06 23:46:43 +02:00
Marc-André Bombeck 71ad8d66b6 fix: preserve sharing failure states
Accepting, revoking and handing back a grant had no failure rendering at all.
The request came back refused, or never left the machine, and the panel did
nothing: the confirm dialog had already closed, the list did not change, and
the only signal was the absence of one. The two refusals that most need a
reader were the two that arrived most quietly — an invitation that had lapsed
before it was opened, and the last guardian being told they may not hand back
a profile that would then have nobody looking after it.

Each refusal now renders on the row it belongs to, announced, in content
contrast, beside a control that runs the same act again. The sentences are
split by what the person does next rather than by status code, so lapsed and
withdrawn read differently and the guardian refusal names the way out. A
request that never reached the server says so instead of reporting a refusal
nobody issued.

The failed state is read off the mutation rather than copied into local state
from onError: the copy is what goes stale, and the mutation already knows
which row it was for. The invitation form keeps every field it had, and only
a successful send clears them.
2026-08-06 23:39:39 +02:00
Marc-André Bombeck c92a80ee4c feat: describe managed sharing activity
Every action a manage-level route files now renders as its own sentence in
the owner's activity view, in all six locales. A write delegate can only add,
so the generic "made a change" was at least the right shape of fact; a manager
changes and removes entries the owner made themselves, and the generic line
withholds the only part that matters — whether a reading was corrected or
deleted, whether a dose history was purged.

The inventory reads the routes and calls the map rather than matching `case`
in its source, so an action that falls through to the fallback fails, and it
follows each resolved key into all six bundles. Every sentence interpolates
the actor's name and nothing else: the audit table is not encrypted and a
value in a verb line would be a health figure in a second store.

The revoke dialog's retention disclosure no longer depends on which of two
requests answers first. `retentionDays` rides the grant list, so a client
holding a row to revoke holds the window it must state, and the branch that
omitted the sentence is gone.
2026-08-06 23:30:07 +02:00
Marc-André Bombeck 25b1b0eab6 Merge record navigation and its session context fence 2026-08-06 23:06:16 +02:00
Marc-André Bombeck 9a5830753c test(02-12.1): name the transport guard's blind spots, match one more
- document srcSet, poster, object data, form action, window.open,
  sendBeacon, CSS url() and spread props as shapes this matcher cannot
  see, alongside the two trees it walks
- match the imperative `.src =` form, anchored to a real occurrence so
  the new leg cannot pass by matching nothing
2026-08-06 23:04:29 +02:00
Marc-André Bombeck 73e73469e3 fix(02-12.1): fetch a document's original once, and only to show it
The detail sheet loaded the original twice on open — the inline preview
and the download href each fetched and decrypted the whole blob — and
for a non-inline document the old href had cost nothing until clicked.

- one loader, lifted to the sheet, and only for a document that renders
  inline; everything else fetches at click time
- make the download a real disabled control that reflects a failed
  fetch: href="#" with aria-disabled announces unavailable and still
  activates, and it ignored the failure entirely
2026-08-06 23:04:29 +02:00
Marc-André Bombeck 120323d995 test(02-12.1): prove Vary on the serving path, not only the contents
Removing the Vary block left the disk-layer case green: it asserted what
is IN the cache, and the claim is what the cache will SERVE. On the
external-switch path nothing wipes those entries — the app never
initiated the switch — so Vary is the only thing between a cached
delegated response and the next request under another context.

- assert cache.match() hits under the stored context and misses under
  the new one; it fails when the Vary is removed
- correct the acceptance map and the client docblock to claim exactly
  what executes: no zero-entry count, no offline leg
2026-08-06 23:04:29 +02:00
Marc-André Bombeck 6e5b420e4e test(e2e): give every switching journey its own session row
The suite only passed on one worker: four specs shared the scope
delegate's cookie jar and moved the same session's record selector, so
at CI's two workers they moved the epoch under each other and the
failures were the harness racing itself.

- one login per switching spec, which is a separate session row and
  therefore a separate selector; the login bucket is cleared between
  them because the ceiling is five and setup now signs in eight times
- each such spec runs in exactly one project, since a second project
  drives the same row from two browsers
- clear what the browser suite WRITES, so it can be run twice: the
  write journey saves a minute-rounded reading and collided with itself
- wait for adoption after leaving a record, retry a lost switch the way
  a person would, and budget the cross-tab hold for machine load
2026-08-06 23:04:08 +02:00
Marc-André Bombeck 9c99ec34d6 test(02-12.1): make the deferred acceptance cases prove their claims
Every one of the three observed nothing and passed anyway.

- AC-04 held /api/auth/me so the record read goes first: /me is unfenced
  and adoptable, so the client silently re-adopted before ever sending a
  stale assertion
- AC-06 installs its intercept before the request and holds a FENCED
  read; /api/auth/me is an actor surface and echoes no context at all
- AC-07 moves to its own spec and a project with the service worker
  enabled, and reads the claim off the cache: with workers blocked the
  data cache is never populated and its positive control could not pass
- restore the shared session after each test, and start from a known
  record, so these cannot fail the specs that run beside them
2026-08-06 21:31:23 +02:00
Marc-André Bombeck 1d575cf1ae fix(e2e): target the visible date control, not its hidden mirror
data-slot rides {...rest} onto DateField's hidden ISO input, so the
invitation spec asserted visibility on an element that can never be
visible and typed into nothing. Use the primitive's data-testid, which
lands on the overlay a person edits, and assert the mirror took the
value.
2026-08-06 20:58:30 +02:00
Marc-André Bombeck c11c462e57 fix: answer a duplicate measurement with 409 on both write paths
The batch path had no unique-violation handling at all, so one duplicate
anywhere in the transaction answered 500 — indistinguishable from a
server fault, and what every client retries against. The single path
narrowed with instanceof, the form prisma-errors.ts exists to replace.
2026-08-06 20:56:16 +02:00
Marc-André Bombeck bcf2322f65 feat(02-12.1): vary the record echo on the headers that produced it
A shared cache is one reverse proxy away, and without Vary the first one
to appear would key a delegated record response on URL alone and hand it
to the next request under a different context. Appends rather than
replaces, so a route that already varies keeps what it had.
2026-08-06 20:51:29 +02:00
Marc-André Bombeck dc343f434c docs(02-12.1): narrow two overstated claims
- the idempotency arm refuses only a wrongly-asserted context; an admin
  route behind unfenced requireAdmin still serves a headerless request
- the epoch trigger does not fire on a statement that names record_epoch
  without moving the selector; the source guard is what covers that
2026-08-06 20:48:50 +02:00
Marc-André Bombeck 731203bdf4 fix(02-12.1): reconcile without firing the reads it is holding
- keep the record entries until /api/auth/me has answered: clearing the
  cache under a mounted observer made the held tab refetch at once
- exclude the account cell from the cancellation, and swallow a repeat
  trigger, so a burst of 409s cannot kill the request that ends the hold
- read the account payload network-only; the default staleTime would
  have returned the very context the browser was told is wrong
2026-08-06 20:45:07 +02:00
Marc-André Bombeck 0fee005683 fix(02-12.1): give an unprovable record context a way out
A selector pointed at a record whose grant has lapsed reports the same
disagreement on every /api/auth/me, so routing it to the hydration gate
rendered a permanent spinner with no controls. Expiry reaches this state
on its own: revocation clears the selector inside its transaction and
expiry does not.

- treat an unprovable context as a refusal, which paints the door with
  the button back to one's own record
- check the refusal ahead of the hydration gate, so neither trigger can
  render behind a spinner again
2026-08-06 20:40:31 +02:00
Marc-André Bombeck ffe38c9bb6 fix(02-12.1): reach fenced document routes through the app transport
A browser-issued <img src>, <iframe src> or <a href download> cannot
carry the record-session assertion, so the fence refused all three on
any session that had been inside a shared record — permanently, since
none of them will ever send a header.

- add a structural guard: no client file may name a record-fenced route
  in a src=, href= or window.location sink
- fetch the thumbnail, the inline preview and the download through the
  app transport and hand the DOM an object URL, revoked on unmount
- make the two API probes in the managed-profiles browser spec assert
  the same context the app beside them asserts
2026-08-06 20:36:45 +02:00
Marc-André Bombeck 8fcbdcc0df test(02-12.1): prove the record-session fence end to end
- give every acceptance case a stable id and assert the mapping from a
  runnable artifact, recording which cases execute in the ordinary gate
  and which await the browser stage
- add the browser spec for the cases no cooperative layer can reach:
  peers reconciling to an exact context, an aborted switch response, a
  closed initiator, a delayed response, and the offline disk layers
2026-08-06 19:33:15 +02:00
Marc-André Bombeck 31b4857d8b feat(02-12.1): carry and verify the record context from the browser
- attach the asserted context to every same-origin request inside the
  three fetch entries, so no call site classifies itself
- discard a response whose echoed context contradicts the adopted one;
  serve one that carries no echo, which is what keeps the public poll
  and every actor surface working
- adopt from /api/auth/me and the switch response, and from nothing else
- send the epoch on every switch and retry once after reconciling
- hold and reconcile on the 409 instead of leaving the record
2026-08-06 19:10:02 +02:00
Marc-André Bombeck 3a99de312e fix(02-12.1): check record context before an idempotent replay
- evaluate the fence in the wrapper above findCached, so a stale request
  neither replays a body, learns a cell exists, nor inserts a claim
- return the refusal rather than throwing: one route composes the
  wrapper outside apiHandler, where a throw escapes the envelope
- read the claim and the session's own context on one session lookup
2026-08-06 18:54:20 +02:00
Marc-André Bombeck 45fec0fc1b feat(02-12.1): refuse a record request whose context has moved
- both record resolvers check the fence after authentication and before
  the carrier, off the one session row that also decides the scope
- POST /api/account/switch takes an optional expectedEpoch and writes
  conditionally, so concurrent switchers resolve to one outcome
- GET /api/auth/me publishes the context a browser bootstraps from
- every response that resolved a record scope echoes it back
- regenerate the API contract
2026-08-06 18:21:40 +02:00
Marc-André Bombeck 59359738c8 feat(02-12.1): decide record-session context in one place
- add an import-free contract module both bundles can name, holding the
  header names, the parse and the verdict
- add the server fence: header read, wide-event stamp, and the refusal
- add RecordSessionChangedError as a third sibling on the existing
  sharing-error arm, so the 409 needs no new serialisation branch
2026-08-06 17:59:07 +02:00
Marc-André Bombeck 5c9befc0ae feat(02-12.1): stamp a record-context epoch on every session
- add sessions.record_epoch, owned by a BEFORE UPDATE trigger so the
  ON DELETE SET NULL path and raw SQL writes cannot skip it
- normalise pre-existing rows so epoch zero means never switched
- project the epoch off the row getSession already loads
2026-08-06 17:52:10 +02:00
Marc-André Bombeck 675c70eba8 Keep the dashboard the server streamed
`/` runs its reads server-side and hands them to TanStack through a
HydrationBoundary, so the first HTML already carries real tiles. React threw
that away on every cold load. The app shell hydrates first and its mount
answers `/api/auth/me`; the dashboard sits below `loading.tsx`, hydrates later,
and its first client render therefore read an account the server never had.
That disagreed with the streamed HTML, React reported #418 and re-rendered the
whole page. The prefetch paid for its queries and delivered none of its paint.

The account payload is now withheld from the hydration render wherever it is
only rendered. `useAccountOnceMounted()` answers null until the component has
mounted, which is what the server rendered, and hands the payload over on the
next render. The dashboard page, the caregiver card, the getting-started
checklist, the achievements tile and the unit labels read it that way. `useAuth`
itself still reads the cache, because the document vault redirects off
`user.modules` and a first render claiming "no account" bounces it to `/`.

Two tiles disagreed without any account involved. A query reports `isLoading`
true on the client's first render and false on the server, so both now gate on
whether the cell holds an answer.

Nothing in CI ran the shipped configuration: the suite's server turns the
prefetch off so route mocks keep governing the dashboard. A second server runs
it on, and one spec asserts that no hydration error is reported and that the
tile node the server streamed is still the node in the DOM once the page
settles.

Measured over nine cold loads with the CPU throttled 4x: seven bailouts before
and none after, median LCP 869 ms before and 145 ms after. FCP and the time to
the first tile in the DOM are unchanged, because the streamed paint was never
the problem. Keeping it was.
2026-08-06 17:28:48 +02:00
Marc-André Bombeck a08e82d0be Merge commit '38214e472' into work/v137-record-session-fence 2026-08-06 17:10:56 +02:00
Marc-André Bombeck 38214e4726 fix(02-12): hold peer tabs during record switches
- Clear scoped reads before the server session changes
- Reconcile every tab with a fresh access response
2026-08-06 15:06:12 +02:00
Marc-André Bombeck c66b29d22a fix(02-12): complete profile navigation translations
- Keep every supported locale aligned with the profile navigation doorway
2026-08-06 14:37:13 +02:00
Marc-André Bombeck a636a3b4c5 fix(02-12): gate shared record navigation
- Wait for the shared-record banner before generated reads
- Keep the profile doorway in the navigation translation namespace
2026-08-06 14:35:02 +02:00
Marc-André Bombeck c42df8cbc3 fix(02-12): gate record preload scope
- Wait for a validated account scope before warming record reads
- Abort scoped preloads and discard handoffs across record transitions
- Cover malformed scope reloads and fresh own-record recovery
2026-08-06 14:32:32 +02:00
Marc-André Bombeck 2ea812d387 Merge guardian notification delivery 2026-08-06 14:24:10 +02:00
Marc-André Bombeck 2ae3a66816 fix(02-11): bound APNs provider delivery
- Time out stalled provider sends without unhandled late rejections\n- Record a transient timeout outcome for cascade fallback\n- Cover timeout fallback with unit and integration tests
2026-08-06 14:10:28 +02:00
Marc-André Bombeck c56d1ca50b fix(02-11): protect guardian egress data lifecycle
- Exclude and erase egress claims with recipient-side lookup support\n- Serialize data wipes with managed-profile Guardian authorization\n- Cover last-Guardian and queued-claim wipe races
2026-08-06 14:05:59 +02:00
Marc-André Bombeck 21e111c06c fix(02-12): refuse malformed record access
- Preserve absent-server compatibility while rejecting published invalid blocks\n- Partition refused record reads and withhold protected presentation
2026-08-06 14:03:13 +02:00
Marc-André Bombeck e8ce0e277a test(02-11): verify final claim uses database time
- Keep a stale application clock from authorizing an expired Guardian\n
2026-08-06 13:47:42 +02:00
Marc-André Bombeck 4b79f83cf7 fix(02-11): release guardian lock before provider egress
- Commit a final authorization claim under the lifecycle lock\n- Keep provider calls and retry outcomes outside database transactions\n- Retain authorization claims with notification delivery diagnostics
2026-08-06 13:46:42 +02:00
Marc-André Bombeck b844d04676 fix(02-12): reject divergent shared-record state
- Verify the active record matches its canonical switcher entry\n- Skip the owner OCR probe in delegated Labs records
2026-08-06 13:39:37 +02:00
Marc-André Bombeck 1818bd874b fix(02-11): authorize guardian egress under lock
- Hold the managed-profile lock through every provider send\n- Add the notification event retention index and race coverage
2026-08-06 09:42:47 +02:00
Marc-André Bombeck 6ecf0cc8ff style(02-11): format notification attribution test
- Apply the repository formatter to the existing integration test
2026-08-06 09:37:42 +02:00
Marc-André Bombeck f5a02c2d29 test(02-11): cover guardian egress races
- Exercise revocation and expiry against blocked channel egress\n- Require a direct retention index for notification events
2026-08-06 09:35:43 +02:00
Marc-André Bombeck 358bb39465 fix(02-12): keep scoped record polls dormant
- suppress whole-record achievements reads for narrowed grants\n- stabilize record journey response assertions
2026-08-06 08:34:02 +02:00
Marc-André Bombeck e568caa2f1 test(02-12): make record switcher journeys deterministic
- Address granted records by their published username\n- Start the profile error mock before record navigation
2026-08-06 08:25:42 +02:00
Marc-André Bombeck c21957db9f fix(02-12): keep record switcher entries reachable
- Constrain the shared-record submenu to available viewport height\n- Scroll long grant lists without hiding delegated records
2026-08-06 08:19:43 +02:00
Marc-André Bombeck 60b4845fea feat(02-11): secure guardian notification delivery
- Remove record-mutating affordances from Guardian channel payloads\n- Reject managed Telegram callbacks and verify channel attribution
2026-08-06 05:44:41 +02:00
Marc-André Bombeck accb98e223 test(02-11): cover guardian notification channel safety
- Cover non-interactive Guardian payloads across delivery channels\n- Reject Telegram callbacks tied to managed records
2026-08-06 05:37:05 +02:00
Marc-André Bombeck 8988cd9e41 chore(02-12): ignore generated Playwright session states
- Cover all e2e storage-state cookie files\n- Keep generated browser sessions out of version control
2026-08-06 05:34:16 +02:00
Marc-André Bombeck 123bc15f16 fix(02-12): restore shared banner contrast
- Use the foreground token for warning context copy\n- Serialize shared-session browser journeys
2026-08-06 05:34:16 +02:00
Marc-André Bombeck 59de92b62e fix: isolate guardian notification preferences 2026-08-06 05:33:02 +02:00
Marc-André Bombeck be4ee9ac6d test: cover guardian notification preferences 2026-08-06 05:30:49 +02:00
Marc-André Bombeck 4999c786e3 test(02-12): exercise access-level record journeys
- Seed adult and managed whole-record grants for browser coverage\n- Verify scoped writes, settings boundaries, and refused coach reads
2026-08-06 05:26:21 +02:00
Marc-André Bombeck a78189b7f6 feat: add guardian notification fanout 2026-08-06 05:23:38 +02:00
Marc-André Bombeck 1c0a5d7777 test: cover guardian notification eligibility 2026-08-06 05:17:56 +02:00
Marc-André Bombeck b231a7892c test(02-12): retire sharing inventory anchors
- remove obsolete inventory-only journey declarations\n- select persistent shared-record journeys by Playwright project config
2026-08-06 05:16:32 +02:00
Marc-André Bombeck 9bb1e5b2ea test(02-12): scan shared record accessibility states
- use an isolated shared-record browser session\n- scan empty, loading, error, and refusal states with axe
2026-08-06 05:14:00 +02:00
Marc-André Bombeck 5e8b90bcc1 Merge notification delivery identity 2026-08-06 05:12:42 +02:00
Marc-André Bombeck 407f7cc044 test(02-12): exercise scoped record doorways
- seed isolated records for all eight shared domains\n- verify each browser switch lands on its scoped read surface
2026-08-06 05:12:33 +02:00
Marc-André Bombeck 7104578d27 fix(02-12): honor shared scope in module pages
- keep scoped record pages out of actor module redirects\n- suppress unrelated illness reads from document-only records
2026-08-06 05:12:23 +02:00
Marc-André Bombeck f6b9c8e882 fix(02-12): fail closed in record presentation
- retain elevated chrome only for internally consistent payloads\n- fall back to the caller record on malformed access entries
2026-08-06 05:07:27 +02:00
Marc-André Bombeck a33cde3034 test(02-12): cover defensive record presentation
- reject inconsistent access levels before chrome can elevate them\n- fall back to the caller record for malformed payloads
2026-08-06 05:06:36 +02:00
Marc-André Bombeck b53147559a feat(02-12): scope cycle startup reads
- resolve calendar reads against the active record\n- resolve cycle insights against the active record
2026-08-06 05:05:59 +02:00
Marc-André Bombeck e037c1b8c5 test(02-12): admit scoped cycle startup reads
- freeze calendar and insights as cycle read handlers\n- retain the exact record resolver scope matrix
2026-08-06 05:05:13 +02:00
Marc-André Bombeck acd96a80e9 fix(02-12): gate protected routes on record scope
- resolve account capabilities before protected page queries mount\n- leave public routes outside the record loading gate
2026-08-06 05:04:26 +02:00
Marc-André Bombeck b358cfa3b8 test(02-12): cover record capability hydration
- hold protected content until account capabilities resolve\n- keep public routes outside the protected loading gate
2026-08-06 05:03:22 +02:00
Marc-André Bombeck 6c4dd2d96b feat(02-12): route scoped records to granted domains
- keep shared navigation independent of actor module preferences\n- open scoped records at their first allowed destination\n- announce record access and kind in doorway names
2026-08-06 05:02:37 +02:00
Marc-André Bombeck 34073cf8dc test(02-12): cover scoped navigation presentation
- prove profile uses a read-only shared route\n- cover scoped navigation independent of actor module flags\n- require action, access, and kind in record button names
2026-08-06 05:00:33 +02:00
Marc-André Bombeck affd356677 test: retain sustained safety event claims
- exercise the shared notification claim boundary\n- preserve rolling sustained-run dedup coverage
2026-08-06 04:59:50 +02:00
Marc-André Bombeck 9eab70f032 feat(02-12): add scoped profile summary
- expose bounded read-only profile facts for shared records\n- keep profile navigation separate from Settings mutations
2026-08-06 04:59:25 +02:00
Marc-André Bombeck 9ba37342d7 fix: claim notification events atomically
- serialize rolling event claims before delivery\n- keep provider egress outside the transaction
2026-08-06 04:57:50 +02:00
Marc-André Bombeck ba7bf49fae test: cover atomic notification event claims
- race record event claims through PostgreSQL\n- require safety producers to honor the claim
2026-08-06 04:53:50 +02:00
Marc-André Bombeck e2d308ec31 test: cover read-only profile summary
- Render bounded profile details\n- Exclude profile mutation controls
2026-08-06 04:53:28 +02:00
Marc-André Bombeck 60f91d27d7 fix: validate account access payloads
- Share the closed access schema with OpenAPI\n- Fail closed on malformed or stale record metadata
2026-08-06 04:52:46 +02:00
Marc-André Bombeck 69f97b268c fix: erase notification anchors with record data
- remove record event anchors during data deletion\n- retain sustained safety dedup coverage
2026-08-06 04:48:47 +02:00
Marc-André Bombeck 9c4c7b2b7d fix: retain notification anchor boundaries
- classify local notification anchors outside backups\n- keep reminder dedup fixtures on record events
2026-08-06 04:46:45 +02:00
Marc-André Bombeck c6b5d5df63 test: cover account access payload parsing
- Preserve canonical shared and manage payloads\n- Reject malformed and stale access metadata
2026-08-06 04:46:15 +02:00
Marc-André Bombeck 10a58a7e6a test: cover recipient-scoped Telegram persistence
- retain independent recipient reminder slots\n- verify chat updates and recipient cascade cleanup
2026-08-06 04:44:08 +02:00
Marc-André Bombeck 027f2b4355 fix: suppress premature managed safety delivery
- keep direct safety notifications to ordinary self-delivery\n- move safety dedup anchors out of delivery diagnostics
2026-08-06 04:41:40 +02:00
Marc-André Bombeck ce94f4773f fix: reject partial notification attribution
- retain only complete delivery principal pairs\n- preserve legacy self-delivery records
2026-08-06 04:39:36 +02:00
Marc-André Bombeck 8b275c87db test: cover partial notification attribution
- reject one-sided delivery identities\n- avoid ambiguous push-attempt ledger writes
2026-08-06 04:38:48 +02:00
Marc-André Bombeck fa46f27b01 feat: scope Telegram reminder tracking to recipients
- keep delegated recipient slots independent\n- bind callback cleanup to the recipient account
2026-08-06 04:38:09 +02:00
Marc-André Bombeck 5807879439 test: cover recipient-scoped telegram reminders
- Keep identical slots separate for each recipient\n- Update one slot when a recipient changes chat
2026-08-06 04:33:35 +02:00
Marc-André Bombeck 9380ea0f18 feat: separate notification event anchors
- Store record-scoped scheduler events outside delivery attempts\n- Keep delivery diagnostics free of bookkeeping rows
2026-08-06 04:32:52 +02:00
Marc-André Bombeck 2999b75ea6 test: cover notification event anchors
- Require record-scoped reminder deduplication\n- Keep anchors independent of delivery recipients
2026-08-06 04:29:54 +02:00
Marc-André Bombeck f0bcb5456c test: name managed settings module key
- Avoid a reserved module variable in the settings inventory test
2026-08-06 04:29:38 +02:00
Marc-André Bombeck 1ba73a4d51 fix: enforce notification delivery authority
- Require active Guardian authority before cross-record delivery\n- Serialize managed delivery checks with lifecycle changes
2026-08-06 04:29:18 +02:00
Marc-André Bombeck b78d64cb98 test: cover notification delivery authority
- Require active Guardian authority for managed delivery\n- Cover inactive and mismatched grants
2026-08-06 04:27:27 +02:00
Marc-André Bombeck 02aa61c9db fix: preserve access payload readers
- Read resolved level and record kind in the record switcher\n- Keep payload consumer coverage aligned with record presentation
2026-08-06 04:27:06 +02:00
Marc-André Bombeck f69e1d7dec feat: add managed settings navigation
- Show only guardian settings for managed records\n- Keep record-scoped settings and exit context visible
2026-08-06 04:23:17 +02:00
Marc-André Bombeck a42d2a6d2f test: cover managed record navigation
- Cover filtered managed settings navigation\n- Keep the exit action visible for an active record
2026-08-06 04:22:32 +02:00
Marc-André Bombeck ba3be7ba9b feat: distinguish managed record access 2026-08-06 04:18:05 +02:00
Marc-André Bombeck 908897cc6b test: cover shared record modes 2026-08-06 04:17:58 +02:00
Marc-André Bombeck afae57207c feat: scope shared record navigation 2026-08-06 04:13:59 +02:00
Marc-André Bombeck cb15100341 test: cover scoped record navigation 2026-08-06 04:13:54 +02:00
Marc-André Bombeck 2ccd022410 test: update notification sender attempt mocks
- Exercise identity-aware delivery attempt recording\n- Keep self-delivery assertions explicit
2026-08-06 04:05:33 +02:00
Marc-André Bombeck 201a24e404 Merge managed record settings 2026-08-06 04:05:16 +02:00
Marc-André Bombeck 437d916fc6 fix: guard managed setting label inventories
- Treat inherited property names as unavailable settings

- Preserve legacy tile aliases only for declared entries
2026-08-06 04:01:00 +02:00
Marc-André Bombeck d9b675f993 feat: attribute notification delivery attempts 2026-08-06 03:59:08 +02:00
Marc-André Bombeck e4993af909 test: cover notification diagnostic attribution 2026-08-06 03:57:55 +02:00
Marc-André Bombeck 906118f86e fix: resolve notification delivery identity 2026-08-06 03:57:23 +02:00
Marc-André Bombeck 24c5c49be3 fix: remove unused managed setting labels
- Keep closed display inventories as the only rendered labels
2026-08-06 03:55:37 +02:00
Marc-André Bombeck 6a1d1dd6e8 fix: preserve managed target defaults
- Return effective threshold ranges after managed updates\n- Localize closed Coach and Insights display inventories
2026-08-06 03:52:49 +02:00
Marc-André Bombeck 913a41b37d test: cover notification delivery identity 2026-08-06 03:49:49 +02:00
Marc-André Bombeck 3bb9349171 test: cover notification attribution constraints 2026-08-06 03:49:42 +02:00
Marc-André Bombeck 6108a71d80 feat: separate notification subjects and recipients 2026-08-06 03:46:57 +02:00
Marc-André Bombeck 5a9f8a0df6 Merge managed profile lifecycle 2026-08-06 03:44:16 +02:00
Marc-André Bombeck 6771b9060f test: cover notification attribution persistence 2026-08-06 03:43:35 +02:00
Marc-André Bombeck 247ac8494c fix: complete managed record settings
- Expose canonical defaults and reject invalid settings families\n- Localize Guardian controls and refresh dependent caches
2026-08-06 03:40:13 +02:00
Marc-André Bombeck e788675b82 feat: configure managed record settings
- Scope writable settings to the selected managed record\n- Render typed Guardian controls with separated audit attribution
2026-08-06 03:21:02 +02:00
Marc-André Bombeck 389f2a042b fix: complete managed Guardian invitation lifecycle 2026-08-06 03:19:34 +02:00
Marc-André Bombeck 493437207e test: cover managed Guardian invitation lifecycle 2026-08-06 03:14:47 +02:00
Marc-André Bombeck 32380b1935 fix: clear revoked Guardian sessions
Return a removed Guardian's browsers to their own record.
2026-08-06 03:08:51 +02:00
Marc-André Bombeck ffe3225639 fix: complete managed Guardian lifecycle
Use locked Guardian membership and transactional lifecycle audits.\n\nKeep acceptance and marker changes atomic.
2026-08-06 03:05:19 +02:00
Marc-André Bombeck 55291ad32d test: cover managed Guardian lifecycle races
Exercise cookie routes, transaction rollback, and record-serialized races.
2026-08-06 03:01:12 +02:00
Marc-André Bombeck 523ab3220b fix: serialize managed profile Guardians
Protect every Guardian-reducing lifecycle transition with a record lock.\n\nReturn a recoverable refusal when the final Guardian remains.
2026-08-06 02:50:30 +02:00
Marc-André Bombeck b639b064f9 test: register managed record settings routes
- Freeze the guardian-only settings endpoints\n- Require an explicit purpose for both routes
2026-08-06 02:42:01 +02:00
Marc-André Bombeck 03ee01ba56 feat: show managed integration status
- Render a record-keyed status view for managed profiles\n- Refuse shared Settings links before actor controls mount\n- Localize intentional unavailable states
2026-08-06 02:38:54 +02:00
Marc-André Bombeck 5059bc9b69 test: cover managed profile Guardian races
- Exercise concurrent final-Guardian reductions against Postgres\n- Cover recoverable account and profile deletion paths
2026-08-06 02:36:08 +02:00
Marc-André Bombeck e5e3590ca3 feat: add managed profile Guardians
- Keep the ordinary invitation consent flow for a second Guardian\n- Clear managed Guardian expiry when the invitation is accepted
2026-08-06 02:32:59 +02:00
Marc-André Bombeck 665f223dc4 test: cover managed profile Guardian consent
- Pin ordinary second-Guardian acceptance\n- Pin non-expiring accepted Guardian grants
2026-08-06 02:29:55 +02:00
Marc-André Bombeck 54cd3e3959 test: cover managed integration status
- Require the record-scoped status query\n- Keep integration controls out of the managed view
2026-08-06 02:29:04 +02:00
Marc-André Bombeck 58434a2b44 feat: create managed profiles atomically
- Require a fresh cookie MFA proof before creation\n- Create the credential-less profile and initial Guardian grant together
2026-08-06 02:28:56 +02:00
Marc-André Bombeck d95c48f48d feat: classify managed record settings
- Inventory every Settings destination as an explicit access class\n- Fail closed for unknown deep-link destinations
2026-08-06 02:28:29 +02:00
Marc-André Bombeck d965076609 test: cover settings classification
- Require a literal settings inventory\n- Limit Guardian configuration to the approved subset
2026-08-06 02:27:27 +02:00
Marc-André Bombeck 009de7cb5f feat: add record keyed settings
- Separate managed record settings from actor identity\n- Limit integration reads to the active managed record
2026-08-06 02:26:44 +02:00
Marc-André Bombeck 1eb0d22285 test: add record settings contract
- Cover record-keyed DTO and cache behavior\n- Pin actor identity separately from the active record
2026-08-06 02:25:53 +02:00
Marc-André Bombeck 51cbbae17f test: cover managed profile creation
- Prove truthful profile attributes and the initial Guardian grant\n- Prove grant-write failure rolls the profile transaction back
2026-08-06 02:25:19 +02:00
Marc-André Bombeck c3125078b9 chore: resolve sharing lint checks
Keep attribution and provider-work tests lint-clean.
2026-08-06 02:13:50 +02:00
Marc-André Bombeck d404d8275a fix: preserve import job wipe ownership
Keep durable actor attribution from deleting record-owned jobs.

Align provider and idempotency coverage with fail-closed behavior.
2026-08-06 02:11:01 +02:00
Marc-André Bombeck f5ca810643 chore: format sharing authority controls
Apply repository formatting to provider and import coverage.
2026-08-06 02:05:24 +02:00
Marc-André Bombeck a620a730b9 test: extend sharing boundary guards
Cover provider work authority and import actor attribution.
2026-08-06 02:04:04 +02:00
Marc-André Bombeck 620817b10b fix: retain import actor attribution
Persist record and actor identities through job completion.\nWrite one bounded transactional completion audit per job.
2026-08-06 02:00:35 +02:00
Marc-André Bombeck adb932052c fix: keep managed system work operator-scoped
Resolve managed record credentials through the operator policy for system work.
2026-08-06 01:53:04 +02:00
Marc-André Bombeck 2b2080f48c test: pin import actor attribution
Cover durable record and actor attribution across completion retries.
2026-08-06 01:52:43 +02:00
Marc-André Bombeck e209db24f4 fix: block delegated provider egress
Carry bounded work authority through queues and revalidate it at dispatch.\nResolve shared records without personal credentials.
2026-08-06 01:49:33 +02:00
Marc-André Bombeck f7a06df2bc test: pin provider origin controls 2026-08-06 01:38:35 +02:00
Marc-André Bombeck 60b842f614 fix: reauthorize delegated replay
- Recheck the live grant before returning cached delegated responses

- Refuse cached replay when the acting record cannot be resolved safely
2026-08-06 01:29:07 +02:00
Marc-André Bombeck f8b05d541e test: pin delegated replay revocation
- Cover active, revoked, and own-record cache replay against Postgres
2026-08-06 01:22:33 +02:00
Marc-André Bombeck 09ff1fb23d feat: enforce managed sharing boundaries 2026-08-06 01:16:18 +02:00
Marc-André Bombeck d86358f3e4 fix: recover managed sharing boundaries 2026-08-06 00:19:35 +02:00
Marc-André Bombeck 01562b4aef test: use the shared browser test entry point 2026-08-06 00:08:54 +02:00
Marc-André Bombeck 8669df4cda feat: add scoped record invitations 2026-08-05 23:58:30 +02:00
Marc-André Bombeck 4923db6464 fix: preserve account access compatibility 2026-08-05 23:58:26 +02:00
Marc-André Bombeck e4e773d543 feat: define scoped sharing levels 2026-08-05 23:58:18 +02:00
Marc-André Bombeck ab14fdb6f3 Let an invitation name its sections and offer management
An owner can now narrow a grant to the parts of their record they mean to
share, and can offer the third level. Both decisions are made once, on the
invitation, and neither widens afterwards.

The invite schema takes `scope`: absent or null is the entire record, which
is what every stored grant means and what an owner who does not narrow still
gets. An empty array, a key outside the vocabulary and the whole-record
sentinel are each refused with a 422 naming the field; `inviteGrant` refuses
the same three underneath, and its `invalid_scope` now has an HTTP mapping
instead of falling into the generic refusal.

Offering MANAGE asks for a fresh second factor when the account has one. That
gate resolves through the session cookie and has no Bearer fall-through, so a
token caller is refused first with `sharing.invite.manage_browser_only` rather
than being told it is not authenticated by a route that had just
authenticated it. The consequence is deliberate: management of a health
record is offered from a browser.

The account payload gains `sections` and `level` beside `access` and
`canWrite`, resolved server-side and ordered as the consent screen reads.
`access` was `grant.access === "WRITE" ? "write" : "read"`, which would have
published a grant that can delete entries as read-only; it is a total map
now, so the next level cannot ship silent. The capabilities hook carries both
facts and turns neither into an affordance yet — the edit and delete controls
come back in the release where the routes behind them answer.

The consent surface asks two questions in order rather than laying out a
nineteen-cell grid. The level is three radios, narrowest preselected. What
they can open is two radios, the entire record preselected, and only the
narrow branch expands the eight sections with a sentence each. Both honest
limits are stated above the checkboxes, where the decision is being made: a
section shares everything written in it, and the cross-record surfaces do not
appear for a narrowed grant. Documents carries its own warning, cycle appears
only for an owner who tracks it, and Manage collapses the question to the one
line that answers it.

The Manage sentence says the other person can add, change and remove entries,
including ones the owner entered themselves, and says in the same breath what
it does not reach. The acceptance side gets its own responsibility line rather
than the write one wearing a stronger adjective.

Six locales.
2026-08-05 23:37:00 +02:00
Marc-André Bombeck feb9d25e87 test: anchor sharing release journeys 2026-08-05 23:29:55 +02:00
Marc-André Bombeck bd6220bbba test: add sharing security principals 2026-08-05 23:26:42 +02:00
Marc-André Bombeck d9e68e7ee3 test: freeze sharing authorization inventories 2026-08-05 23:24:54 +02:00
Marc-André Bombeck e05bad0ec2 chore: refresh the sharing release foundation 2026-08-05 23:14:01 +02:00
Marc-André Bombeck 553e0b4a28 Merge commit 'd07b9249c' into release/v1.37.0 2026-08-05 23:04:39 +02:00
Marc-André Bombeck d42d2bb784 Merge branch 'main' into release/v1.37.0 2026-08-05 23:04:36 +02:00
Marc-André Bombeck d07b9249c8 fix: complete dashboard hydration 2026-08-05 23:03:17 +02:00
Marc-André Bombeck 1a70044af9 fix: preserve delegated dose facts on replay 2026-08-05 22:48:31 +02:00
Marc-André Bombeck e89374d5b3 Merge remote-tracking branch 'origin/main' into release/v1.37.0 2026-08-04 17:17:50 +02:00
Marc-André Bombeck bee02004ba Merge pull request #716 from MBombeck/docs/changelog-slot-upsert
Name the refusal the last release notes left out
2026-08-04 17:17:46 +02:00
Marc-André Bombeck da3cabb55f Give a grant a section set and a third level
A grant has meant one thing since it shipped: the whole record, to read or to
add to. This lays the words for the two shapes the rest of the sharing work
needs — part of a record, and management of one — while changing what no
existing grant does.

`ShareDomain` is a closed set of eight sections in `src/lib/sharing/scope.ts`,
clustered from the delegable read surfaces rather than invented, plus the
distinguished `record` for the routes that read across them. It never converts
to a `ModuleKey` and never imports one: two masks, two questions, no shared
spelling, because the day they share a name is the day somebody makes one
imply the other, and a module the owner enabled is not a section the owner
shared.

`account_grants.scope_json` is NULL on every row that exists, and NULL is the
entire record — the answer those rows were consented as, so no backfill and no
re-consent. A non-NULL value is read through one fail-closed normaliser: a
blob it cannot parse opens nothing, including a section the blob happened to
name. That is the deliberate inverse of the module preference normaliser,
which fails open on purpose; both do the safe thing with a value nobody can
read, and the safe thing differs because one answers an authorization question
and the other a presentation question.

`MANAGE` joins the level enum, ordered above WRITE so a write grant can never
satisfy it, and carries no scope at all: management of part of a record
promises a boundary that cannot survive an edit, so the invite path refuses to
write one.

`requireRecordAuth` takes the section as a second required argument. The
requirement is the lever — a delegable route without a classification does not
typecheck, so the set of classified routes cannot fall behind the set of
delegable ones. All fifty-seven modules carry theirs. The structural guard
freezes each against the production vocabulary, fails when a module's own arms
disagree, and pins a non-zero count of resolved sections so a matcher that
stopped reading the argument fails instead of agreeing with everything.

`requireGuardianAuth` is exported and reaches nothing yet. It gates on the
managed-profile marker rather than on the grant, so an adult who granted
management of their own record cannot arrive at that record's settings by any
argument about what MANAGE means: widening MANAGE would widen the record
resolver and would not touch this one. Its frozen list lands empty, with the
declaration site as the positive control that keeps "nothing reaches it" a
measurement rather than a renamed symbol.

`users.managed_profile_at` says since when a record is one somebody else runs.
A timestamp and not a boolean, for a reason the schema has to keep possible:
clearing it is the handover, and the grants and the activity trail span it
untouched.
2026-08-04 17:11:40 +02:00
Marc-André Bombeck cd3f628f98 Name the refusal the last release notes left out
The fix that stopped a delegate overturning a recorded dose through the second
intake route landed on the trunk with no line in the notes. A change that
alters what somebody else may do to your record and says nothing about it is
the shape this project keeps rediscovering, and a release assembled from these
notes would have shipped it silently.
2026-08-04 16:44:24 +02:00
Marc-André Bombeck 03877a0971 Merge pull request #715 from MBombeck/fix/slot-upsert-outcome-change
The v1.36.1 audit follow-ups, and the way round the intake refusal
2026-08-04 15:52:06 +02:00
Marc-André Bombeck 24922b2787 Close the way round the delegated-intake refusal
v1.36.1 stopped a delegate changing a dose the owner had already recorded, and
it stopped them on one route. The sibling `POST /api/medications/[id]/intake`
reaches the same rows through the shared slot upsert, where the only existing
protection is against a pending sync echo washing out a recorded dose. An
explicit skip is not an echo: it fell through, flipped the outcome, and the
inventory the take had consumed was refunded on the way. So the refusal I added
was a door with the next one left open.

The rule compares OUTCOMES rather than refusing every write onto an actioned
slot, and the reason is the third case in the new contract. A double tap, an
offline replay and a retry after a partial batch all re-post the same decision,
and a caregiver hits all three; refusing those would make the feature
unreliable exactly when somebody is standing in a kitchen with a pill box. Same
decision applies, a different one is refused.

The check rides into `applyCanonicalSlotWrite` rather than sitting at the call
site, because that is where the existing row is already loaded: no extra query,
and nothing between the read and the update for a concurrent write to slip
through. A refused attempt files under the owner with the same action name the
sibling route uses, so it reaches the activity panel the same way.

Three integration cases, and each asserts the row rather than the status alone
— a 403 that had already written the flip would read as protection while being
the opposite. Watched fail: with the delegate flag forced off, the flip returns
201 while the replay and the owner's own correction stay green.
2026-08-04 15:32:40 +02:00
Marc-André Bombeck 25e86b36b3 Close the delegated-access gaps the release audit left open
Seven findings from the adversarial pass before v1.36.1 was tagged. One
blocking defect shipped in that release; these did not, and they are all places
where somebody looking after another person's health record meets a wall with
no explanation, or where a guard cannot fail.

The document vault was the largest. `/documents` is marked as a shared
destination, so the shell offers it under a switch, and every read behind it
resolved the caller instead of the record: the vault painted a query-error card
and the illness view painted another beside it. That is the same failure the
release describes as fixed on the dashboard. Five GET arms move to the record
resolver now, and only the GET arms: the list, one document, its file, its
thumbnail and the vault's usage payload, which the filter bar is built from.
Uploading, retyping, deleting, linking a document to an illness and every AI
verb stay with the owner, and the two reads that spend decryption CPU key
their quota on the person calling rather than the record, the rule
`medications/compliance` already follows.

Logging a value on a metric you track yourself leaves the admitted set. It was
admitted, named on the consent screen in six languages, and unreachable: the
only form that posts one sits on a page a shared record does not open, and the
component that renders it says so in its own comment while returning null. It
is the third route the rule that withdrew allergies and family history fitted
exactly, and it was applied to two of the three. Reading those values stays.

Two guards could not fail, and both were proved by mutation before and after.
The prefetch guard checked rule three with two regexes: one was satisfied by
the doc comment every page carries, the other missed an aliased import, and
the pair stayed green with the dashboard genuinely prefetching off the
switch-blind session. It reads the AST now, resolves aliases through the
module's own import table, and pins the five prefetching pages by name so a
page that stops being detected is loud. The activity verb map decided
membership on a literal `requireRecordAuth("write")`, so putting the argument
on its own line, which is what the formatter does the moment the call grows,
dropped a route out of the scan and turned a genuinely-red run green. Both
counts are of matches now rather than of files walked.

The rest are single instances of rules applied everywhere else. "Take all due"
was withheld on a note saying it rides the bulk intake route; it does not, and
its own docblock says why not, so a helper with five morning tablets tapped
five times for nothing. Marking a dose skipped is offered wherever marking it
taken is. A form could be opened in the frame before the app knew whose record
was on screen and then stood there once the answer arrived, on the capture
sheet and on the dashboard's quick-entry sheets. Two more copies of the intake
toast were still building their own, one of them with an Undo pointing at a
route no delegate may call. The customise link on the mood page led to a page
that exists to say it is not part of what was shared. And the access-level
radios on the invitation screen are hidden by design with no focus ring on
their label, so keyboard focus moved invisibly across the one screen where
somebody grants write access to their record.

Three new structural guards, each watched fail first: the customise link sits
inside a capability branch on every surface a delegate can reach, every intake
surface confirms through the one shared decision, and the batch sweep is
offered at the level that admits it.
2026-08-04 14:55:32 +02:00
Marc-André Bombeck 80ecbd7454 Merge pull request #714 from MBombeck/fix/audit-v1361
Stop a delegate deferring somebody else's medication reminders
2026-08-04 13:10:00 +02:00
Marc-André Bombeck 69343c8820 Stop a delegate deferring somebody else's medication reminders
Found by an adversarial pass over the release candidate before it was tagged,
and it is the reason the tag waited.

`POST /api/medications/intake` is admitted for delegates because a caregiver
standing next to the patient has to be able to say the tablet went down. It is
an update, though, and the same body can carry two other things. Snoozing
writes `snoozedUntil` on the OWNER's medication row, and the reminder cron
skips that medication for as long as the stamp is in the future. The field
takes any future instant. So somebody with write access could stop another
person's medication reminders for years, and three things made it quiet: the
owner is deliberately not notified of a delegated snooze, the activity feed
renders the whole family as "marked a dose", and the only accurate trace was a
line in the admin audit log.

The second was flipping a dose the owner had already recorded — taken to
skipped and back, which rewrites their compliance history and refunds
inventory. The consent screen promises that changing what is already there
stays with the owner.

Both refuse for a delegate now and stay open to the owner, who is the only
person either was ever for. A refused attempt is filed under the owner and gets
its own sentence in the activity panel rather than borrowing the one for
marking a dose, because folding them together is what made the gap dangerous.

Two more from the same pass:

The consent notice named allergies among the things a delegate may add. That
left the admitted set before this release shipped, and it said so in six
languages on the one screen where somebody decides who may write into their
health record. It also omitted half of what IS admitted. The copy now matches
the frozen list, and the test asserts the withdrawal rather than only the
presence of the rest.

The banner told a WRITE delegate nothing at all — the mode line rendered only
in the read case, guarded by a comment stating that write grants did not exist
yet. This is the release that made them exist. It matters that the banner say
it, because the rule that a refused control is absent rather than disabled
rests on the banner naming the mode globally.

And a third instance of the substitution this release already fixed twice: the
BMI chart divided the owner's weights by the height of whoever was looking.
Inside a shared record it draws nothing now rather than a number belonging to
two different people.
2026-08-04 12:30:01 +02:00
Marc-André Bombeck 7ff420477c Merge pull request #713 from MBombeck/release/v1.36.1
chore(release): v1.36.1
2026-08-04 12:00:34 +02:00
Marc-André Bombeck d77a3fe8d7 chore(release): v1.36.1 — a second person can contribute, and the front door works 2026-08-04 11:44:13 +02:00
Marc-André Bombeck b5227495c1 Merge pull request #712 from MBombeck/work/sharing-write-integration
Delegated write access, and the front door a delegate lands on
2026-08-04 11:40:17 +02:00
Marc-André Bombeck 87e908decd Ask the menu whether it opened, not the trigger that just disappeared
My own bug, and it produced a failure that pointed at the opposite of the
cause. The helper clicked the trigger and then re-read the trigger's
`data-state` to decide whether the menu had opened. Radix marks the rest of the
page `aria-hidden` while a menu is open, and Playwright's role locators skip
anything hidden from the accessibility tree — so a trigger found through
`getByRole` stops matching the instant the click succeeds. Reading its
attributes then does not report "still closed"; it hangs until the test budget
runs out, and the log blames the trigger for not being there.

The check is on the menu now. Both journeys pass locally, and the reason is in
the file so the next person does not have to lose an evening to it.
2026-08-04 11:21:51 +02:00
Marc-André Bombeck 10e113e537 Give the add-measurement journey the dashboard's budget, not the default one
It kept dying at thirty seconds on the quick-add trigger. The trigger was not
the problem: the dashboard route segment suspends behind its server render and
shows `loading.tsx` until that resolves, and on a shared runner with the whole
suite in flight that has overrun the default test budget. Raising the locator
timeout achieved nothing, because the test itself was the thing expiring.

So the wait is now on the skeleton going away rather than on the network going
quiet — `networkidle` says nothing about whether a suspended segment resolved —
and the budget belongs to the page rather than to the default. Every assertion
about the round trip stays exactly as tight as it was.
2026-08-04 09:26:43 +02:00
Marc-André Bombeck 17a2ec3328 Give the trigger the same patience the click it replaced had
`.click()` carries Playwright's 30 s actionability wait. The visibility check
that replaced it ran on the default expect timeout, so the helper made the wait
shorter than the code it stood in for, and a dashboard that was slow to paint
failed on the trigger rather than on the menu.
2026-08-04 02:11:22 +02:00
Marc-André Bombeck 9eb5db4c35 Close the same hydration race on the three remaining menu triggers
The add-measurement journey and the two accessibility steps that open a
dropdown all did what the water journey did: wait for the network, click the
trigger, then wait for a menu item. All three clicked markup React had not
wired up yet, and the add-measurement one timed out on the trunk's own runner
for exactly that reason.

They open through the same helper now. The documents bulk-bar menu keeps its
plain click deliberately: it fires after selecting fifty rows, so hydration is
not in question there and a retry would only hide a real failure.
2026-08-04 01:52:02 +02:00
Marc-André Bombeck ef63d7b458 Merge remote-tracking branch 'origin/main' into work/sharing-write-integration 2026-08-04 01:31:07 +02:00
Marc-André Bombeck a08aa342b2 Pin ip-address past the leading-zero parsing advisory
Address4 decoded a leading-zero octet as decimal, so `010.0.0.1` parsed as
10.0.0.1 instead of being rejected. That is precisely the alternate-notation
class `isPublicUrl` was written to catch, and this copy arrives transitively
under the MCP SDK's rate limiter, where nothing of ours screens the value
first. The production tree resolved 10.2.0 while the dev tree already had a
fixed one, so the override names the floor rather than trusting resolution.
2026-08-04 01:30:57 +02:00
Marc-André Bombeck 7a713c33d0 Stop the dashboard console assertion from failing on a defect it does not own
The assertion demanded an empty console on `/` and was catching React's
hydration mismatch, intermittently, on this branch. Measured before touching
it: a production build of the trunk with the SSR prefetch on — the shipped
configuration — raises #418 on three loads out of three, on both viewports. A
control worktree on plain main behaves identically, so nothing here caused it.
With the prefetch off, which is what this suite runs against, neither tree
raises it in isolation; it appears only when the whole suite is loading the
machine enough to change the streaming order.

So the check was failing a branch for a defect that ships today, and doing it
unreliably enough that it read as a regression. The one message is exempted,
with the measurement and the mechanism at the filter so nobody has to
rediscover either, and the exemption names its own removal condition. Every
other console error still fails this test.

The defect itself is written down rather than waved through: the server streams
the route-level skeleton while the client's first pass renders the dehydrated
snapshot, and React throws the server tree away. Which means the prefetch that
exists to make this page paint fast is paying its cost and delivering none of
its benefit.
2026-08-04 01:18:15 +02:00
Marc-André Bombeck 59aa6b94f4 Merge remote-tracking branch 'origin/main' into work/sharing-write-integration 2026-08-03 22:10:27 +02:00
Marc-André Bombeck f41605efba Close two high advisories on the outbound path
`undici` moves to 8.10.0 and the `fast-uri` override rises to 3.1.5. Both were
published as high after the last run on the trunk, so this is new information
rather than neglect, and both matter here: undici is what backs `safeFetch`,
which is the one documented egress boundary and the place the connect-time
DNS-rebinding pin lives.

The undici advisory is a cross-user information disclosure and a parse-time
crash through degenerate private cache directives. `fast-uri` arrives four ways
through transitive dependencies and the existing override was pinned one patch
short of the fix.

The safe-fetch dispatcher suite passes against the new client, which is the
part that had to be checked rather than assumed: the pin reaches into undici's
connect hook and a client bump is exactly where that could quietly stop being
enforced.
2026-08-03 22:10:15 +02:00
Marc-André Bombeck 64c2f7410a Wait for the menu to open, not for the network to go quiet
The water-capture journey clicked the dashboard quick-add trigger after
`waitForLoadState("networkidle")` and then waited thirty seconds for a menu
item that never arrived. The failure snapshot shows the page rendered, the
trigger present, and no menu anywhere: the click landed on server HTML that
React had not attached a handler to yet, and the one click the test had was
spent before hydration.

`networkidle` cannot close that window, because the trigger is in the first
HTML and exists long before the client bundle finishes. The gate has to be the
element's own state. `openMenu` clicks and confirms the trigger reports itself
open — Radix stamps `data-state`, the hand-rolled mobile capture button carries
`aria-expanded` off React state — and spends another click if it does not,
because the problem is a lost event and waiting longer for a swallowed click
achieves nothing. Out of attempts it fails naming the state the trigger was
actually in, rather than letting the caller time out on a menu item that was
never going to appear.

This is a race the spec always had; it surfaces when the machine is loaded
enough to push hydration past the click, which is why it reads as a
branch-specific regression when it is not one. The tour passthrough spec keeps
its single un-retried click on the same trigger: proving that exactly one click
reaches the button through the overlay is that test's entire point.
2026-08-03 21:47:58 +02:00
Marc-André Bombeck 7eed26eb01 Merge remote-tracking branch 'origin/work/side-effect-backup' into work/sharing-write-integration 2026-08-03 21:18:13 +02:00
Marc-André Bombeck 75644bc3d2 Carry recorded side effects through the backup and back
MedicationSideEffect was classified as backed up and was not carried: the
export wrote nothing and the restore had nothing to read, so a restored
account kept the drug and lost the reason someone may have stopped taking it.
Delegated write access sharpens that — a side effect is one of the things a
second person can contribute, and it was the contribution a restore dropped.

The rows ride inside their medication, like the schedules beside them. A
top-level array would have to carry `medicationId` and survive a restore that
mints a fresh id for a portable file, which is the remap the intake events
already work around by drug name; a nested create has no id to remap, because
Prisma binds the child to whatever id the parent row actually got.

The note follows the measurement contract for the same dual-column
arrangement: a portable export carries the decrypted note and no ciphertext, a
disaster-recovery payload carries the ciphertext verbatim, and the restore
re-encrypts a legacy plaintext row rather than writing plaintext back into the
column.

Move the model from COVERAGE_PENDING to TWO_ENDED_MODELS, and settle the claim
where a written verdict cannot: the round trip seeds a side effect, exports
through the real builder, empties the account and reads the row back out of
the real restore route with its category, entry, severity and note intact.
Both halves were excised to check the test can fail — the restore branch turns
the count red, the payload turns the field values red.
2026-08-03 21:15:45 +02:00
Marc-André Bombeck a004d2358e Merge branch 'work/shared-front-door' into work/sharing-write-integration
# Conflicts:
#	src/__tests__/delegable-surface-guard.test.ts
2026-08-03 21:15:37 +02:00
Marc-André Bombeck b817a2d47e Merge remote-tracking branch 'origin/fix/delegated-fix2' into work/sharing-write-integration 2026-08-03 21:15:01 +02:00
Marc-André Bombeck 508cc8a60a Let a delegate read the dashboard they land on
Ten routes on `/` refused with `undeclared_mode`, which made the first page
of account sharing the only page in it that does not work. Each one now
declares a mode, per route rather than as a class.

Eight are record reads: the dashboard snapshot, the Today digest, the badge
grid, the Coach nudge signal and reminder ledger, the medication low-stock
thresholds, and the two presentation blobs. The old objection to admitting an
aggregate — a summary can carry a finding from a module the grant does not
cover — does not hold while a grant is whole-record and all-or-nothing. Every
admission site names that, so the day per-module scope lands the aggregates
are findable.

The layout routes split their verbs. Reading the owner's arrangement is right
and, for the dashboard, forced: the snapshot already carries the layout and
the client seeds the same cache cell from it, so an actor answer would put two
people's layouts in one key. Writing it is not a caregiver's job, so the PUT
and DELETE stay bare and refuse. Same on the medication list, where the stored
order names the owner's medication ids and means nothing anywhere else.

Two are actor surfaces: the UI language belongs to the person reading the
screen and must not be transplanted onto the record, and the feature-flag
matrix reads the settings singleton and no user row at all.

Also fixes a second instance of the delegate-data-under-owner-banner defect,
on the same page: the dashboard's client-side band fallback derived blood-
pressure targets and the weight range from `/api/auth/me`, which answers about
the caller, and painted them over the record's charts. Under a switch it now
derives nothing and waits for the snapshot's own bands.

The integration suite drives every admitted route with both accounts seeded,
proves the two answers differ, and then demands the owner's back.
2026-08-03 21:12:35 +02:00
Marc-André Bombeck 1968616219 Merge pull request #698 from MBombeck/dependabot/npm_and_yarn/shadcn-4.16.0
build(deps-dev): bump shadcn from 4.13.0 to 4.16.1
2026-08-03 20:57:31 +02:00
Marc-André Bombeck 89c872a169 Pin the two writes this branch withdrew, instead of leaving their old proof
Taking `POST /api/allergies` and `POST /api/family-history` out of the
delegable set moved one end and left the other: the integration suite still
asserted that a delegate holding a WRITE grant gets a 201 from both, so ten
cases went red on a decision that was deliberate.

They are pinned the other way round now, with the reason in the file. A
delegate is refused at either grant level, nothing lands under either
account, and — the leg that matters most and that nothing else here covered —
the owner's own unswitched write still succeeds. Withdrawing a delegated
write by breaking the ordinary one would have been the worse bug.
2026-08-03 20:56:04 +02:00
Marc-André Bombeck 029c526252 Give the intake purge a tombstone, and two health writes their audit row
The dose-history purge was the one destructive verb in the intake family
that removed rows outright. Both siblings, the single-event DELETE and the
bulk delete, stamp `deletedAt` and bump `syncVersion`; the purge called
`deleteMany`, so a mis-tap was final and a client offline at purge time kept
every row forever, because a row that no longer exists produces no tombstone
for the sync feed to carry. It tombstones now, scoped to live rows so a
second purge counts zero. No inventory refund: a purge wipes a history as
bookkeeping, and refunding every dose ever taken would inflate the current
container count instead.

The manual water quick-add and the lab-result un-delete both wrote health
data and reached only the wide event, which expires. Months later nothing
could answer who put a day's total there or who brought a reading back, and
with a second person able to act on a shared record that question has a
second possible answer. Both write a durable row now, named after the
neighbours they sit beside.

The refused-delegation audit comment claimed the row was written for the
owner's benefit. It is not: it is filed under the caller, it is only written
for a header refusal, and a header names an account the caller merely
asserts. Filing under that claim would let anyone write rows into any
account's activity feed by naming it. The comment says what the row is now,
and points at `recordDelegatedAccess`, which is the half the owner does see.

Two comments in the biomarker surfaces still claimed the `SetNull` foreign
key left the readings behind when a marker is deleted. That stopped being
true when delete became a "drop this and its history" action and the
confirmation copy was rewritten in six locales to say so.

The purge route gains a call-shape assertion rather than a count assertion,
because a count comes back identical from a `deleteMany`. The lab restore
route had no test at all and now has one.
2026-08-03 20:49:27 +02:00
Marc-André Bombeck 837ebcfeea Name the intake action the route actually writes, and stop awaiting the delegate notice
The activity feed maps an audit action to a sentence. The web client posts to
/api/medications/[id]/intake, which has audited as `medication.intake` since
v1.0.0, but the map only knew `medications.intake.update` — so a delegate
recording a dose showed up in the owner's feed with no verb at all. Both
spellings are recognised now, plus `measurement.create.batch`.

A new test reads the audit actions straight out of every route that calls
requireRecordAuth("write") and fails when one has no case in the map, so the
next route to be opened for delegates cannot land a silent gap.

The delegate notification is fire and forget now, like every neighbouring
side effect. The dispatcher awaits each channel in the cascade, so one
unreachable channel added its whole timeout to the request of the person
standing next to the patient waiting for a dose to register. The integration
test polls the ledger rather than relying on the await, so nothing about the
proof weakens.
2026-08-03 20:34:53 +02:00
Marc-André Bombeck 582cd79aa1 Merge remote-tracking branch 'origin/main' into fix/delegated-fix2 2026-08-03 19:19:34 +02:00
Marc-André Bombeck 0b1a6c1b09 Make the delegated-write journey actually run
Every test in e2e/delegated-writes.spec.ts had been skipping since the
day the invitation form shipped its level control. The skip guard looked
for data-slot="grant-invite-level"; the control landed as
"grant-invite-access-option". The file said out loud what to change and
nobody changed it, so a quiet skip and a passing suite read the same in
a CI summary.

Two assertions inside it had never been executed and were both wrong:
the header button reads "Add", not "Add measurement", and the form opens
on blood pressure, which has no `value` field. Fixed against stable
attributes rather than viewport text, with data-slot="measurement-add"
added to the control the journey clicks.

Adds the deep-link leg the SSR suite cannot hold: a query parameter is
the same affordance as the button, and ?add= / ?new=1 open exactly what
the resolved level admits.
2026-08-03 19:12:11 +02:00
Marc-André Bombeck ebf032158e Give the intake toast one decision, and stop admitting two writes nothing calls
Three surfaces record a dose and all three had to reach the same two
conclusions inside somebody else's record: name the record, and drop an
Undo the server refuses. Two learned it and the dose ledger did not,
because the ternary was written out three times. It is written once now,
in the file the other two already share, with its own test.

POST /api/allergies and POST /api/family-history leave the frozen
delegable write set. The argument that admitted them still stands — an
allergy is the single most useful thing a caregiver can contribute — but
the only surface that posts to either lives in Settings, which a switch
closes, so no delegate could reach the form at any level. That is a
permission frozen ahead of the caller for it, and the list is built the
other way round on purpose.

Both delegable READ arms stay. A caregiver reading the allergy list is
what the feature is for; only the contribute step waits, and it comes
back in the same diff as the surface that offers it.
2026-08-03 18:47:42 +02:00
Marc-André Bombeck e26a8f3824 Render the withheld controls in the affordance suite
Three of the newly gated surfaces are query-backed, so the suite gains a
query client and a cache seed rather than a hook mock: the component
under test stays the real one. Each leg asserts the rail, the card and
the reminder row are still THERE — only the mutating control is gone.

Breaking each gate in turn puts every leg red.
2026-08-03 18:38:23 +02:00
Marc-André Bombeck 45363edb77 Withhold the controls a shared record refuses
Nine surfaces offered a delegate an action the server declines, and the
switch had never been asked about any of them.

The Today rail's dismiss and the coach check-in's keep / let-go write
through routes that resolve the caller, so both refuse under a switch;
they now ask canManage and are absent at either grant level. A priority
action with no href and no handler is no longer rendered as an inert
button at all — the type carries that rule now.

The Vorsorge dashboard card offered the mark-done that /checkups already
withholds, and the checkups list branch inlined its own ungated copy of
the button the cards branch gates, so which view a browser last chose
decided whether the action appeared. Both bind canManage.

The chart overlay cog persists through a route that resolves the caller
and stores a preference belonging to the person rather than the record.
Gated once in the control so the three chart wrappers cannot drift.

Three query parameters opened sheets past a gated button: ?add=<TYPE> on
measurements, ?new=1 on medications, and ?edit=1 on a medication detail,
the last of which opens a wizard refused at both levels. A deep link is
the same affordance as the control that produces it.

The efficacy retarget dial rewrites a setting the owner chose. The
episode documents card offered a link and an upload the vault gates on
the same endpoint throughout. And the dose ledger built its own success
toast, missing both the Undo suppression and the "saved to" receipt its
two siblings already carry — the one a delegate met on every dose.

The Coach drawer is not mounted inside a shared record, so every button
calling askCoach() opened nothing. The launch provider now publishes no
value there and each entry point's existing null check does the rest;
the documents sheet, the one that rendered without checking, now checks.
2026-08-03 18:33:48 +02:00
dependabot[bot] 9e61e73dec build(deps-dev): bump shadcn from 4.13.0 to 4.16.1
Bumps [shadcn](https://github.com/shadcn-ui/ui/tree/HEAD/packages/shadcn) from 4.13.0 to 4.16.1.
- [Release notes](https://github.com/shadcn-ui/ui/releases)
- [Changelog](https://github.com/shadcn-ui/ui/blob/main/packages/shadcn/CHANGELOG.md)
- [Commits](https://github.com/shadcn-ui/ui/commits/shadcn@4.16.1/packages/shadcn)

---
updated-dependencies:
- dependency-name: shadcn
  dependency-version: 4.16.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-03 16:15:56 +00:00
Marc-André Bombeck a0fc404fb8 Merge pull request #697 from MBombeck/dependabot/npm_and_yarn/tanstack/react-query-5.101.4
build(deps): bump @tanstack/react-query from 5.101.2 to 5.101.4
2026-08-03 18:13:01 +02:00
Marc-André Bombeck e621da670c Merge pull request #696 from MBombeck/dependabot/npm_and_yarn/react-hook-form-7.83.0
build(deps): bump react-hook-form from 7.81.0 to 7.83.0
2026-08-03 18:12:53 +02:00
Marc-André Bombeck 5da64628ec Merge pull request #695 from MBombeck/dependabot/npm_and_yarn/eslint-config-next-16.2.12
build(deps-dev): bump eslint-config-next from 16.2.6 to 16.2.12
2026-08-03 18:12:46 +02:00
Marc-André Bombeck 3a7fe5f1aa Merge pull request #694 from MBombeck/dependabot/npm_and_yarn/prisma/adapter-pg-7.9.1
build(deps): bump @prisma/adapter-pg from 7.8.0 to 7.9.1
2026-08-03 18:12:38 +02:00
Marc-André Bombeck 33e9cc2784 Merge pull request #693 from MBombeck/dependabot/github_actions/docker/login-action-4.6.0
build(deps): bump docker/login-action from 4.5.1 to 4.6.0
2026-08-03 18:12:30 +02:00
Marc-André Bombeck 1d28aeecf9 Merge pull request #710 from MBombeck/fix/delegated-fix1
Never seed one person's record into another person's page
2026-08-03 17:09:35 +02:00
Marc-André Bombeck 24c45ad9e9 Return the sharing journey to the page Accept lives on
The coach positive control navigates to the dashboard to prove the launcher
renders for a delegate in their own record. It left the browser there, and the
next step clicks Accept, which lives on the access page. The click waited out
its timeout against a page that does not carry the button.

An assertion inserted mid-journey has to restore the state it borrowed.
2026-08-03 15:56:28 +02:00
Marc-André Bombeck 154449d77a Stop a prefetching page from seeding the wrong person's record
A server-prefetching page dehydrates a health record into the HTML and
seeds it into the client's query cache under the key the client cell
reads. That copy is only right when the account the page read is the
account the client's route would answer with, and under an account
switch it never is: `getSession()` answers who is CALLING, deliberately
and permanently, so all five prefetching pages seeded the delegate's own
rows into a document opened on somebody else's record. The dashboard was
the worst of it — snapshot, digest and widget layout ride routes that
refuse the refetch, so the delegate's numbers stayed on the owner's
dashboard, while the chart row refetched to the owner and left the page
showing two people at once under a banner naming one.

Resolve the session through `getUnswitchedSession()` instead, which
answers null while the browser is acting on another record. The prefetch
steps aside and every cell fetches through its route, which is where the
grant check lives. Resolving the owner here instead was the other
candidate and is worse: the grant check has exactly one home, half of
what these pages prefetch rides routes that declared themselves not
delegable, and re-deriving it in an RSC would be a second program
deciding whose record this is.

Close the two shell-level doors beside it. The Coach launcher, its
drawer mount and the module tour hang off `<AuthShell>` rather than off a
route, so dropping Insights and Coach from the navigation under a switch
left them painting on every page in the record and on the unavailable
panel too — one tap from a drawer whose every action refuses, and a
`POST /api/insights/coach/seen` fired by opening it at all. All three
bind `useRecordCapabilities()`, the same resolved grant the banner and
the switcher read. Absent, not disabled.

The prefetch rule is structural: the guard walks the app tree, so a sixth
prefetching page is covered the moment it lands rather than the moment
somebody remembers. The pages stay on the session-surface allowlist with
their reasons rewritten, because a wrapper one directory deeper is the
easiest way for a surface to walk out of a guard.
2026-08-03 13:49:19 +02:00
dependabot[bot] 15bd7e660a build(deps): bump react-hook-form from 7.81.0 to 7.83.0
Bumps [react-hook-form](https://github.com/react-hook-form/react-hook-form) from 7.81.0 to 7.83.0.
- [Release notes](https://github.com/react-hook-form/react-hook-form/releases)
- [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md)
- [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.81.0...v7.83.0)

---
updated-dependencies:
- dependency-name: react-hook-form
  dependency-version: 7.83.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-03 11:03:27 +00:00
dependabot[bot] ad18303f7e build(deps-dev): bump eslint-config-next from 16.2.6 to 16.2.12
Bumps [eslint-config-next](https://github.com/vercel/next.js/tree/HEAD/packages/eslint-config-next) from 16.2.6 to 16.2.12.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/commits/v16.2.12/packages/eslint-config-next)

---
updated-dependencies:
- dependency-name: eslint-config-next
  dependency-version: 16.2.12
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-03 11:03:23 +00:00
dependabot[bot] 02ff6dff2b build(deps): bump @tanstack/react-query from 5.101.2 to 5.101.4
Bumps [@tanstack/react-query](https://github.com/TanStack/query/tree/HEAD/packages/react-query) from 5.101.2 to 5.101.4.
- [Release notes](https://github.com/TanStack/query/releases)
- [Changelog](https://github.com/TanStack/query/blob/main/packages/react-query/CHANGELOG.md)
- [Commits](https://github.com/TanStack/query/commits/@tanstack/react-query@5.101.4/packages/react-query)

---
updated-dependencies:
- dependency-name: "@tanstack/react-query"
  dependency-version: 5.101.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-03 11:03:20 +00:00
dependabot[bot] 8779fb9cc9 build(deps): bump @prisma/adapter-pg from 7.8.0 to 7.9.1
Bumps [@prisma/adapter-pg](https://github.com/prisma/prisma/tree/HEAD/packages/adapter-pg) from 7.8.0 to 7.9.1.
- [Release notes](https://github.com/prisma/prisma/releases)
- [Commits](https://github.com/prisma/prisma/commits/7.9.1/packages/adapter-pg)

---
updated-dependencies:
- dependency-name: "@prisma/adapter-pg"
  dependency-version: 7.9.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-03 11:03:01 +00:00
dependabot[bot] 95293461f2 build(deps): bump docker/login-action from 4.5.1 to 4.6.0
Bumps [docker/login-action](https://github.com/docker/login-action) from 4.5.1 to 4.6.0.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/abd2ef45e78c5afb21d64d4ca52ee8550d9572c7...dbcb813823bdd20940b903addbd779551569679f)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: 4.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-03 11:02:10 +00:00
Marc-André Bombeck 326db73883 Merge pull request #709 from MBombeck/work/dw-e
Stop offering a delegate buttons the server will refuse
2026-08-03 12:59:04 +02:00
Marc-André Bombeck 134bf204dc Merge pull request #708 from MBombeck/work/dw-d
A delegate can add to the record they were given
2026-08-03 12:58:08 +02:00
Marc-André Bombeck 251b534660 Merge remote-tracking branch 'origin/main' into work/dw-e 2026-08-03 12:25:34 +02:00
Marc-André Bombeck 748def03bd Say what somebody did, not that they did something
The activity view told an owner that a delegate acted on their record. With
delegated writing it can say which act: added a reading, recorded a lab result,
marked a dose. The mapping already existed as a pure module with its own test
and a fallback for anything unmapped; this is the wire it was missing.
2026-08-03 12:24:05 +02:00
Marc-André Bombeck 59965e141e Drive a delegated write through the browser, once the level control lands
The component suite runs without a DOM renderer, so it proves what a page
paints and never what a button does. That is the right shape for this work,
because the property that matters most is a control being absent — but it
leaves the other half unproven: a form that renders is not a form that
submits, and a write that reaches somebody else's record is exactly the thing
worth watching happen.

The journey stands down while the invitation form has no level control, since
minting a WRITE grant behind the UI's back would prove a path no person can
walk. It names the control it is waiting for, so a run that skips while the
control exists reads as a bug here rather than an absence upstream.
2026-08-03 12:17:15 +02:00
Marc-André Bombeck d5a9360c52 Give the caregiver a front door and a receipt
Sharing lived in a settings panel and a menu three levels deep. That is where
a grant is managed and not where it is used: somebody who opens this app every
morning to check on a parent does not go through settings to do it, and the
design standards draw the same line, settings being account utilities rather
than feature destinations. So the dashboard carries one compact card listing
the records shared with this account, each row a one-tap switch through the
existing flow.

It is a doorway and not a preview. No numbers, no last reading. A slice of
somebody else's record on the delegate's own dashboard would sit outside the
one frame the design leans on, the banner naming the record you are inside.
An account nobody has shared with sees nothing at all.

The other half is the receipt: a reading, a lab result or a dose recorded
under a switch now says which record it landed in, because "Saved" alone is
the confirmation somebody acting for another person does not need. The undo
on the dose toast goes at the same time, since a delegate cannot remove what
they recorded and an undo they can see is one the server refuses.

Also here: the lines the owner's activity view owes each admitted verb, as a
translated mapping with a fallback, so a later release filing a verb it has
never heard of still renders a sentence rather than a blank row.
2026-08-03 12:12:08 +02:00
Marc-André Bombeck ab53d42874 Keep dose marking under a switch, and nothing else on medications
Marking a dose taken or skipped is the verb the delegation was written for:
somebody looking after a parent confirms the morning tablet. Adding a
medication and noting a side effect come with it. The card menu keeps only
what survives and disappears entirely when nothing does.

Four detail tabs leave the registry inside somebody else's record, because
their whole content is owner work: the schedule editor and its plan history,
the supply ledger, the external-token row, and the advanced surface holding
the wizard, the import and the destructive zone. A stale deep link into one
lands on the landing tab, the way an inapplicable tab already does.

The take-all-due sweep goes too. It rides the bulk intake route, which the
delegation does not name, and a control that half-works is worse than one
that is not offered.
2026-08-03 12:11:52 +02:00
Marc-André Bombeck 7817632385 Hide the controls a delegate cannot use, surface by surface
Every page a switch can reach now renders the controls the grant covers and
none of the others. Readings, lab results and illness entries keep their add
path at WRITE and lose edit, delete and selection at both levels. Mood,
screeners, cycle days, checkup reminders and the document vault lose every
mutation control at both levels, because no grant admits those verbs and the
routes behind them refuse a switched session outright.

Absent, not disabled, throughout. The banner already says whose record this
is, so no chip repeats it beside each missing button; the one exception is
the measurements empty state, where somebody who may add will look for the
edit control beside the row they just entered, and one muted line says where
the limit is.

Two dead ends went with them: the custom-metric section on the measurements
page linked every row into a route the shell turns a delegate away from, and
the wrench glyphs point at settings pages sharing does not cover.
2026-08-03 12:11:42 +02:00
Marc-André Bombeck bc43a9f062 Drop the shared delete, bulk and capture affordances under a switch
Three controls carry most of the app's mutation surface between them. The row
delete is spelled once for measurements, lab results, biomarkers, allergies,
family history, custom metrics and medication supply; the selection bar is
the only bulk delete; the capture picker is the fastest path to four entry
forms on a phone and bypasses every page header.

Deleting belongs to the owner at every grant level, so the first two are
absent inside somebody else's record rather than greyed out: a disabled bin
still claims the row is the delegate's to remove. The picker keeps the two
kinds a delegation admits and drops a mood entry and a glass of water, which
the server refuses under a switch; when nothing survives, the bar's plus
button goes with them instead of opening an empty sheet.
2026-08-03 12:11:29 +02:00
Marc-André Bombeck 785a1eacfc Freeze the delegable write set and drive it against Postgres
The surface guard grows a write leg. Membership is decided by the argument
a module passes to the record resolver, not by the identifier, because a
delegable read and a delegable write name the same symbol and mean opposite
things. The call matcher resolves aliased and namespace-qualified calls
back to the original name, and proves it can against synthetic modules.

Two assertions carry the decision not to add a provenance column to eleven
tables. Every module in the write list has to call auditLog, which is the
only writer that stamps the acting account, and none of them may reach the
audit table through the client instead. That decision rested on the trail
existing; it now rests on a test.

The prose on the read list said the write arms keep refusing under a
switch. Eleven of them no longer do, so those sentences are rewritten
rather than left to lie.

The integration suite drives the shipped POST exports through the real
handler, resolver, grant table and Prisma. Five legs per verb: the write
lands under the owner and nowhere else, a read grant is refused with
nothing written, a caller who was never granted is refused the same way,
the request after a revocation is refused with no re-login, and a caller
who never switched is indistinguishable from before. The grant is minted
through the invitation flow rather than planted, and the audit assertion
reads both ends of the row.
2026-08-03 12:11:28 +02:00
Marc-André Bombeck 3e7127dca5 Ask what the record on screen allows before rendering a control
Account sharing shipped read-only, and everything that consulted the grant
lived in the application chrome: the nav bars, the banner, the switcher. No
feature surface asked. A delegate opened somebody else's record, saw the add
button on every page, filled the form, and was refused by a server that was
right to refuse. Nothing leaked; it taught people the product was broken.

This is the answer every mutation affordance asks for. Two booleans, because
a grant at WRITE admits a short closed list of verbs and nothing else:
`canAdd` for an entry of an admitted kind, `canManage` for changing what is
already there or adding what the list does not name. `canWrite` arrives
resolved from the server and is bound, never recomputed; what this decides is
only which class of control a resolved level covers.

The absent case is the permissive one. Failing closed would blank every add
button in the app for every account on every cold load, to spare a delegate
one frame between the reload and the account query landing.
2026-08-03 12:11:18 +02:00
Marc-André Bombeck 9ac7d5af7c Let a delegate add a medication, record a side effect and mark a dose
Four medication verbs resolve the record: adding a medication with its
nested schedule, recording a side effect, and both forms of marking a dose.
Editing and deleting a medication stay refused under a switch, which is the
sharpest asymmetry in the feature — a delegate can create a medication and
can never correct the typo in its dose afterwards.

The side-effect rate bucket keys on the acting account rather than the
record. That was the condition on which the verb was admitted: on the
record key a delegate could exhaust the owner's allowance and lock them out
of their own log, and could collect a fresh one by switching to another
record. Everyone who has not switched lands in the bucket they always did.

Both intake routes tell the owner who marked their dose. Everything else
downstream stays addressed to the owner and is correct there: the
cross-device sync wakes their devices, the web-push clear closes their
pending reminder and recounts their badge, the compliance rollup recomputes
their day.

Two validation breadcrumbs move to auditLog(), the only writer that stamps
the acting account.
2026-08-03 12:11:10 +02:00
Marc-André Bombeck 095aba095e Let a delegate add to the clinical record of a shared account
An allergy, a family-history entry, an illness episode and a custom-metric
value now resolve the record rather than the caller.

Two of them carry a consequence worth naming. The family-history row
describes the record's relatives, so it is the one admitted write where
third-party health information is present by design; it is stored as the
record's own, exactly as the read arm already serves it. The illness module
gate runs against the record before the write, so a delegate cannot open an
episode inside a record whose owner switched the module off, whatever they
set on their own account.

The custom-metric entry reaches its metric through the ownership hop, which
now resolves against the record: a delegate can only feed a definition the
owner made, and their own metric of the same name is unreachable from in
there. Its validation breadcrumb moves to auditLog().
2026-08-03 12:10:59 +02:00
Marc-André Bombeck c6be0778dc Let a delegate enter a lab result and the marker it needs
POST /api/labs and POST /api/biomarkers resolve the record. The free-text
lab path mints its biomarker under the record's catalogue rather than the
caller's — a result added to somebody's record whose marker landed on the
helper's account would leave the owner with a reading they cannot chart.

Adding a marker the record already tracks stays the ordinary 409 from the
same per-account uniqueness the owner would hit themselves. The PUT and
DELETE on the sibling routes are unchanged and still refuse under a switch.

Both validation breadcrumbs move to auditLog(), the only writer that stamps
the acting account.
2026-08-03 12:10:49 +02:00
Marc-André Bombeck 17c4e76165 Let a delegate enter a reading into a shared record
Both POST arms of /api/measurements resolve the record rather than the
caller. Every `userId: user.id` in the handler already meant "the record",
so the bodies are untouched: the safety-floor check, the reminder
satisfaction, the rollup recompute and the cache eviction are statements
about the record and stay addressed to it.

The two validation breadcrumbs move from a bare client create to
auditLog(). That helper is the only writer that stamps the acting account,
and a delegate's malformed payload filed without it reads as the owner's
own typing.
2026-08-03 12:10:37 +02:00
Marc-André Bombeck 9e3cd7c430 Merge pull request #706 from MBombeck/work/dw-c
Tell the owner when somebody else marks a dose
2026-08-03 11:22:17 +02:00
Marc-André Bombeck d72451d59b Merge pull request #705 from MBombeck/work/dw-b
Offer read or read-and-add when you invite somebody
2026-08-03 11:21:26 +02:00
Marc-André Bombeck 53ef27e63d Merge pull request #707 from MBombeck/work/dw-a
Scope the idempotency replay cell to the record a request claims
2026-08-03 11:21:17 +02:00
Marc-André Bombeck c98a478003 Merge remote-tracking branch 'origin/main' into work/dw-a 2026-08-03 10:54:01 +02:00
Marc-André Bombeck f751510675 Merge remote-tracking branch 'origin/main' into work/dw-c 2026-08-03 10:39:47 +02:00
Marc-André Bombeck aadf751355 Merge remote-tracking branch 'origin/main' into work/dw-b 2026-08-03 10:39:45 +02:00
Marc-André Bombeck 4f8fa25b51 Anchor the sync fixtures on a relative clock
The sync-changes fixtures seeded rows at a literal calendar date. The route
serves only what sits inside the tombstone retention horizon, which is sixty
days plus a fifteen-day margin, so the fixture was inside the window when it
was written and fell out of it exactly seventy-five days later. Three cursor
round-trips started failing at midnight with no commit behind them, and would
have failed on every run from then on.

The rows now anchor five days before the current time, so they cannot age out
of the window they are meant to be inside. The mood entry's own date string is
derived from the same anchor rather than written out, because the two drifting
apart is the same defect one level down.
2026-08-03 10:34:48 +02:00
Marc-André Bombeck fe142bbd3a Correct the entry type's account of what a level is
The payload type still said the level is read throughout and `canWrite` false.
Both were true of the shipped release and neither survives the invitation
gaining a choice. Also says what `canWrite` does not mean, since the word
invites a larger reading than the thing it grants.
2026-08-03 10:20:26 +02:00
Marc-André Bombeck c7960d726d Scope the idempotency replay cell to the record a request claims
A delegate retrying with one `Idempotency-Key` across two people's records met
itself in one cell. The cache tuple was `(caller, key, method, path)`, so the
second record's request replayed the first record's cached 201: the handler
never ran, no row was written for the second person, and the caller was told it
had been — with the other person's id in the body. Nothing errored and nothing
logged a conflict, and five of the write verbs about to become delegable are
wrapped here.

Fold the claimed record into the `key` component, centrally, once. Not into
`userId`: that column is a foreign key to `users` with a cascade behind it and
cannot hold a composite. It keeps naming the caller, which is what makes two
delegates on one record two cells for free. The separator is a byte the key
validator refuses, so a caller cannot hand-craft a key into a cell belonging to
a request they are not making.

A request with no acting account keys byte-for-byte as it did before, so a
client that never heard of sharing cannot be affected.

Accepted and pinned by test: the fold uses the CLAIM, before the grant check,
so within the 24h window a delegate whose access has ended can still replay a
key they had already completed. They receive bytes they already had, nothing
new is written, and a fresh key from them is refused because that request
reaches the handler.

Both frozen surfaces move in this diff. The claim reader gains a guard leg
freezing its consumers, since an unchecked claim is exactly the value a future
caller must not mistake for permission.
2026-08-03 10:18:27 +02:00
Marc-André Bombeck ca3a654e47 Say what a grant is now that it can carry two levels
The module header still described a permission to read, and the grantee field
still said "invited to read it". Both are half the sentence once the level is
a choice.
2026-08-03 10:14:06 +02:00
Marc-André Bombeck f24ae6deb8 Read the acting-account carrier from one place
The rule that decides what a request says it is acting as — session stamp on
the cookie transport, selector header on Bearer, a header on a cookie request
naming nothing — sat inside the resolver that acts on the answer. A second
caller needs the same question answered before any auth context exists, and
two implementations of "whose record is this" drift; the copy that drifts is
the one nobody reads.

Move the decision, the header name and the two predicates into
`auth/acting-carrier`, as a pure function of what the transport carried. The
resolver keeps what only it may do: turning a claim into a data scope once a
live grant says so. No behaviour changes — the resolver's arms are the same
arms, and its suite passes untouched.

The header-name guard follows the constant to its new file.
2026-08-03 10:13:55 +02:00
Marc-André Bombeck d82e29737b Say what the level means on both screens that decide it
The invitation form gains the choice, and the option labels say what actually
ships rather than the word "write": a delegate can add readings, results,
observations, a medication and a marked dose, and can edit or delete nothing,
including what they entered a moment ago. That gap between what "write access"
sounds like and what it does is where a support case lives, so it is on the
card rather than in a reply.

The delegate reads the same thing before they accept. A pending write
invitation states its level and one sentence about what accepting means, on the
screen where they accept it, because acceptance is where the two consents meet
and it happens once.

Ending an access says what stays: the entries remain and the owner can remove
any of them, and the activity view keeps saying who entered what for as long as
the instance's audit window reaches. That number comes from the server, so an
instance running ninety days says ninety, and a browser that has not been told
says nothing rather than a made-up year.

The browser journey now invites at the wider level and reads the posted body
for it. That is the only check in the tree that can: the component convention
is server-rendered only, so no test under src/ runs the form's submit path, and
every one of them stays green with the control wired to a constant.
2026-08-03 10:12:22 +02:00
Marc-André Bombeck 533400ce60 Let an invitation carry the level it offers
A grant has always had an access column and `inviteGrant` has always written
READ into it. That was the right way to ship the first version: "this release
never grants write" was a property of the file rather than a promise in a
comment. Remove it deliberately now, so somebody sharing their record can offer
reading or reading plus adding.

The level is a required argument to `inviteGrant` and is defaulted in exactly
one place, the invite schema, where an omitted field becomes READ. An older
client's payload therefore stays valid and stays narrow, and the domain module
never guesses a level nobody named.

There is no upgrade path and that is the decision, not a gap. A grant is READ
or WRITE from the moment it is offered and stays that way until somebody ends
it. Widening a live one would change what the delegate agreed to without asking
them again, and their consent is half of what makes a write grant legitimate.
The way up is a new invitation, accepted again.

The audit row and the wide event carry the level: "who was given what, and by
whom" is the question that row exists to answer.
2026-08-03 10:12:08 +02:00
Marc-André Bombeck bf7fba4af0 Route the delegated-dose alert through one helper that refuses on self
The intake routes call notifyDelegatedIntake with both account ids and
the helper decides. Keeping the comparison here rather than at the call
sites means a route added later cannot notify somebody about a dose they
marked themselves, and a snooze is answered in one place as what it is:
moving a dose, not resolving one.

The medication name is read scoped to the owner, because that name goes
onto the owner's lock screen. Nothing addresses the delegate: the
dispatcher takes a single account id, and under record substitution that
id is the owner. The person who marked the dose learns what they did
from the response they are already awaiting.

The integration test asserts the ledger row before the sender mock, so a
dispatch nobody recorded cannot pass as a dispatch.
2026-08-03 09:52:02 +02:00
Marc-André Bombeck 696b4d7d1c Give every notification event type words to render
The matrix derives each row's label from the event name, so a new event
type gets a row whether or not anybody wrote the strings for it. That is
how SECURITY_ALERT has been rendering its own raw key since v1.23: the
forward i18n coverage test only sees literal call sites, and this key is
assembled from a runtime value.

Move the derivation out of the page so a test can compute the keys the
page computes, assert both resolve in all six bundles, and name the
missing one. Write the sign-in row's strings, and the strings for the
delegated-dose row and its push body.
2026-08-03 09:51:53 +02:00
Marc-André Bombeck 427e25d1ae Add a notification for a dose somebody else marked
The owner of a shared record gets an alert when a delegate marks one of
their doses. It is the one exception to the rule that bookkeeping stays
in the activity view: whether the tablets were taken is a fact about the
owner's own body, and they should not have to go looking for it.

Default ON, against the opt-in precedent of PERSONAL_RECORD, because the
event only exists once the owner has invited somebody and given them
write access. The per-channel row in the matrix is the valve for anyone
who finds it noisy, and both positions of that preference are covered.
2026-08-03 09:51:42 +02:00
Marc-André Bombeck 1efd337f53 Merge pull request #704 from MBombeck/fix/grant-invite-expiry
Let somebody actually set the date a shared access lapses on
2026-08-02 21:21:24 +02:00
Marc-André Bombeck cb8e886ffc Retire the registry entry the hardcoded null needed
The destructive-control registry carried this card because a detector read
its hardcoded `expiresAt: null` as a field being blanked, and an entry
explained at length why blanking was harmless here. The explanation was
right and the cause was not: the null was there because nobody could set a
date, not because none was wanted.

With the control wired the detector no longer fires, so the entry no longer
matches anything and the registry's own staleness check asked for it back.
2026-08-02 21:03:29 +02:00
Marc-André Bombeck 6780e54036 Let somebody actually set the date a shared access lapses on
The invite route has accepted expiresAt, stored it and annotated on it since
the grant model shipped. The card sent a hardcoded null, so the column existed,
the validator accepted it, the wide event reported on it, and no person could
set one. The release note said an invitation could carry a lapse date.

The form now offers the date, floored at tomorrow because a grant that lapses
today confers nothing. A chosen day maps to the END of that day in the
browser's own zone, so "until the 30th" means the 30th rather than the
midnight that starts it, which is the reading anybody picking a date has in
mind. Empty stays the default and still means no lapse date.

Both ends are pinned rather than one: the control is asserted in the rendered
form, and the mapping is exported so its contract holds without a click, which
is this repository's convention for component tests.
2026-08-02 20:56:31 +02:00
Marc-André Bombeck 8a5293bc1a Merge pull request #703 from MBombeck/release/v1.36.0
chore(release): v1.36.0
2026-08-02 20:46:44 +02:00
Marc-André Bombeck 314bf26638 chore(release): v1.36.0 — one record, two people, and a line that says which 2026-08-02 20:28:53 +02:00
Marc-André Bombeck 5ff949ea70 Merge pull request #702 from MBombeck/work/backup-plan-reader
Prove a backed-up model travels, instead of proving a name exists
2026-08-02 20:22:24 +02:00
Marc-André Bombeck 824545c693 Merge pull request #699 from MBombeck/work/sharing-routes
Open the classified read routes to a delegate
2026-08-02 20:22:16 +02:00
Marc-André Bombeck d1a9147034 Merge remote-tracking branch 'origin/main' into work/sharing-routes 2026-08-02 20:02:50 +02:00
Marc-André Bombeck f1fd68aa55 Merge pull request #701 from MBombeck/fix/a11y-scan-sentinels
Wait for content the page owns before scanning it
2026-08-02 20:02:35 +02:00
Marc-André Bombeck 33fc238305 Scan the dashboard once its charts are in the accessibility tree
An unrevealed chart cell is `invisible` and `aria-hidden`, so the chart row
is not in the accessibility tree at all until the reveal gate fires. Waiting
on the tile strip left it to chance whether the row was read: locally the
cells were still hidden when the strip appeared and revealed six seconds
later, while the runner that reported the broken heading order had already
revealed them. The row is the largest surface on the page, so a scan that
sometimes skips it is not a check of the page.

Gating on a revealed cell makes the coverage the same on every run. With the
heading level put back to its old value the case now fails 16 out of 16
repeats across both themes and both viewports, where the same defect
previously surfaced twice in several full runs.
2026-08-02 19:45:05 +02:00
Marc-André Bombeck ef9d66b7f9 Title the chart card at the level it actually sits on
A dashboard chart card called itself an h3. Nothing contained it. The cards
beside it in the same grid — "Recent unlocks", "Recent workouts" — are h2,
and so are the target and usual-range cards on the metric subpages, so the
chart card was both the odd one out and a level skipped straight from the
page h1. The rendered dashboard ladder was h1 → h3 → h3 → h3 → h2 → h2, and
/insights/bmi was h1 → h3 → h2.

A heading level is a claim about nesting. Someone moving through the page by
headings hears a subsection announced where there is no section, and screen
reader rotors build their outline from exactly this. Promoting the title
keeps the same text, the same classes and the same pixels; only the claim
changes.

The unit guard fails in the fast run; the browser scan catches the same
regression through axe, but only in the e2e job.
2026-08-02 19:44:45 +02:00
Marc-André Bombeck 06d44fd8b1 Stop one model's relation write answering for another's
A child model rides its parent through the backup, so the check looks
for the relation field name as well as the delegate. It looked for the
bare name anywhere in the declared files, and `symptomLinks` is declared
twice — on `IllnessDayLog` for the illness link, on `CycleDayLog` for
the cycle one. Deleting the illness branch from the restore route left
all twelve checks green, because the cycle write in another file was
answering a question about a different table.

A name that points at exactly one model is still evidence anywhere. A
name shared by several counts only in a file that also operates on the
declaring parent's delegate, and a check asserts the cycle file proves
the cycle link and refuses to prove the illness one.

That leaves the illness link unprovable from source: its include is a
shared constant with no query beside it, and the parent that would
disambiguate it is reached through the episode in another file.
`STRUCTURALLY_UNATTRIBUTABLE` names it with what defeats the matcher,
and naming a model there is not a free pass — it has to be seeded in
the round trip, which is checked here.
2026-08-02 19:34:59 +02:00
Marc-André Bombeck cb9867e379 Prove a backed-up model travels by making it travel
The plan says which models a backup carries and a source-text check says
each one has a reader and a restore branch written for it. Neither can
tell a restore branch that runs from one that only exists: wrap the
nutrient restore in `if (false && …)` and every check stays green, which
is the correct-green-and-inert shape this project already shipped once.

So settle it end to end. Seed one row of every two-ended model, export
through the real payload builder, delete the account so the cascade
empties what a hand-listed sweep would miss, restore through the real
admin route, and count each row back out. A model that never travels
comes back at zero and says which one it was.

The two-ended list is a literal tuple now, so the seed registry can be
keyed by it: adding a name without seeding and counting a row for it is
a compile error rather than an unproven claim.

Also names `src/lib/illness/dto.ts` as a backup writer. The illness
day-log's symptom include is a shared constant living there, not a
literal in the records writer — the same "the caller delegates" shape
that already caught the measurement pager.
2026-08-02 19:34:47 +02:00
Marc-André Bombeck 002a82106a Merge remote-tracking branch 'origin/main' into fix/a11y-scan-sentinels 2026-08-02 18:50:47 +02:00
Marc-André Bombeck 47e50ece39 Wait for content the page owns before scanning it
Several accessibility scans ran against a page that had not finished
arriving, so axe reported violations the app does not have. The worst of
them was the medications case, which waited for a level-one heading and
then checked that a level-one heading exists. A page that really lost its
heading would have waited out the timeout under a misleading name instead
of failing the rule, which makes it a check that cannot fail rather than a
flaky one.

The filter rail was the other bad sentinel. It renders beside the loading
silhouettes rather than after them, so it was on screen while the rows were
still grey rectangles. Under an 8x CPU throttle the rail and the loading
marker resolved in the same 40ms poll and the rows a poll later.

Every case now gates on a marker the real component carries in its
resolved, non-empty branch, and on a component other than the one the scan
asserts. Both the desktop table and the mobile card list carry the same
marker so the wait holds at any viewport. No sentinel names a heading, the
app frame, a busy marker or the filter rail any more.
2026-08-02 18:50:31 +02:00
Marc-André Bombeck c53c0036ea Merge pull request #700 from MBombeck/fix/header-seam-banners
Keep the header seam continuous when a banner is showing
2026-08-02 18:35:00 +02:00
Marc-André Bombeck e449a19e55 docs(sharing): say how the cycle gate actually resolves the record
The two cycle entries in the frozen list claimed the gate reads `gender` off
the resolved auth context. It does not: `requireCycleEnabled` names that
parameter `_gender` and ignores it, then re-loads gender and the profile by
the resolved user id through the module gate. The answer is the same — the
owner's — but a reviewer checking the claim would have found a dead argument
and no explanation.

The profile route is the exception and now says so: it passes the auth-context
gender to `isCycleEnabled` itself to compute the flag it returns.

A frozen-list entry is only worth the reviewing it invites, so it has to
describe the mechanism that is there rather than the one the call site looks
like it has.
2026-08-02 18:17:05 +02:00
Marc-André Bombeck 49ffba77f3 Merge remote-tracking branch 'origin/main' into work/sharing-routes
# Conflicts:
#	src/__tests__/delegable-surface-guard.test.ts
2026-08-02 18:07:11 +02:00
Marc-André Bombeck 81529a3910 Give the shared-record banner the inline-action row shape
The strip is new this release and had not been checked against the
design standards. It carried the shape §11 names as the anti-pattern: a
centred flex-wrap row whose gap-y drops the action onto its own line
once the name is long enough. The maintainership strip is the sibling
that already had an action and already had the right shape, so the two
now read the same — sentence on min-w-0 flex-1, way out on shrink-0,
beside it rather than under it.

The exit control was a 32px tap target. Leaving somebody else's record
on a phone is the one interaction in the whole banner stack, and it now
carries the standard's floor (min-h-11 sm:min-h-9).

The three strips also spell their icon size three ways for identical
CSS; they all use size-3.5 now.

Text tiers are unchanged and were already right: the person's name is
foreground because it is content, the read-only qualifier is muted
because it is meta.
2026-08-02 18:04:26 +02:00
Marc-André Bombeck c12a6873b3 Hoist the shell banner stack above the sidebar and content row
The offline, shared-record, demo and maintainership strips lived inside
the content column, so each one pushed the top bar down while the
sidebar's logo band stayed at the top of the window. Both bands read
SHELL_HEADER_BAND and are therefore the same height with the same
border, and the single line they draw across the top of the app still
came apart: measured on the French maintainership strip, the two borders
sat 66.5px apart at 768px and 61.0px apart at 1280px, and the full
three-banner stack put them 184.5px apart. After the hoist the step is
0.00px at every depth and both widths.

A banner is a statement about the whole window, not about the content
column, so it belongs above the row. The outer wrapper keeps the h-dvh
and the row below takes what the banners leave, which means the stack
comes out of the viewport budget instead of being added on top of it:
the document still does not scroll at any depth, and <main> stays the
one vertical scroller at both breakpoints.

The existing seam guard could not see this class. It asserts that both
bands carry the shared band tokens, which stayed true the whole time,
and the e2e spec beside it measures a shell with nothing above the
header. The new spec forces the banners on through the conditions the
components actually read — an unmaintained locale, a patched account
payload, a real offline context — and measures the same two borders at
four stack depths. Reverting the layout change turns it red on the first
banner with the measured offset in the message, while the older seam
spec stays green.

The maintainership strip gains a data-slot so the shell's chrome can be
enumerated from one attribute.
2026-08-02 18:04:07 +02:00
Marc-André Bombeck 81e5c7464b test(sharing): point the refusal arm at a route that can never be delegable
`GET /api/measurements` was the resolver test's example of a route refusing
under a switch. It is delegable now, so that arm was asserting the opposite
of what ships and went red on the migration — which is the arm doing its job,
not a defect in it.

Split in two. The measurements route keeps both of its real claims: unchanged
un-switched, and the owner's rows and not the delegate's once switched. The
refusal moves to `GET /api/share-links`, which is non-delegable permanently
and by design — a delegate who could mint a clinician link would hold a door
that survives the owner revoking their access. A route that can never join
the frozen list cannot break this arm the same way twice.
2026-08-02 17:36:44 +02:00
Marc-André Bombeck 210380f46d Merge pull request #690 from MBombeck/work/sharing-client
Account sharing, the part people touch
2026-08-02 17:13:30 +02:00
Marc-André Bombeck 7a39a649be feat(sharing): open the medication reads to a delegate
Ten routes: the cabinet list, the medication detail, its cadence, schedule
revisions, side effects, inventory, phase config and intake history, plus the
account-wide intake list and the batched compliance read.

`GET /api/medications/compliance` is the one delegable read that spends a
quota, and its rate-limit bucket now keys on the ACTOR while everything below
it scopes to the record. Both halves matter: a delegate hammering the route
must burn their own allowance rather than lock the owner out of their own
cabinet, and switching records must not hand the same caller a fresh one. The
test reads the `rate_limits` row rather than inferring it from a 429, because
a bucket keyed on the wrong person still answers 200.

`GET /api/medications/[id]/api-endpoint` stays refused. It returns two scalar
fields and no secret, and it tells a delegate whether the owner holds a live
ingest credential and for which medication — in the same file as the PUT that
mints one that would survive revocation.

The two intake validation breadcrumbs move onto `auditLog()` for the actor
stamp. The POST arm's breadcrumb stays as it is: that arm cannot be reached
under a switch.
2026-08-02 17:06:23 +02:00
Marc-André Bombeck 526041770d Merge pull request #691 from MBombeck/fix/gate-blind-spots
Let the structural guards see the directories they were skipping
2026-08-02 17:05:49 +02:00
Marc-André Bombeck fe765a7ae2 feat(sharing): open the cycle reads to a delegate
Four routes: the cycle history, the day log, the profile and the custom
symptom vocabulary.

All four gate on `requireCycleEnabled(user.id, user.gender)`, and both
arguments now come off the record. That is the correct reading and the one
that had to be verified rather than assumed: whether cycle tracking applies
is a property of the record, so a delegate who tracks nothing still sees the
owner's cycle, and a delegate who tracks their own sees nothing when the
owner does not. Both directions are asserted.
2026-08-02 16:57:07 +02:00
Marc-André Bombeck 10f9a83356 feat(sharing): open the sleep, nutrient, illness and workout reads
Eight routes: the two sleep reads, the nutrient overview and its daily
series, the illness episode list, detail and day logs, and the workout list.

The illness day-log read is the one worth reading twice. Its queries are
episode-scoped rather than user-scoped, and what makes them safe is the
`loadOwnedEpisode(id, user.id)` hop above them. That hop now resolves against
the record, so a delegate cannot reach their own episode from inside somebody
else's account — asserted, because it is the kind of thing that would look
fine and behave wrong.

`GET /api/workouts/[id]` stays refused. It differs from the list beside it by
one conditional include that decrypts a paragraph written about the owner.
2026-08-02 16:52:59 +02:00
Marc-André Bombeck 20f5ae27a0 test(e2e): give the account-switching journey its own session
The switch is stamped on the session row, not held in the tab. Every
authenticated spec opens its context from the same storageState file, so
the sharing journey switching that jar into the owner's record switched
it for whatever spec happened to be mid-navigation on the other worker.

The failures land nowhere near the cause: /settings/ai painting "Not
part of shared access" instead of the AI panel, an axe scan reading a
banner its spec never asked for, a waitForResponse waiting on a request
the refused surface never sends. Which spec loses depends on scheduling,
which is why it moved between runs.

Log the delegate in a second time and hand that jar to the journey. Same
account, its own session row, no reach outside the file. The three login
captures collapse into one helper while the third one is added, and the
fixture's login-bucket reset already covers the extra attempt.

The guard matches the two things a switching spec cannot avoid naming,
the switcher entry it clicks and the endpoint that entry calls, and
checks both that the match set is non-empty and that the shared jar is
still what the ordinary specs read. Verified red by pointing the journey
back at the shared jar.
2026-08-02 16:49:47 +02:00
Marc-André Bombeck 89532ee48e docs(about): state the GeoLite2 licence in full
The credits page named CC BY-SA 4.0 alone. MaxMind stopped distributing
GeoLite2 under that licence by itself: the databases ship under the
GeoLite End User License Agreement, which incorporates CC BY-SA 4.0 by
reference and controls wherever the two disagree. Name both, in that
order, and link the EULA. The attribution string was already there and
is unchanged; the e2e page check now asserts both licences rather than
the one that no longer stands alone.

Reconcile the self-hosting guide with the same wording, point it at the
current EULA URL, and say why the `/about` page must stay reachable — it
is where an operator's own attribution lives.

Correct the project licence line while on the page: it still claimed
AGPL-3.0, which the page's own footer contradicts. The trunk has been
PolyForm Noncommercial 1.0.0 since v1.15.19.
2026-08-02 16:45:51 +02:00
Marc-André Bombeck 8c070c953b feat(sharing): open the mood, custom-metric and record reads to a delegate
Six routes: the mood-entry list and detail, the custom-metric list, detail
and entries, and the personal-record list. The custom-metric entries read
establishes ownership on the metric before it queries by metric id, and that
hop now resolves against the record — a delegate cannot reach their own
metric from inside somebody else's account.

`GET /api/mood/tags` stays refused. It looks like plain record vocabulary and
one select in the middle of it pulls the owner's tag layout, which is a
presentation preference and belongs to the person rather than the record.

The mood list's validation breadcrumb moves onto `auditLog()` for the actor
stamp, the same change the measurement reads took.
2026-08-02 16:44:52 +02:00
Marc-André Bombeck c82ff767a3 Say in the runbook what a backup does not carry
Every credential-shaped row is left out on purpose — API tokens, trusted
devices, step-up elevations, known devices, clinician share links, and the
grants behind shared record access. The per-model reasoning already lives in
backup-plan.ts with a structural test behind it, but an operator planning a
recovery does not read that file.

The consequence differs by target and the difference is the part worth knowing.
Restoring onto the same instance changes nothing: the restore replaces data
tables and does not touch grants, so shared access carries on as it was.
Restoring onto a fresh instance brings none of it, so both people invite and
accept again before sharing works. That is the fail-safe direction, and it is
better planned for than discovered.
2026-08-02 16:39:35 +02:00
Marc-André Bombeck 5575d4ca2e build(knip): say what the dead-code gate proves and what it cannot
Vitest is a knip plugin, so every file under `src/**/__tests__/**` is an
entry, and a module whose only importer is its own test counts as used
for as long as the test survives. Planting a module with a single test
importing it left `pnpm knip` at exit 0 — the gate reports green on code
production stopped reaching.

Knip can answer the question, just not in the pass CI runs: production
mode drops the plugin's test entries and keeps the entry and project
patterns suffixed with `!`. Mark them, which is inert in the default
pass, so `pnpm knip --production --include files` is one command away.

It stays a review tool rather than a second gate, and the config says
why: twenty-nine files today, some test-only by construction and some
unreachable from production on purpose, plus at least one false positive
where a script's `@/` import does not resolve. Baselining that set
unread would encode noise as an invariant.

Move the config to JSONC so all of the above lives next to the settings
it describes instead of in a commit message nobody will run `git log`
for.
2026-08-02 16:39:16 +02:00
Marc-André Bombeck af0f749740 feat(sharing): open the lab and clinical-record reads to a delegate
Ten routes: lab results and their detail, the biomarker catalogue and its
detail, allergies, family history, the mental-health screener history, and
the health-profile facts. All GET arms; every write arm in the same files
keeps `requireAuth()` and refuses under a switch.

The family-history payload is the one admitted read that carries third-party
health information by design — it describes the owner's relatives — and it is
admitted because a caregiver reading a family history is what the feature is
for and the rows are the owner's own.

The mental-health module gate resolves against the record, not the caller.
That is the recorded decision: the module map says which parts of a record
exist, so a delegate who enabled the screener on their own account gains no
screener view inside somebody else's. The integration test asserts both
directions.
2026-08-02 16:38:39 +02:00
Marc-André Bombeck a640e84142 Exclude the worktrees the tooling was already meant to exclude
git, eslint and vitest each carry an exclusion for local development
worktrees, and all three name /.worktrees/ while the convention actually in
use is /.wt-*/. Every one of them was therefore walking eleven full copies of
the source tree.

The consequences differed by tool and none of them announced itself. pnpm lint
took ten minutes instead of one and reported warnings from whatever commits
those copies happened to sit on. vitest collected duplicate suites that drag in
a second React instance, which fails in ways that have nothing to do with the
working tree. git left them merely untracked, one git add -A away from
committing the repository eleven times over.

With the true warning count finally visible, teach no-unused-vars the
underscore convention this codebase already follows and drop the five
disable directives that convention made redundant. pnpm lint is clean.

A non-underscore unused argument still warns; that was checked rather than
assumed.
2026-08-02 16:36:25 +02:00
Marc-André Bombeck a463b1fa01 Stop recording the address a delegate accepts a grant from
A consent record has to answer who consented and when, and the grant row
already does. It does not have to answer from where, and an address kept for
as long as both accounts exist is personal data held past the point it
evidences anything. Nothing read the column, which makes it exactly the
write-only field scripts/audit-column-readers.ts exists to surface.

The acceptance stays evidenced: audit_logs records it with the caller's
address under that table's own retention. The column never reached the wire,
so the grant view and the OpenAPI contract are unchanged.

Written before the feature shipped, so migration 0295 drops an empty column.
2026-08-02 16:36:12 +02:00
Marc-André Bombeck 255cbf5fe0 feat(sharing): open the measurement reads to a delegate
Six routes move from `requireAuth()` to `requireRecordAuth("read")`: the
measurement list, the single reading, the two series reads, and the two
reminder reads. Each is admitted in the delegable classification with its
five answers written; each enters the frozen list with the argument for why
a delegate reading through it cannot extend their own reach.

Only the GET arms move. The POST, PUT and DELETE arms in the same files keep
`requireAuth()`, which refuses outright while a switch is active, so a file
entering the list admits a read and nothing else.

The two validation breadcrumbs on the list and series reads now write through
`auditLog()` rather than a bare `prisma.auditLog.create`. That helper is the
only writer that stamps `actorUserId`, and without the stamp a delegate's
malformed query lands on the owner's record looking like the owner's own.

Integration coverage drives the shipped GET exports against real Postgres:
the owner's rows reach a delegate holding a live grant, the delegate's own
rows do not, a caller without a grant is refused `sharing.access.denied`, the
request after a revocation is refused with no re-login, and a caller who
never switched sees exactly what they saw before.
2026-08-02 16:30:46 +02:00
Marc-André Bombeck 1ae137eb84 test(guards): sweep the directories the structural guards were skipping
`fs.globSync` never matches a leading dot, so every guard built on
`**/*.{ts,tsx}` walked past `src/app/.well-known` — the two OAuth
discovery documents and the apple-app-site-association handler sat
outside fourteen frozen-set sweeps. An unlisted `getSession()` planted
in the authorization-server route left the session-surface guard at nine
passed; it fails now.

Move those fourteen onto one shared walker built on `readdirSync` with
`recursive`, which has no dot rule, and give it a floor every caller has
to state, so a walk that comes back too small throws instead of
reporting a clean tree.

Give the same floor to the guards that compared a discovered set against
a frozen list with nothing asserting the set had been read: gutting the
walker in the inventory-write guard left its invariant test green,
because zero offenders reads exactly like no offenders. Raise the
migration-count floor off one, and assert the locale bundles are found
before the per-locale cases are generated from them.

Document, at each walker that prunes on purpose, what is pruned and that
dot-prefixed directories are not.
2026-08-02 16:21:19 +02:00
Marc-André Bombeck f9ad2d3986 Format the account-access round trip 2026-08-02 15:43:49 +02:00
Marc-André Bombeck b2e439ee03 Merge main 2026-08-02 15:42:30 +02:00
Marc-André Bombeck f574e63368 docs: what sharing a health record does, and what it cannot undo
An operator page for the feature, written in the register the
reproductive-health page established: say the narrow true thing rather
than the reassuring one.

What the person given access can reach, and the table of what they cannot
— credentials, sessions, tokens, connected services, notification
channels, exports, share links, the sharing itself, and the AI surfaces.
The AI row gets its own paragraph because it is the one that looks
arbitrary: server-managed processing runs under the consent the record's
owner gave for their own use.

Revocation is described honestly. It lands on the next request rather
than the next login, it puts a browser that was inside the record back
into its own account, and it cannot take back what was already seen. The
product can close the door; it cannot reach through it, and the page says
so rather than implying otherwise.

The activity view's window is described as the operator's setting, not as
365 — an instance that shortens the audit retention shortens this view,
and an empty list means nothing was recorded within the window rather
than that nothing ever happened.

The three trust facts stay where they were: the operator could always
read the database, encryption at rest is instance-keyed rather than
per-user, and AI processing stays under the owner's own consent.

The data-protection note is deliberately absent — its stance is a
maintainer decision, and the page reads complete without it.
2026-08-02 15:17:31 +02:00
Marc-André Bombeck cacf802b8d test(e2e): the sharing journey, and an honest account of the stale paint
Two browser contexts, two seeded accounts, one database: the owner invites,
the delegate accepts and opens the record, the owner takes it back. Every step
through the shipped UI, because the half of this feature that can go wrong is
the half a person touches.

The stale-paint check is a negative one and deliberately not "the new record's
data arrives" — a check that waits for the new data says nothing about what
was on screen while it arrived. An init script arms a MutationObserver before
any page script on every navigation, including the reload the switch performs,
and latches the delegate's own marker weight. The observer's positive control
runs first on a page that definitely shows it, so its later silence is not the
silence of a broken observer.

Then it was broken on purpose, and the result is written into the spec rather
than assumed. Removing the switch-time cache wipe, the persister's restore
guard and the record-scoped hash — all three — leaves the spec GREEN: the
restore already refuses to clobber a query the live cache holds, and the
dashboard's query is created during render, so the snapshot never reaches that
route's screen at all. Removing the reload turns it red on the banner rather
than on the marker. So this suite is a regression net over the journey, not a
proof of any one control; the controls are proven where they can be broken and
observed, in the unit suites, and the spec's header says so.

The nav assertion turned up a real gap while it was failing: the avatar block
still linked into the account settings from inside a shared record. Those
routes refuse under a switch, so the link led only to an explanation of why it
did not work. It renders as a plain identity block now, and the mobile user
menu drops the same utilities.

Setup gains a second account, a marker weight in each record, a grant reset,
and a clear of the login bucket — this setup signs in twice now, and the
ceiling is five attempts a quarter-hour, so three local runs used to end with a
429 from the fixture rather than a failure from the product.
2026-08-02 15:14:35 +02:00
Marc-André Bombeck 883fd2d047 docs(api): publish the account-access block and the selector header
Three additions to the contract, all of them things a native client cannot
work out on its own.

`GET /api/auth/me` enters the spec for the first time, and enters it loose:
`accountAccess` is specified in full, the remaining preference fields are
declared open rather than half-enumerated. The endpoint has never been in this
document and its payload carries thirty-odd keys no contract has ever named;
specifying a subset and closing the object would publish something the server
does not keep.

`X-HealthLog-Account` is published as a reusable parameter with no route
referencing it, which is the honest state of the contract — the routes that
read another account's record arrive with the surface migration and will
reference it as they land. The header is live in the resolver today, and a
client needs the description before it can be built against a tagged spec: the
value comes from `accountAccess.accounts`, it is a selector and never a
permission, and it must never ride the sync engine, device registration, or an
auth call.

`GET /api/account/activity` carries `retentionDays` in the response and says
why: the window is operator-configurable, so a client that assumed 365 would
tell somebody their record was never opened when the honest answer is "further
back than this reaches".

The parameter is defined in the sharing route module rather than the shared
components block, so the boundary guard keeps holding the header's name to two
files — the resolver that reads it, and the one place that publishes it.
2026-08-02 14:50:05 +02:00
Marc-André Bombeck 04d30c2570 test(sharing): break every control, then keep the ones that noticed
Each behaviour here was verified by removing the code that provides it and
confirming the test went red, then putting it back. Two of them did not, and
both were rewritten rather than kept:

The restore-side persister check asserted that the delegate's own dashboard
could not be read back inside a shared record. Deleting the guard left it
green, because the record-scoped hash already makes a snapshot written in one
record unreadable in another. It now counts what landed in the cache, so the
guard it names is the thing it measures — and the weaker line is kept beside
it with a note saying why.

The switcher's account rows were asserted from server-rendered markup. Radix
portals do not render server-side at all, so an earlier draft was measuring
the renderer. Those rows moved to the browser suite; what stays here is the
gate, which fails sharply — with the `canSwitch` bail removed the two cases do
not return different markup, they throw.

Two more shapes worth naming. The cache dimension is exercised through a real
QueryClient built from the app's own defaults, because "the hash string
changed" and "one record's data cannot be read while inside another" are
different claims. And the invalidation is a plain function over a client with
three live entries seeded, with a test that asserts they start valid — without
it, a client that failed to seed and one where everything was invalidated look
the same from every other assertion.
2026-08-02 14:39:55 +02:00
Marc-André Bombeck 5199de78af feat(sharing): the shared-access panel and the record-activity view
Settings gains one section for one concept: who else can open this health
record, whose this account may open, and when they were opened. Split across
two pages it would be two half-answers.

An invitation confers nothing until the other person accepts it, and the card
says so above the field rather than after the submit — that is the part
somebody needs to know before they type a name. Refusals are named from the
stable errorCode, because "no account with that name" and "that person already
has access" are different situations with different next steps.

Ended grants stay in the list. The row is the consent record, and "who had
access, from when to when, and who ended it" is the question the panel exists
to answer; a list that dropped them could not. Revoking asks once and then does
it: reducing access must never be harder than granting it was.

`GET /api/account/activity` answers the owner's other question. One row per
person per day with a count, not one per request — a hundred identical lines
is a way of answering nothing. The window is published with the rows rather
than assumed: audit history is purged on a schedule the operator sets, so the
view prints the number the server resolved from the same setting the purge job
reads. An instance running ninety days says ninety.

Six locales ship with it.
2026-08-02 14:26:39 +02:00
Marc-André Bombeck dd3d5646de feat(sharing): the switch, the banner, and the nav inside another record
Switching is three acts in a fixed order, and the order is the safety
argument. Ask the server, so a refused switch leaves the browser where it was.
Empty the caches a reload cannot reach, awaited rather than fired, because a
wipe racing the navigation is a wipe that sometimes does not happen. Then
reload the document, which is what discards the in-memory cache, the rendered
React trees, and every request already in flight against the old record.

The banner is the feature, not decoration. Someone who forgets they are
switched will log their own blood pressure into another person's record, and
there is no undo for a reading that was never theirs. So it states whose
record is open, that it is read-only, and carries the way out — in the one
visual register reserved for "something about this screen is not normal", at
the top of the shell above every other strip. A subtle tint is what people
stop seeing on the third switch.

The switcher lives in one component mounted in both user menus. A way in on
the laptop and no way out on the phone is how the two menus have drifted
before.

Nav entries that sharing does not cover drop out, and a page reached by
bookmark says so instead of painting a row of refusals. Both are paint: the
server refuses those routes on its own, from a frozen list this code cannot
reach. Settings, connected services, notifications and the AI surfaces are the
account around a record rather than the record itself.

A grant can end while a browser is inside the record. Revocation clears the
delegate's sessions in the same transaction; expiry does not, and leaves a
session stamped with an account it may no longer act on — correct refusals
under a screen that lies. One cache subscriber notices the stable errorCode
and leaves, rather than asking two hundred call sites to remember.
2026-08-02 14:26:26 +02:00
Marc-André Bombeck 80175f3bfc feat(sharing): key the query cache by the record it holds
Every cached read in this app is about one health record, and nothing in the
key factory said which one — there was only ever the signed-in account's. Once
a browser can act on somebody else's, `["dashboard","snapshot"]` names two
different answers and the cache cannot tell them apart. That is this repo's
known cache-poison class, on health data, across two people.

One line at the root rather than a dimension threaded through twenty-three key
modules: a `queryKeyHashFn` that folds the record id into the cache identity of
every entry. Key arrays are untouched, which is the part that matters — prefix
invalidation and the import-time dependent-key bundles both match on the array
and keep working. Prefixing the arrays would have broken every bundle silently.

The hash is defence in depth. Switching is a full page reload, so the
in-memory cache is empty on the other side of it; the layers that survive a
reload are the IndexedDB snapshot and the service worker's data cache, and
those are handled by refusing to write either while a switch is on, and by
skipping the restore. Nothing of the owner's record ever reaches the disk of a
delegate's device, so a stale scope marker can cost an empty restore and never
another person's data.

The persister's per-account binding read the account payload's id, which under
a switch is the delegate in both states — it could not tell the two apart. It
now asks the record scope, which can.
2026-08-02 14:26:10 +02:00
Marc-André Bombeck 562123d4d1 feat(sharing): publish which records an account may open
`GET /api/auth/me` grows an `accountAccess` block: the accounts this caller
may act on, the one the browser is inside right now, and the booleans a UI
binds directly — `canSwitch`, and `canWrite` per account. Every value is
resolved server-side. A client that worked out what it may do from grant rows
would be a second program deciding one person's access to a health record, and
the two answer differently the first time an expiry or a revocation appears.

`canWrite` is false for every grant in v1 because invitations write READ only.
It is resolved through the grant state machine rather than hardcoded, so the
day a WRITE grant exists the answer changes without this file being edited.

The route becomes an actor surface. It has to be: the switcher, the banner
naming whose record is open, and the way back out all read this payload, and
under a bare `requireAuth()` the whole app shell would refuse the moment a
switch was on. Every field it returns is still the caller's own.

The active record is published as a full entry, not an id to look up. A banner
that had to join two fields could render unnamed the moment they disagreed;
here the active entry is one of the listed ones, selected by the pass that
built them. A stamp left behind by a grant that lapsed reads as not switched —
the same answer the resolver gives the next delegated request.

Not published: the other account's avatar. Those bytes are owner-scoped, so a
URL here would resolve to a refusal and paint a broken image. Clients keep the
initials fallback.
2026-08-02 14:25:55 +02:00
Marc-André Bombeck 0d4b79d91b Merge pull request #689 from MBombeck/work/sharing-lifecycle
Account sharing, operable end to end
2026-08-02 13:43:05 +02:00
Marc-André Bombeck 6a096a75eb test(sharing): admit the switch endpoint to the actor-surface list
The first entry in either frozen list. It is the way back out of a
switch: every other route refuses while one is active, so a browser that
could not reach this one would be stuck inside a record it entered. The
entry names why it may say what it says — one session row, the caller's
own, nothing of the owner's rendered and nothing granted.

The entry count moves with it, so an addition has to be made twice
rather than once.
2026-08-02 13:05:43 +02:00
Marc-André Bombeck 5067020e99 refactor(sharing): drop a cast the select already proves
The invite lookup selects exactly the columns a grant party carries, so
asserting the shape afterwards said nothing the types did not already
know.
2026-08-02 13:04:25 +02:00
Marc-André Bombeck 56447a9457 feat(sharing): invite, accept, switch, revoke, renounce
The lifecycle surface under /api/account. An owner offers read access to
somebody already on the instance, the delegate accepts, either side ends
it, and a browser session points itself at a record it has been granted.

Ending a grant clears the acting-account carrier on every session of the
delegate pointing at that record, in the same transaction that stamps the
row. Split apart, a revocation would leave a browser inside a record it
can no longer read: every request refused, the banner still naming the
owner, nothing on screen able to explain it.

Revocation has no step-up and no confirmation step. Reducing access must
never be harder than granting it was.

Grant management is non-delegable by construction rather than by a check:
every route here resolves through bare requireAuth(), which refuses while
the caller is acting on another account, so no code path through them
runs as somebody else. The switch endpoint is the one actor surface, and
it is the way back out. A delegate already inside a record renounces
after switching out, one request, rather than the fail-closed default
growing an exception that later gets widened.

The state machine is not re-implemented anywhere: routes call the grant
module's predicate and its transitions, and the session carrier has one
writer.
2026-08-02 13:04:25 +02:00
Marc-André Bombeck 843c74c98c feat(sharing): record who acted when it was not the account's owner
Adds AuditLog.actorUserId (migration 0294) and threads it centrally, out
of the wide-event context the acting-account resolver already stamps. No
call site passes an actor, so no route can forget one.

NULL keeps meaning "acted for themselves" — the reading every existing
row carries. The threading fills the column only when a request resolved
an acting account AND the row is being filed under that account, so a
self-action, a refusal, and a delegate's row about themselves all stay
NULL rather than acquiring an id that would rewrite what the history says.

Delegated reads coalesce to one row per owner, delegate and day, through
a partial unique index and an insert that expects to lose the race. The
alternative is a row per request on the busiest table in the schema and
an activity view made of identical lines.

The column carries no foreign key, against the grain of user_id beside
it: SET NULL there erases an account from its own history, while here it
would turn "the delegate opened this record" into "the owner opened this
record". An id that no longer resolves reads as a deleted account; an id
that silently became NULL reads as a lie.
2026-08-02 13:04:25 +02:00
Marc-André Bombeck 42f9e754e7 Merge pull request #688 from MBombeck/work/sharing-allowlists
Freeze which routes may serve someone else's record
2026-08-02 12:30:27 +02:00
Marc-André Bombeck e4b1718924 test(sharing): freeze the delegable and actor-surface route lists
Both resolvers land with empty allowlists. That is the correct start and
also the shape that hides a broken matcher: a scan that finds nothing
agrees with a list that holds nothing, and the two look identical from
outside. So every leg pins a count that does not start at zero. The scan
asserts it found route modules, the two frozen legs assert the matcher
still finds the declaration site, the co-occurrence leg asserts each
cookie-only helper is present in the tree it reads, and the two
out-of-band Bearer surfaces assert they still resolve a token of their
own before asserting they reach no resolver.

Membership is decided from the parsed module rather than the source text,
so a route may explain in a comment why it is not delegable without being
enrolled by saying so, and an aliased import cannot hide one. The
synthetic modules at the top prove both halves of that.

Enumerates with a recursive readdir rather than a glob: globSync skips
dot directories, so it drops the three route handlers under
src/app/.well-known and leaves the sweep looking healthy at 444 modules
instead of 447. One of the three is pinned by name.

Scans 447 route modules and 2338 source files, and finds nothing.
2026-08-02 12:10:43 +02:00
Marc-André Bombeck 6167ac5149 Merge pull request #687 from MBombeck/work/sharing-resolver
The acting-account resolver and its fail-closed refusal
2026-08-02 11:55:45 +02:00
Marc-André Bombeck 3f932040ad test(sharing): hold every arm of the acting-account resolver
The unit file walks the arms with the grant module deliberately unmocked,
so the resolver consuming the one "is this grant active" predicate is a
property under test rather than a claim in a comment. Its Prisma fake
honours its own `where` clause for the same reason: a fake that answers
any query with any row turns every scoping assertion into a check that
cannot fail.

The integration file proves the two things a unit suite cannot, because
both are about which rows come back. Substitution: the owner's
measurements are returned and the delegate's own, seeded alongside, are
not, so a resolver that quietly served the caller their own record shows
up as the wrong values rather than as an empty list. Never cached: a
revocation lands between two requests inside one test and the second one
403s.

The do-no-harm arm runs against a real shipped route, and the cookie-only
helpers are asserted against a real session row carrying a real switch,
because the one edit that would break them is `getSession()` itself
substituting the owner and no mocked session can catch that.

The structural guard freezes the set of files allowed to touch the
carrier column and the selector header, and asserts a non-zero match
count before comparing against the allowlist. A matcher that finds
nothing agrees with an emptied list and reports success; this repository
has shipped several guards that did exactly that.
2026-08-02 11:32:13 +02:00
Marc-André Bombeck e9029ed3c2 feat(sharing): resolve the acting account inside the auth layer
One resolver, both transports, on every request. The cookie path reads
the carrier off the session row it has already loaded; the Bearer path
reads the `X-HealthLog-Account` selector header, because stamping switch
state onto a long-lived token would make the credential itself ambient
authority. Two carriers converge on one function for the same reason
`resolveBearerToken` lives in one file for two wires.

Three declared modes. `requireRecordAuth("read" | "write")` honours a
valid switch and substitutes the owner as the data scope while keeping
the delegate as the actor. `requireActorAuth()` always serves the
caller's own rows and keeps working under a switch, which is what the
switcher and the banner need.

Bare `requireAuth()` refuses to run under a switch at all, with a stable
`sharing.not_permitted` code. It does not fall back to the caller's own
account, and that arm is the point of the whole design: a delegate who
believes they are reading the owner's record and is handed their own is
the same data mixing pointed the other way. A route nobody has reviewed
is inaccessible while switched, never wrongly accessible.

The grant is loaded from Postgres on the request that uses it. Nothing
memoises the verdict, so a revocation lands on the delegate's next
request rather than their next login.

Refusals do not enumerate. The denial takes no constructor arguments and
carries a fixed message, and neither branch looks the named account up:
an account that does not exist and one that granted nothing produce the
same empty row from the same query, so the two answers are identical in
bytes and in timing rather than by careful wording. The reason reaches
the audit row and the wide event and nothing else.

`getSession()` still answers who is calling. That is what leaves
`requireAdmin`, `requireCookieAuth` and `requireFreshMfa` structurally
out of a switch's reach; the row's carrier rides out beside the session
id as a value to be checked, never as a decision already made.

The selector header is a Bearer carrier only. Sent over the cookie
transport, or to an actor surface, it is refused rather than ignored. A
client that names an account on a route which never reads one has a bug,
and a correct response to a wrong expectation hides that bug until it
arrives as a support case about data that looks wrong.

Five test files gain the session shape their fixtures always claimed to
have; they were building an auth context without one.
2026-08-02 11:32:00 +02:00
Marc-André Bombeck 18f3fd6b50 feat(sharing): carry the acting account on the session row
Migration 0293 adds `sessions.acting_as_user_id`. NULL, which is what
every session has carried until now, means the browser is acting as the
account it signed in as.

It is a selector and not an authorization. The resolver joins it against
a live grant on every request, so a value stranded here by a grant that
has since been revoked or expired confers nothing. Nothing sweeps the
column for correctness; the sweeps that exist are housekeeping, so a
delegate's browser lands back in its own account instead of on a wall of
403s.

ON DELETE SET NULL, not CASCADE. The two ends mean opposite things:
deleting the session's owner should take the session with it, which is
the existing `user_id` cascade, while deleting the account being acted on
must leave the delegate's browser session alive. A cascade on this side
would sign a delegate out of their own account because somebody else
deleted theirs.
2026-08-02 11:31:41 +02:00
Marc-André Bombeck bf9bd924b2 Merge pull request #686 from MBombeck/work/sharing-grant-model
The account grant model and its lifecycle
2026-08-02 10:24:53 +02:00
Marc-André Bombeck 48f29cc802 test(sharing): hold the revoker pair at the database
A revoked grant with no revoker, or a revoker with no revocation, are
both rows that cannot answer the question the table exists to answer.
The migration already enforces the pair; this asserts it against real
Postgres rather than trusting that the domain module is the only writer.
2026-08-02 10:03:04 +02:00
Marc-André Bombeck 07e8ca9ef5 test(sharing): teach the wipe guard that ownership is not always user_id
The delete-all-data guard counted an account's surviving rows with a
literal `WHERE user_id = $1`, which is the same assumption the wipe loop
itself used to make. Account grants relate two accounts and carry no such
column, so the guard raised `column "user_id" does not exist` and stopped
before it could assert anything.

The predicate now comes from the wipe plan's own owner-column
declaration, so the guard asks the question the route answers instead of
its own version of it.
2026-08-02 10:03:04 +02:00
Marc-André Bombeck 33c879dd6b feat(sharing): add the account grant and its lifecycle module
An account grant is one account's standing permission to read another
account's record. The row is also the consent record for the act that
created it: there is no second receipt table, because two records of one
act drift and then nobody can say which is true.

That shapes the table. Revocation stamps revoked_at and revoked_by
instead of deleting, so the record can still answer who had access, from
when to when, and who ended it. The uniqueness constraint is therefore
partial — one live grant per (owner, delegate), with history accumulating
underneath — otherwise a re-invitation would either be refused or would
overwrite the first grant's acceptance. Both foreign keys cascade: a
grant naming a user who no longer exists is an authorization nobody can
resolve and nobody can revoke.

The state machine lives in src/lib/sharing/grants.ts and only there. The
acting-account resolver and the grant surfaces both read these rows, and
if each carried its own idea of "active" the drift would be silent in
exactly one direction: the resolver admitting a grant the panel shows as
ended. Pending confers nothing, expiry is checked against the clock of
the request that reads the row, and every transition is a conditional
update so two concurrent accepts cannot both win.

The access column carries READ or WRITE and only READ is ever written.
It exists from day one so that delegated writes become enforcement work
rather than migration work.

Three lifecycle paths, each proven against the real route:

- Delete All Data removes grants from either side. The wipe loop asks
  every model for "this account's rows", and a table relating two
  accounts has no user_id to answer with, so wipe-plan.ts now declares
  the owner columns and translates. Wiping only the grantor side would
  leave the account still holding access to other people's records.
- Account deletion removes them in both directions.
- An admin restore leaves them exactly as it found them. Grants are
  classified NOT_IN_BACKUP: rolling data back is a decision an admin
  makes, but rolling an authorization back is a decision nobody makes,
  and a grant revoked on Tuesday must not come back alive out of
  Monday's file. After a restore, sharing is off and both people
  re-consent.

The backup classification guard was reading a user relation by field
name, so a model naming its account relations grantor and grantee read
as instance-scoped and was excused from having a verdict at all. It now
reads the type. That surfaced InviteToken, classified here too.
2026-08-02 10:03:04 +02:00
Marc-André Bombeck 8febdbab26 Merge pull request #685 from MBombeck/fix/restore-unknown-symptom-key
Let a restore survive a catalogue key that no longer exists
2026-08-02 09:27:26 +02:00
Marc-André Bombeck 63075c47d4 test(backup): prove the skip report reaches the screen, not just the wire
The server names every unresolved catalogue key in its response and in the
audit row, and the integration suite holds that end. This is the other one:
a report nobody sees is the same silence the naming replaced.

The panel moves into its own exported component so it can be rendered
against a report directly. The SSR smoke tests in this directory cannot
drive a state transition, and a render proven only by reading it is not
proven. Pinned: every key is printed rather than summed away, each key
carries its own count and catalogue, an empty report renders nothing at
all, and the copy resolves in a second locale.
2026-08-02 09:10:58 +02:00
Marc-André Bombeck 9c4235b66d fix(backup): a retired catalogue key must not cost the whole file
Three of the restore's lookups resolve a key against a seeded catalogue:
cycle symptoms, illness symptoms, mood factors. Each threw on a key it
could not resolve, inside the one transaction that wipes and rebuilds the
account. So a single renamed symptom rolled everything back and answered
500. No measurements, no doses, no notes, nothing. A year-old backup read
by a newer instance is the ordinary case for a backup, and the catalogue
drifts between those two dates by design.

The unresolvable link is dropped and named now. What it costs is one
association between a row and a symptom; the day-log, the mood entry, the
flow, the temperature and the encrypted note all come back. The count and
the exact keys ride the response, the audit row and the wide event, and
the admin surface shows them in a panel that stays put instead of a toast
that leaves. A quiet drop would be the older failure of this same seam
wearing a success message.

A dangling `cycleId` or a dose recorded against a medication the file
never carried still throws. Those name rows the file was supposed to hold,
so a missing one means the file contradicts itself. A catalogue key names
a row the instance owns, which is why it gets the other answer.

`IllnessSymptom` carries no owner column at all, so a key that will not
resolve there can only ever be drift; the file was never able to supply it.

The restore does not mint the missing catalogue row back. That would
preserve the link at the price of reference data colliding with whatever
the next migration seeds under that key, and a label nothing can translate.
2026-08-02 09:04:36 +02:00
Marc-André Bombeck 1156839d73 Merge pull request #684 from MBombeck/release/v1.35.6
release/v1.35.6
2026-08-02 07:48:44 +02:00
Marc-André Bombeck 3cf2cb417f chore(release): v1.35.6 — one line where there were two 2026-08-02 07:29:42 +02:00
Marc-André Bombeck 3a46a74dcb Merge pull request #683 from MBombeck/fix/header-border-seam
Give the shell header band one owner
2026-08-02 07:28:49 +02:00
Marc-André Bombeck 57fbbcdef8 Give the app-chrome header band one owner
The top bar's bottom border and the sidebar logo band's bottom border draw
one horizontal line across the top of the app, and they sat a pixel apart.
Both declared h-16, so the number was never the problem. Every box in the
app is border-box: the top bar carried `h-16 border-b` on one element, which
puts the line inside the 4rem at 63 to 64 px, while the sidebar put `border-b`
on the wrapper and `h-16` on the link inside it, which puts the line after the
4rem at 64 to 65 px. Same number, different line.

The height and the border now travel together as SHELL_HEADER_BAND in
shell-metrics.ts, next to the sub-shell scroll floor that exists for the same
reason. The element carrying that class is the band; neither call site
restates a height, and the sidebar link stretches with h-full. Border colour
stays per-surface, because the two chrome surfaces are tinted apart by design
and only the geometry has to match.

Two guards. chrome-header-seam.test.tsx asserts the structural property, that
each band renders every token of the shared constant and declares no height of
its own; a second height class on either element replaces the shared one
through twMerge, so both halves fire on the same edit. The e2e spec measures
the painted result at 768, 900, 1024 and 1280 px in both the expanded sidebar
and the collapsed rail, and checks each band actually paints a border at the
same weight first, so two missing lines cannot pass as two aligned ones.
2026-08-02 07:12:19 +02:00
Marc-André Bombeck 57423d9f03 Merge pull request #680 from MBombeck/work/dashboard-verdict
Retire the dashboard verdict resolver
2026-08-02 06:38:02 +02:00
Marc-André Bombeck 42587d52bd Merge main 2026-08-02 05:54:53 +02:00
Marc-André Bombeck b972deed1f Merge pull request #682 from MBombeck/fix/e2e-two-failures
Scan the painted page, and bound the waits that could not time out
2026-08-02 05:54:44 +02:00
Marc-André Bombeck ece9ba90b1 Bound the two settle waits that could never time out
`settleBeforeMeasure` ends with a `waitForLoadState("networkidle")` whose
rejection is swallowed and a `page.evaluate` awaiting
`document.fonts.ready`. Both are written to end on their own terms, and
neither had a bound: the config leaves `actionTimeout` and
`navigationTimeout` unset, which Playwright reads as no limit, so a
single sub-resource that never completes consumes the whole test budget
rather than the wait.

The way it surfaces is the worst part. The swallowed timeout hides the
stall, the run reports whichever call was still pending when the fixture
closed the page, and the message reads

  Test timeout of 30000ms exceeded.
  Error: page.evaluate: Target page, context or browser has been closed

which names neither the surface nor the resource. Raising the budget
changes nothing, because no budget bounds an unbounded wait.

Route one font request to a handler that never answers and the current
code reproduces that message exactly; with the bound in place the same
run reaches the spec's own assertion in twelve seconds.

Six seconds is an order of magnitude above the slowest settle measured
across the suite (1.1 s, /insights at a mobile viewport).
2026-08-02 05:37:14 +02:00
Marc-André Bombeck ab13cfb689 Scan the painted page, not the skeleton standing in front of it
The `/insights/workouts` case gated its axe scan on `#main-content
[role="status"]`. That role is not a content marker: the busy skeletons
carry it too, and the one the streamed route shell paints first is a
`chart-skeleton` with `aria-busy="true"`. The sentinel therefore went
green on a document the page client had not touched yet. A frame trace
under a 20x CPU throttle puts that skeleton on screen at 408 ms and the
page's own `<h1>` at 4119 ms, so for most of four seconds the scan could
land on a tree with no level-one heading and report
`page-has-heading-one` against `html`. That is the failure a loaded
runner has been showing, and the page it accused has the heading.

Gate on the two states the page itself renders instead, the list or the
empty state. The overview case above already excludes `aria-busy`
skeletons the same way.

`/coach` had a smaller version of the same gap: `coach-page` is the
sizing wrapper around a `<Suspense fallback={null}>`, on screen 241 ms
before the conversation under it exists. Gate on the conversation.

Neither sentinel waits for a heading. Removing the `<h1>` from
`SubPageShell`, `CoachHero` and the conversation's screen-reader title
still turns the matrix red with four `page-has-heading-one` violations
per theme.
2026-08-02 05:37:03 +02:00
Marc-André Bombeck 86f0e5d2cb refactor(dashboard): remove the orphaned verdict resolver
The nine-rung verdict ladder was written for the opt-in dashboard hero.
That hero was retired when the digest-driven Today rail became the single
promoted hero, and its i18n copy was dropped across every locale in the
same change, but the resolver stayed behind. Since then it has had no
caller outside its own tests: nothing renders it and no string exists for
any of its variants.

Every rung it computed already has a live owner. Dose states ride the
digest's dose_window item, an elevated-at-rest window rides tension_window,
the score delta rides the digest score block the Today hero paints its chip
from, weight drift and sleep deficit and a silent stretch are the coach
nudge cron's own triggers, and a crisis blood-pressure reading is the
safety-floor engine's. Wiring a renderer back on would rebuild the second
hero the retirement removed.

- Delete the resolver, its ladder suite, and the client-safety import walk
  that pinned its bundle graph.
- Fold the two shared nudge thresholds back into the cron. The leaf module
  existed only so a client component could read them without dragging the
  server graph along; there is no such component now.
- Repoint the score-config guard off the verdict onto the digest fields the
  Today hero actually reads, so it still fails on the assembly it was
  written for.
- Repoint the clinical-floors notes off the retired surface.
2026-08-02 02:32:24 +02:00
Marc-André Bombeck 4a8a4e1e30 Merge pull request #679 from MBombeck/release/v1.35.5
release/v1.35.5
2026-08-02 02:15:25 +02:00
Marc-André Bombeck 03d2a712d0 Move the contract tests to the end that now writes
Three integration cases pinned the old behaviour: the sync handshake stamping
the checkpoint, and the calendar read persisting the prediction. Both are the
faults this release removes, so the cases were asserting a bug.

Each file now asserts the read writes nothing AND that the other end does. The
second half is not decoration: without it, "nothing was written" would pass
just as well against a column nothing writes at all.

The cycle case seeds its own history and its own profile row rather than
reaching a route to get one, because reaching the route is exactly what the
prediction must no longer depend on.
2026-08-02 02:00:08 +02:00
Marc-André Bombeck c9ee84e5e4 chore(release): v1.35.5 — a read stops deciding what gets written 2026-08-02 01:30:12 +02:00
Marc-André Bombeck b40e9bc40f Merge work/side-effecting-gets 2026-08-02 01:29:46 +02:00
Marc-André Bombeck 1e6f72b1c5 Prove the achievements read writes nothing against a real pending unlock
The assertion in the module-gate suite could not fail: that fixture's mood
badges carry no completion date, so the result it drove had no pending
unlock and "nothing was written" was true either way. Restoring the INSERT
left it green.

The case moves to its own file with the builder faked so the result always
carries a pending unlock. Undoing the fix now turns it red. The
disabled-module invariant the old case reached for lives with the write, in
the sweep's suite.
2026-08-02 01:27:42 +02:00
Marc-André Bombeck 6ac3a61829 Take the writes off three read routes
A GET must not have side effects — api-handler.ts says so next to
READ_HTTP_METHODS, where an MCP-audience token is admitted on the safe
methods precisely because they are assumed to write nothing. Three routes
broke that: the sync handshake bumped User.lastSyncedAt, the achievements
read inserted unlock rows, and the cycle calendar fired a discarded promise
at the forecast cache so a failed write left no trace anywhere.

Each write moves to the place that causes it.

The sync checkpoint is now stamped by the batch ingest endpoints for
measurements, mood and intakes. The handshake reports it. That also fixes
the watermark: the checkpoint used to advance past a window the client had
not drained, and a client trusting it would skip that window. It can only
trail a real sync now.

The unlock rows move to a nightly achievement-unlock-sweep. The badge grid
never needed them — unlocked comes from the live metrics and the completion
date is derived — so the payload is unchanged; the rows pin that date and
carry it into the backup, and the sweep reaches accounts that never open
the page.

The cycle forecast moves to a nightly cycle-prediction-refresh. The
CyclePrediction row is not a cache of a read: it is the index the reminder
cron scans, so which reminders an account received depended on whether
somebody had opened the calendar. persistPredictionCache no longer
swallows its errors either — the job reports them.
2026-08-02 01:21:03 +02:00
Marc-André Bombeck 817886e145 Merge pull request #678 from MBombeck/release/v1.35.4
release/v1.35.4
2026-08-02 00:57:18 +02:00
Marc-André Bombeck 2618a7ae71 chore(release): v1.35.4 — the checks tell the truth about the calendar and about themselves 2026-08-02 00:38:01 +02:00
Marc-André Bombeck c682145627 Merge work/score-version-fixtures 2026-08-02 00:37:11 +02:00
Marc-André Bombeck 7a6335a2c7 Merge work/session-surface-guard 2026-08-02 00:37:10 +02:00
Marc-André Bombeck 3b9504a441 Merge work/today-day-arithmetic 2026-08-02 00:37:10 +02:00
Marc-André Bombeck eb641dcd7b Merge pull request #677 from MBombeck/fix/vorsorge-test-timezone
Anchor the checkup due fixtures to the zone the component reads
2026-08-02 00:36:52 +02:00
Marc-André Bombeck 9fb0f8b798 Anchor the checkup due fixtures to the zone the component reads
The two calendar-day cases built their due instant with setHours on the
process clock, which vitest pins to UTC, while the component floors the due
date in the profile zone. Those two disagree about the date for the two hours
before UTC midnight, so both cases went red every night in that window and
green again by morning.

Deriving the date parts from the display zone removes the disagreement rather
than hoping the suite never runs at night. Noon is chosen deliberately: at any
offset the zone uses, 12:00 UTC lands on the same calendar date there, so the
instant cannot slide either way.

Verified inside the failing window: red before, green after, and putting
setHours back turns it red again.
2026-08-02 00:19:59 +02:00
Marc-André Bombeck af35346687 Derive score-version fixtures from the SCORE_VERSION constant
Eight test and fixture files hardcoded scoreVersion: 2, a value the
constant has not held since v1.35.0. Now they import SCORE_VERSION and
use it, so a future bump cannot leave a fixture pinned to a stale
number.

The one genuinely historical case (record.test.ts, proving the input
fingerprint moves when the algorithm version moves) now derives both
its "previous" and "current" markers from SCORE_VERSION instead of two
unrelated literals, so the pair keeps its meaning after the next bump.
2026-08-02 00:15:29 +02:00
Marc-André Bombeck da85e64cfa Catch the Bearer resolver the guard's matcher walked past
The Bearer guard demanded the literal `apiToken.findUnique(`.
`lib/idempotency.ts` writes the same call fluent-style, with a newline
between `prisma.apiToken` and `.findUnique({`, so the matcher never saw
it. It has been resolving a raw Bearer value to a user id since the
idempotency work landed, outside the frozen set, while the guard stayed
green on five files.

Tolerate whitespace around the member access and name the file with what
it does: it decides which user's idempotency cell a replay lands in, and
authorises nothing, because the handler still runs its own requireAuth.

Add the non-zero count assertion the other guards now carry. Narrowing
the regex back to its old form turns this test red, which is the proof
the broadened matcher is what finds the file. The mint-site matcher in
T3 was checked for the same defect and has no hidden members.
2026-08-01 22:45:04 +02:00
Marc-André Bombeck a08631e0a1 Freeze the set of surfaces that resolve a caller by any mechanism
The Bearer guard freezes one mechanism: the files that turn an
Authorization header into a user. It reads like coverage of "who can
resolve a caller" and it is not. Two other families do the same job by
other means and no guard watches either.

Fifteen files under src/app read the session cookie directly instead of
going through requireAuth: eight API routes and seven pages. Nine more
authenticate on a token carried in the URL, including the clinician
share tree, which serves one person's whole health record to an
anonymous caller holding a path segment. A sweep that greps for
getSession sees none of the second family.

Freeze both as literal lists with a reason per entry, matched by five
independent legs: the session-deriving helpers, a direct read of the
session cookie name, a dynamic route segment carrying a credential,
share-token resolution, and a query-string credential. Legs overlap, so
each asserts its own membership and its own non-zero count. A leg whose
matcher stops matching then fails instead of letting the union carry it.
2026-08-01 22:39:50 +02:00
Marc-André Bombeck 7df25a6d92 Merge pull request #676 from MBombeck/fix/settings-overscroll
Give the scroll container its own containing block
2026-08-01 21:42:27 +02:00
Marc-André Bombeck 6bc5aff84a Record the pre-hydration scroll surface in the release notes 2026-08-01 21:25:52 +02:00
Marc-André Bombeck 1b7dff411a Give the scroll container its own containing block
`<main id="main-content">` scrolls the authenticated shell, but it was
`position: static`, so an absolutely-positioned descendant with no nearer
positioned ancestor resolved against the initial containing block. That
block sits outside the scroll container: `overflow-y-auto` never clipped
those boxes, and their static position extended the DOCUMENT's scrollable
overflow instead. The result is a second vertical scroll surface beside
`<main>`, which UI-STANDARDS §9 forbids.

The escapees are library markup, so no per-component wrapper would have
caught them. A Radix `<Switch>` outside a `<form>` renders a hidden
`position:absolute` bubble input on its first pass and drops it only once
the button ref resolves, and the root `loading.tsx` chart skeleton carries
an `sr-only` announcement that lives until the real content streams in.
Both are gone within a few hundred milliseconds of hydration, so the page
carried a full-height document scrollbar for the whole pre-hydration
window and looked clean immediately after. On /settings/modules at a
390x844 viewport the document measured 1952 px against an 844 px viewport
while the switches were still bubble-inputs.

Anchoring the scroll container closes the escape route for every such box
at once. The over-scroll guard grows the matching structural assertion:
`<main>` must not compute to `position: static`. The height read it
already had can only see an escapee that happens to be mounted at measure
time, which is why it went red on a loaded CI runner and green on the same
tree twenty minutes earlier; the computed style is timing-free and fails
on every route and both viewports the moment the anchor is removed.
2026-08-01 21:24:24 +02:00
Marc-André Bombeck 6d4eefe26b Merge pull request #675 from MBombeck/release/v1.35.3
release/v1.35.3
2026-08-01 20:20:27 +02:00
Marc-André Bombeck 67d4f87720 Hold the checkup overdue flag for the whole day it is due
The MCP due-list answered "is this checkup overdue" by comparing the two
instants, so a checkup booked for nine in the morning read overdue from ten
past. The screens read the same reminder as "today" until midnight. One
reminder, two verdicts, and the model reading the tool result repeated the
one nobody could see.

Same counting as the screens and the briefing payload now, on the account's
own clock rather than the server's. A checkup stays due for the whole of the
date it belongs to, and is overdue from the date after.
2026-08-01 20:09:37 +02:00
Marc-André Bombeck 49ac6679c8 Count preventive-care days on the person's calendar, not in hours
The briefing payload states how far off a checkup is as a bare number the
model narrates back: "due in N days", "overdue by N days". It got that
number by dividing the hour gap by twenty-four, which answers a different
question than the one the sentence asks. A checkup booked for nine this
morning came out "overdue by 0 days" by the evening. One due Sunday at
01:00, read late on Friday, came out one day off — Saturday, on a calendar
where it is two. A clock-change day is twenty-three or twenty-five hours
long and rounded whichever way its length pushed it.

The checkup screens had exactly this and it was fixed there, so the counting
already exists. Lift it out as `calendarDaysUntil` and have both the phrase
and the number come off it, rather than leaving the payload with a second
body that can drift again. It counts by differencing two integer day indices
read on the person's profile clock, so the answer is exact rather than
rounded, and `extractFeatures` resolves that zone and hands it down — the
number now agrees with the screen the person is looking at.

Today's checkup moves off the overdue list, where the hour gap had put it as
soon as its appointment time passed. The hour it was booked for may be
behind, but the day it belongs to is not.

The horizon that bounds the read stays an hour cutoff on purpose. It is a
query bound, not a statement to anyone about which day something falls on.
2026-08-01 20:04:10 +02:00
Marc-André Bombeck ffe5545032 chore(release): v1.35.3 — an ECG arrives on its own, and only once
Apple Watch ECG recordings reach the record straight from the app instead of
only through an export archive. One recording per request, gated by the same
switches that already govern reading them.

A recording is now identified by what it is rather than by what a source calls
it, so the same strip arriving through both doors converges on one row. The
migration that adds the constraint resolves the duplicates already stored: it
keeps the row holding the waveform over one holding only a verdict, and moves a
removed row's event link onto the row that is kept. The losing rows are deleted.
2026-08-01 19:54:08 +02:00
Marc-André Bombeck 3b37d73f31 Merge branch 'work/ecg-ingest' into release/v1.35.3 2026-08-01 19:50:52 +02:00
Marc-André Bombeck 42e16a6e12 Stop the plaintext-waveform check passing on a coincidence
It asserted the stored ciphertext does not contain each sample rendered
as a string. Base64 is full of digits, so a short sample value like 3
matches by accident: the check failed on a mutation that had nothing to
do with encryption, and would equally have passed while leaking. It now
asserts the column holds the keyId.base64 envelope and nothing else,
which a serialised sample array cannot satisfy.
2026-08-01 19:35:16 +02:00
Marc-André Bombeck 8f90fd3174 Prove the ECG ingest, the dedupe and the migration on dirty data
A round trip through the real handlers: post a recording, read it back
through the list and the detail routes, and check what a client actually
receives rather than a fixture rebuilt at each end. Post it twice and
the second call says updated, not inserted, and the table does not grow.
Feed the same strip to the export-archive importer afterwards and it
says skipped; feed it to the importer first and the route says
duplicate. Both directions leave one row.

The migration test drops the index, manufactures the collisions the
resolution step exists for, and runs the migration file through the same
executor the deploy uses. It checks which row survived each tiebreak,
that the salvaged event link followed the keeper, that rows differing
only by user, source or sampling rate were left alone, and that the
constraint rejects a new twin afterwards. Applying the migration to the
empty testcontainer proves none of that.

The Withings ECG tests now hand the transaction the same delegate the
shared writer uses, so they still watch the real write instead of a stub
standing in for it.
2026-08-01 19:26:47 +02:00
Marc-André Bombeck 0e301b580c Let an Apple Watch ECG arrive without a 1.5 GB export archive
POST /api/insights/ecg takes one recording per request: the stable
recording id the client already has, the on-device timestamp, the
sampling rate, the waveform as integer micro-volts, the lead, the
average heart rate, and the device's own verdict. Same gating as the
reads (auth, the insights module, the insightStatus surface), userId
from the session, APPLE_HEALTH the only source a client may claim.
sampleCount and durationSeconds are derived here, and nothing about the
waveform is ever interpreted.

The write body now lives in one place, src/lib/ecg/persist-recording.ts,
shared by the Withings sync, the export-archive importer and the new
route. Three writers with three persistence bodies is how the two ends
of one rule drift apart.

Migration 0291 adds the second unique index on
(user_id, source, recorded_at, sampling_frequency). The archive importer
identifies a strip by a hash of its content and a live client by the
device's own sample uuid, so the same physical recording arriving
through both doors carried two different ids and would have landed
twice. One device does not record two different strips at the same
instant at the same sampling rate, so the constraint is sound and the
convergence stops being a convention.

The table already holds rows on deployed instances and two writers have
been filling it since v1.19.0, so the index cannot just be created: a
pre-existing collision would abort the migration. The migration resolves
duplicates first, keeping the row with the most samples (a stored strip
beats a verdict-only row), then the one linked to its event
measurement, then the most recently written, then the lowest id so the
choice is total. The losers' event link is salvaged onto the keeper
first, so resolving a duplicate never costs the recording its place in
the event timeline.

If that resolution is wrong on some instance, the failure is visible at
deploy time and not later: db:migrate:deploy runs on boot, so the
container crash-loops with the migration named in the logs and the
release never serves traffic. A deploy that finishes in under thirty
seconds did not run it.

The GET list and detail routes and the export-archive path are
unchanged; this is a second door, not a replacement.
2026-08-01 19:19:01 +02:00
4057 changed files with 584822 additions and 63748 deletions

No files matched your search

+106 -9
View File
@@ -4,6 +4,9 @@
# Copy this file to .env and fill in the values.
# $ cp .env.example .env
#
# This is a short starter. Every variable the app reads, with what it does,
# is documented in .env.production.example.
#
# Required variables: DATABASE_URL or POSTGRES_PASSWORD,
# ENCRYPTION_KEY, API_TOKEN_HMAC_KEY
#
@@ -59,6 +62,18 @@ NODE_ENV="development"
# internet; the session cookie crosses the wire in cleartext.
# SESSION_COOKIE_SECURE="false"
# Where this server's environment is configured: compose, truenas, coolify,
# unraid or portainer. Only picks which instructions the admin's "Back up
# your encryption key" step shows first; unset means compose.
# HEALTHLOG_PLATFORM="compose"
# Start-up encryption key check: enforce (default) refuses to serve when the
# key does not open the stored data; warn only logs it and serves anyway. A
# last resort for a refusal you are certain is false (a first start, with no
# recorded key to reset). It disables a safety check: with a wrong key every
# encrypted value fails and new rows are written under that key.
# ENCRYPTION_KEY_CHECK="enforce"
# -----------------------------------------------------------------------------
# Required Secrets — generate with `openssl rand -hex 32`
@@ -76,10 +91,9 @@ API_TOKEN_HMAC_KEY="REPLACE-WITH-OUTPUT-OF-openssl-rand-hex-32"
# -----------------------------------------------------------------------------
# Withings OAuth (optional — for automatic scale/BP/activity sync)
# -----------------------------------------------------------------------------
# Register an app at https://developer.withings.com/ and paste the credentials
# here. Per-user OAuth credentials can also be configured in Settings.
# WITHINGS_CLIENT_ID=""
# WITHINGS_CLIENT_SECRET=""
# Register an app at https://developer.withings.com/ and enter its client id
# and secret in Settings -> Integrations -> Withings. There is no environment
# variable for them; only the redirect override and webhook secret live here.
# WITHINGS_REDIRECT_URI="https://healthlog.example.com/api/withings/callback"
# WITHINGS_WEBHOOK_SECRET="" # any random string — used to harden the webhook URL
@@ -92,16 +106,46 @@ API_TOKEN_HMAC_KEY="REPLACE-WITH-OUTPUT-OF-openssl-rand-hex-32"
# TELEGRAM_WEBHOOK_SECRET=""
# -----------------------------------------------------------------------------
# Notification targets on a private network (optional)
# -----------------------------------------------------------------------------
# Webhook (Gotify, Home Assistant, n8n) and ntfy targets on your own network,
# comma-separated exact origins, e.g. "https://gotify.example.com,http://ntfy.lan:8080".
# A target resolving to a private address is otherwise refused at send time.
# Link-local, metadata and unspecified addresses stay refused even when listed.
# See docs/self-hosting/notifications.md.
# NOTIFICATION_PRIVATE_ORIGINS=""
# -----------------------------------------------------------------------------
# Document picker: Paperless-ngx and Papra -- optional
# -----------------------------------------------------------------------------
# The Paperless-ngx and Papra instances people may connect to pick documents
# from, comma-separated exact origins (scheme://host[:port], no path), e.g.
# "https://paperless.example.com,http://papra.lan:1221". Unset, the document
# picker is switched off. Only a listed origin is ever contacted, public or
# private; requests are pinned to it, redirects are not followed, and
# link-local, metadata and unspecified addresses stay refused even when
# listed. A malformed entry is logged once and grants nothing.
# See docs/self-hosting/document-sources.md.
# DOCUMENT_SOURCE_ORIGINS=""
# -----------------------------------------------------------------------------
# AI Provider (optional)
# -----------------------------------------------------------------------------
# Users bring their own API keys via Settings. No server-side key needed by
# default. The admin can configure a fallback key in the Admin Panel.
# Local-AI SSRF opt-in (optional). The local AI provider rejects private/
# internal hosts by default. Set to an exact host allowlist (comma-separated,
# e.g. "ollama.lan,10.0.0.5") or "true" for any private host — intended for a
# self-hosted Ollama / LM Studio endpoint. See docs/integrations/ai-providers.md.
# AI endpoints on your own network (optional). An AI base URL on a private
# address is refused unless its exact origin is listed here, comma-separated
# (e.g. "http://ollama.lan:11434,http://10.0.0.5:4000") — for a self-hosted
# Ollama, LM Studio or LiteLLM gateway. Link-local, metadata and unspecified
# addresses stay refused even when listed. See docs/integrations/ai-providers.md.
# AI_PRIVATE_ORIGINS=""
# Older form, kept for existing installs: an exact host list still works
# (e.g. "ollama.lan,10.0.0.5"). "true" is deprecated: it now covers only the
# admin AI key and admin accounts' own AI settings, and will be removed.
# ALLOW_LOCAL_AI_PRIVATE_HOSTS=""
# Daily-briefing output-token ceiling (optional). Default 2500, clamped to
@@ -169,6 +213,13 @@ API_TOKEN_HMAC_KEY="REPLACE-WITH-OUTPUT-OF-openssl-rand-hex-32"
# regex- and length-bounded), but the gating decision is up to the
# operator — there is no way for the server to detect whether the flag
# matches the real deployment topology. When in doubt, leave it off.
# Number of trusted reverse-proxy hops in front of the app. The client IP is
# read that many entries from the right of the X-Forwarded-For chain. Set 0
# for a directly-exposed host; 1 (the default when unset) behind a single
# reverse proxy. X-Real-IP is read only at 1. A wrong value makes the app
# refuse the headers, log one warning, and share one rate-limit bucket across
# all anonymous callers.
# TRUST_PROXY_HOPS="1"
# TRUST_CF_CONNECTING_IP=""
@@ -201,13 +252,47 @@ API_TOKEN_HMAC_KEY="REPLACE-WITH-OUTPUT-OF-openssl-rand-hex-32"
# the backup silently. The backup runs at 02:30 Europe/Berlin via pg-boss cron.
# Restore with `pnpm tsx scripts/restore-backup.ts <userId> <YYYY-MM-DD>`.
# See docs/ops/backup-restore.md for the format spec + step-by-step.
#
# The worker never deletes a BACKUP object -- its grant is PutObject, GetObject
# and AbortMultipartUpload -- so BACKUP_RETENTION_DAYS is the number you set
# the bucket's own lifecycle rule to, not something the worker enforces. The
# one key it does delete is its own connection test's `_healthcheck/<ts>.bin`,
# and that delete is best-effort: without DeleteObject on that prefix every
# Test-connection press leaves one 1-byte orphan behind, silently.
#
# BACKUP_S3_ENDPOINT="https://<account>.r2.cloudflarestorage.com"
# BACKUP_S3_BUCKET="healthlog-backups"
# BACKUP_S3_ACCESS_KEY=""
# BACKUP_S3_SECRET_KEY=""
# BACKUP_S3_REGION="auto" # "auto" for Cloudflare R2; real region for AWS S3
# BACKUP_RETENTION_DAYS="30" # objects older than this are pruned (best-effort; prefer a bucket lifecycle rule)
# BACKUP_RETENTION_DAYS="30" # the number for your bucket lifecycle rule (see above)
# BACKUP_ENCRYPTION_KEY="" # 64-hex-char or base64 32-byte; SEPARATE from ENCRYPTION_KEY
# BACKUP_ENCRYPTION_PREVIOUS_KEYS="" # retired off-host keys, comma-separated, read-only during a rotation
# -----------------------------------------------------------------------------
# Stored backups in the database (optional)
# -----------------------------------------------------------------------------
# The largest weekly or uploaded backup of one account the app keeps, in
# megabytes of encrypted copy. Default 2048. It does not depend on the app's
# memory: a copy is written and read in pieces of about a megabyte. The limit
# only stops a runaway copy from filling the database volume, which holds the
# old and the new copy side by side while a backup runs. An account with 2.6
# million readings stores a copy of about 100 MB.
# BACKUP_MAX_STORED_MB="2048"
# -----------------------------------------------------------------------------
# Audit-trail retention (optional)
# -----------------------------------------------------------------------------
# How long rows in `audit_logs` are kept. Default 365 days; the floor is 7 and
# anything below it is ignored, so a window set in seconds by mistake cannot
# empty a fresh table. A daily pg-boss job does the pruning.
#
# The number is not internal. Settings -> Shared access states it under the
# activity list, and the dialog that ends somebody's access says how long
# "who entered what" stays answerable. Both read the value the server
# resolved, so an instance running 90 says 90 everywhere.
# AUDIT_LOG_RETENTION_DAYS="365"
# -----------------------------------------------------------------------------
@@ -242,6 +327,15 @@ API_TOKEN_HMAC_KEY="REPLACE-WITH-OUTPUT-OF-openssl-rand-hex-32"
# DEPLOY_WEBHOOK_SECRET=""
# -----------------------------------------------------------------------------
# Outbound requests HealthLog makes on its own (optional switches)
# -----------------------------------------------------------------------------
# Each accepts "1", "true" or "yes". See .env.production.example for detail.
# PASSWORD_BREACH_CHECK_DISABLED="1" # no HaveIBeenPwned range query when a password is set
# UPDATE_CHECK_DISABLED="1" # no daily GitHub releases request
# IP_GEO_LOOKUP_DISABLED="1" # no online IP geolocation for login events
# -----------------------------------------------------------------------------
# IP geolocation (optional)
# -----------------------------------------------------------------------------
@@ -250,3 +344,6 @@ API_TOKEN_HMAC_KEY="REPLACE-WITH-OUTPUT-OF-openssl-rand-hex-32"
#
# Directory the offline GeoLite2 databases are read from; default /opt/geolite2 (the path the image bakes its own copy into). Point it at a directory you mount yourself to bring your own MMDBs — see docs/self-hosting/geolite2.md.
# GEOLITE2_DIR="/var/lib/geolite2"
#
# MaxMind licence key for the runtime GeoLite2 fetch (issue #659): set it and the worker downloads both databases into GEOLITE2_DIR itself, no rebuild or manual mount. Free key at https://www.maxmind.com/en/geolite2/signup — see docs/self-hosting/geolite2.md.
# MAXMIND_LICENSE_KEY="your-maxmind-licence-key"
+336 -17
View File
@@ -35,6 +35,68 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# own Withings developer app and pastes the pair into Settings (stored
# encrypted in the DB). There is therefore no WITHINGS_CLIENT_ID/SECRET.
# WITHINGS_WEBHOOK_SECRET=""
# Overrides the derived "<NEXT_PUBLIC_APP_URL>/api/withings/callback". Set it
# when the callback registered with Withings differs from the app's own
# public URL -- e.g. a second hostname in front of the same instance.
# WITHINGS_REDIRECT_URI=""
# -----------------------------------------------------------------------------
# Google Health Connect -- optional integration (per-user BYO-keys)
# -----------------------------------------------------------------------------
# Like Fitbit, the client id/secret are per-user and live encrypted in the DB.
# This only overrides the derived
# "<NEXT_PUBLIC_APP_URL>/api/google-health/callback"; it must stay same-origin
# with NEXT_PUBLIC_APP_URL or the handshake is refused.
# GOOGLE_HEALTH_REDIRECT_URI=""
# -----------------------------------------------------------------------------
# Telegram -- optional notification channel
# -----------------------------------------------------------------------------
# Shared secret for the Telegram bot webhook. It is both the path segment the
# bot posts to and the value compared against the update header, so set it
# before installing the webhook from Settings -> Notifications. Without it the
# settings page cannot register the webhook and inbound updates are refused.
# TELEGRAM_WEBHOOK_SECRET="<openssl rand -hex 32>"
# -----------------------------------------------------------------------------
# Nightscout -- optional integration
# -----------------------------------------------------------------------------
# Nightscout instances on your own network that the per-user connection form
# should accept, comma-separated (e.g. "http://nightscout.lan:1337"). The
# validator refuses private and internal hosts by default; this is the opt-in
# for a self-hosted Nightscout that is not reachable from the public internet.
# NIGHTSCOUT_PRIVATE_ORIGINS=""
# -----------------------------------------------------------------------------
# Notification targets on a private network -- optional
# -----------------------------------------------------------------------------
# Webhook (Gotify, Home Assistant, n8n, a Discord relay) and ntfy targets on
# your own network, comma-separated exact origins (scheme://host[:port], no
# path). A target that resolves to a private address is otherwise refused at
# send time; the test button reports it as private_origin_not_approved. A
# listed origin is still dialled through the pinned resolver with redirects
# forbidden; link-local, metadata and unspecified addresses stay refused even
# when listed, and a malformed entry is logged once and grants nothing.
# See docs/self-hosting/notifications.md.
# NOTIFICATION_PRIVATE_ORIGINS=""
# -----------------------------------------------------------------------------
# Document picker: Paperless-ngx and Papra -- optional
# -----------------------------------------------------------------------------
# The Paperless-ngx and Papra instances people may connect to pick documents
# from, comma-separated exact origins (scheme://host[:port], no path), e.g.
# "https://paperless.example.com,http://papra.lan:1221". Unset, the document
# picker is switched off. Only a listed origin is ever contacted, public or
# private; requests are pinned to it, redirects are not followed, and
# link-local, metadata and unspecified addresses stay refused even when
# listed. A malformed entry is logged once and grants nothing.
# See docs/self-hosting/document-sources.md.
# DOCUMENT_SOURCE_ORIGINS=""
# -----------------------------------------------------------------------------
@@ -140,10 +202,9 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# The EASIEST path is the admin panel: /admin -> Web Push VAPID -> "Generate
# keys" mints and stores the pair for you (private key encrypted at rest). Use
# these env vars only if you prefer env-config over the DB. The loader reads
# DB first, then env (src/lib/notifications/vapid-config.ts). NOTE: these are
# NOT in docker-compose.yml's `environment:` whitelist -- if you go the env
# route under compose, add them there too or the values never reach the
# container (see docs/self-hosting/getting-started.md Troubleshooting).
# DB first, then env (src/lib/notifications/vapid-config.ts). These three
# names are the only ones it reads, and all three are on docker-compose.yml's
# `environment:` whitelist, so a value set here reaches the container.
# VAPID_PUBLIC_KEY=""
# VAPID_PRIVATE_KEY=""
# VAPID_SUBJECT="mailto:you@example.com"
@@ -164,6 +225,7 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# APNS_KEY="" # OR APNS_KEY (raw PEM) OR APNS_KEY_FILE -- one satisfies the manifest
# APNS_KEY_FILE=""
# APNS_CRITICAL_ENTITLEMENT="" # "true" only if your build has Apple's Critical Alerts entitlement; else urgent = time-sensitive
# APNS_PRODUCTION="" # "true" forces the production APNs gateway; normally derived from NODE_ENV
# -----------------------------------------------------------------------------
@@ -184,6 +246,35 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# SMTP_SECURE="false"
# -----------------------------------------------------------------------------
# Session cookie Secure flag -- the most common self-host snag
# -----------------------------------------------------------------------------
# Unset, the flag tracks NODE_ENV, so a production image sets `Secure` and a
# browser on plain HTTP silently drops the session cookie: login appears to
# succeed and every following request is anonymous. Set it to false ONLY on a
# LAN, Tailscale or VPN-only host that deliberately serves HTTP. Behind a TLS
# reverse proxy, leave it alone.
# SESSION_COOKIE_SECURE="false"
# -----------------------------------------------------------------------------
# Platform hint for the encryption key backup step
# -----------------------------------------------------------------------------
# Where this server's environment lives: compose, truenas, coolify, unraid or
# portainer. The admin's "Back up your encryption key" step opens on the
# instructions for that platform. Unset means compose. Catalog templates set
# it for you.
# HEALTHLOG_PLATFORM="compose"
# Start-up encryption key check: enforce (default) refuses to serve when the
# key does not open the stored data; warn only logs it, reports it as a
# warning on /api/health, and serves anyway. A last resort for a refusal you
# are certain is false (a first start, with no recorded key to reset). It
# disables a safety check: with a wrong key every encrypted value fails and
# new rows are written under that key. Remove it once the key is confirmed.
# ENCRYPTION_KEY_CHECK="enforce"
# -----------------------------------------------------------------------------
# Deploy webhook -- Coolify -> HealthLog auto-deploy feedback
# -----------------------------------------------------------------------------
@@ -208,10 +299,15 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# docs/ops/tls-cert-pin.md for extraction + the re-pin runbook.
# TLS_LEAF_SPKI_PINS=""
# Local-AI SSRF opt-in (optional). The local AI provider rejects private/
# internal hosts by default. Set to an exact host allowlist (comma-separated,
# e.g. "ollama.lan,10.0.0.5") or "true" for any private host — intended for a
# self-hosted Ollama / LM Studio endpoint. See docs/integrations/ai-providers.md.
# AI endpoints on your own network (optional). An AI base URL on a private
# address is refused unless its exact origin is listed here, comma-separated
# (e.g. "http://ollama.lan:11434,http://10.0.0.5:4000") — for a self-hosted
# Ollama, LM Studio or LiteLLM gateway. Link-local, metadata and unspecified
# addresses stay refused even when listed. See docs/integrations/ai-providers.md.
# AI_PRIVATE_ORIGINS=""
# Older form, kept for existing installs: an exact host list still works
# (e.g. "ollama.lan,10.0.0.5"). "true" is deprecated: it now covers only the
# admin AI key and admin accounts' own AI settings, and will be removed.
# ALLOW_LOCAL_AI_PRIVATE_HOSTS=""
# Daily-briefing output-token ceiling (optional). Default 2500, clamped to
@@ -219,6 +315,54 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# ("AI response was cut off"). See docs/integrations/ai-providers.md.
# INSIGHTS_MAX_TOKENS=""
# Per-user hourly ceiling for POST /api/insights/generate (optional).
# Default 10. Lower it on a tight LLM budget; the 24h cache already
# short-circuits read traffic. See docs/integrations/ai-providers.md.
# INSIGHTS_RATE_LIMIT_PER_HOUR=""
# Per-user hourly ceiling for the document-AI actions (optional). Read/index,
# extract, suggest and summarise share one bucket per user. Default 6,
# clamped to 1-1000. Raise it when users batch-read many documents against a
# generous provider budget; lower it on a tight one. See
# docs/integrations/ai-providers.md.
# DOCUMENT_AI_LIMIT_PER_HOUR=""
# Hourly upload ceiling for each document-upload token (optional). Applies
# only to uploads made with a token minted under Settings > API & Tokens >
# Document tokens: a Paperless workflow or the import script. Every upload
# that sends a file counts, duplicates included. Default 120, clamped to
# 1-1000. Uploads from the web app and the phone keep their own bucket. Raise
# it to import a large archive faster; the per-user storage quota still
# applies. See docs/integrations/document-import.md.
# DOCUMENT_UPLOAD_LIMIT_PER_HOUR=""
# Per-user hourly ceiling for lab-report scans (optional). The photo/PDF scan
# and the browser-OCR text scan share one bucket per user. Default 6, clamped
# to 1-1000. Raise it when users scan a stack of reports at once against a
# generous provider budget; cost stays bounded by the daily AI budget. See
# docs/integrations/ai-providers.md.
# LABS_OCR_LIMIT_PER_HOUR=""
# Extra hosts the ADMIN-configured AI base URL may point at, on top of the
# built-in public providers (comma-separated bare hostnames). Set it when you
# run a gateway this instance should trust. It widens the admin setting only;
# per-user BYO keys keep the pinned public-host posture either way.
# ADMIN_AI_BASE_URL_ALLOWLIST=""
# Codex (ChatGPT sign-in) model slugs. CODEX_MODEL pins one slug ahead of the
# built-in chain; CODEX_MODEL_FALLBACK_CHAIN replaces the chain outright
# (comma-separated, first match wins). Reach for these when the provider
# rotates a slug and requests start failing with 503 -- without them a
# rotation needs a new release to fix.
# CODEX_MODEL=""
# CODEX_MODEL_FALLBACK_CHAIN=""
# Surfaces reviewed n-of-1 experiment outcomes in the Coach snapshot. Off by
# default: the read-back is the most overclaim-prone Coach surface, so it is a
# deliberate operator opt-in. Set to "1" to enable; anything else keeps it
# dormant while the review worker still records outcomes.
# COACH_EXPERIMENT_VERDICT="1"
# -----------------------------------------------------------------------------
# Off-host backups -- all-or-none
@@ -229,6 +373,84 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# BACKUP_S3_SECRET_KEY=""
# BACKUP_ENCRYPTION_KEY=""
# The two optional members of the set, both with defaults, so leaving them
# unset does not disable backups.
#
# Region sent with the SigV4 signature. Default "auto", which is what
# Cloudflare R2 expects; AWS S3 and most MinIO deployments want their real
# region name here.
# BACKUP_S3_REGION="auto"
#
# How long backup objects are meant to live, in days. Default 30, minimum 1.
# The app does not expire objects by age: this number is what you set the
# bucket's own lifecycle rule to. It does delete objects in two cases, so the
# credential needs DeleteObject: every copy of an account that is deleted or
# whose data is wiped, and its own connection test's `_healthcheck/<ts>.bin`.
# See docs/ops/backup-restore.md.
# BACKUP_RETENTION_DAYS="30"
#
# Off-host keys no longer written with, comma-separated, kept so older
# objects stay readable during a rotation of BACKUP_ENCRYPTION_KEY. Remove a
# key once the lifecycle rule has retired every object written under it.
# BACKUP_ENCRYPTION_PREVIOUS_KEYS=""
# -----------------------------------------------------------------------------
# Stored backups in the database (optional)
# -----------------------------------------------------------------------------
# The largest weekly or uploaded backup of one account the app keeps, in
# megabytes of encrypted copy. Default 2048. It does not depend on the app's
# memory: a copy is written and read in pieces of about a megabyte. The limit
# only stops a runaway copy from filling the database volume, which holds the
# old and the new copy side by side while a backup runs. An account with 2.6
# million readings stores a copy of about 100 MB.
# BACKUP_MAX_STORED_MB="2048"
# -----------------------------------------------------------------------------
# Audit-trail retention -- optional
# -----------------------------------------------------------------------------
# How long rows in `audit_logs` survive, in days. Default 365. The floor is 7:
# a smaller value is ignored rather than obeyed, so a window entered in seconds
# by mistake cannot empty a fresh table. A daily job does the pruning.
#
# This number is shown to users, not just enforced. Settings -> Shared access
# prints the window under the activity list, and the dialog that ends somebody
# else's access states how long "who entered what" stays answerable. Both take
# the value the server resolved from this variable, so an instance running 90
# says 90 on both surfaces.
# AUDIT_LOG_RETENTION_DAYS="365"
# How long Coach conversations survive, in days. Default 365, floor 30. Like
# the audit window above this number is shown to the user -- the Data &
# Privacy page states it -- so an instance running 90 has to be able to say
# 90 rather than repeat the default.
# COACH_MESSAGE_RETENTION_DAYS="365"
# How long the host CPU/memory samples behind the admin monitoring charts are
# kept, in days. Default 7. Raise it for a longer trend; lower it on a host
# where disk is the scarce resource.
# HOST_METRIC_RETENTION_DAYS="7"
# Thinning of dense intraday samples (heart rate, glucose) once they age out
# of the detail window. On by default. Set "false" to keep every raw sample
# forever -- accurate to the second, at the cost of unbounded table growth.
# DENSE_INTRADAY_RETENTION_ENABLED="false"
# Consecutive failures before an integration is reported as persistently
# failing and notified about. Default 3, minimum 1. Raise it when a flaky
# upstream makes the notification noisy.
# INTEGRATION_FAILURE_ALERT_THRESHOLD="3"
# -----------------------------------------------------------------------------
# Database session timeout -- optional
# -----------------------------------------------------------------------------
# Statement timeout applied to every database session, in milliseconds.
# Default 60000, which bounds a genuinely runaway query while leaving headroom
# for the heaviest legitimate read (the live-aggregate analytics fallback on a
# large account). Set "0" to disable it and restore unbounded behaviour.
# DATABASE_STATEMENT_TIMEOUT_MS="60000"
# -----------------------------------------------------------------------------
# FHIR health-record export -- optional
@@ -268,8 +490,41 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# address and the geo lookup resolves the wrong location. Set this to "1"
# ONLY when Cloudflare is in front -- a direct-exposed self-host must leave
# it unset, or an attacker could forge the header. Off by default.
# Number of trusted reverse-proxy hops in front of the app; the client IP is
# read that many entries from the right of the X-Forwarded-For chain. 0 for a
# directly-exposed host, 1 (the default when unset) behind a single reverse
# proxy; X-Real-IP is read only at 1. A wrong value makes the app refuse the
# headers, log one warning, and collapse anonymous callers into one
# rate-limit bucket.
# TRUST_PROXY_HOPS="1"
# TRUST_CF_CONNECTING_IP="1"
# Memory cap of the app container (read by docker-compose.yml, not by the app).
# Node sizes its heap from it: 1536m (the default) gives 792 MB, 1g only 524 MB,
# which a long-used account fills in normal operation. Lower it on a host with
# 2 GB or less, raise it on a busy instance.
# APP_MEMORY_LIMIT="1536m"
# -----------------------------------------------------------------------------
# Outbound requests HealthLog makes on its own -- optional switches
# -----------------------------------------------------------------------------
# Besides the services you connect yourself (AI provider, integrations,
# notification channels, off-host backups), the server contacts three third
# parties by default. Each has an off-switch that accepts "1", "true" or "yes":
#
# - HaveIBeenPwned, when a password is set (registration, change, admin
# reset). Only the first five hex characters of the password's SHA-1 are
# sent (k-anonymity); the password and its full hash never leave. With the
# switch on, known-breached passwords are no longer refused.
# PASSWORD_BREACH_CHECK_DISABLED="1"
#
# - The GitHub releases API, at most once a day per browser, for the "update
# available" badge on the About page and the admin version tile.
# UPDATE_CHECK_DISABLED="1"
#
# - The online IP geolocation provider for login events; see
# IP_GEO_LOOKUP_DISABLED in the next section.
# -----------------------------------------------------------------------------
# IP geolocation lookup -- optional
# -----------------------------------------------------------------------------
@@ -289,8 +544,9 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# IP_GEO_LOOKUP_URL="http://ip-api.com/json"
# IP_GEO_ALLOW_INSECURE="true"
#
# Set to "1" to disable all third-party IP egress (GDPR Art. 44). With egress
# off the resolver uses only the offline GeoLite2 MMDB tier, if present.
# Set to "1" (or "true" / "yes") to disable all third-party IP egress (GDPR
# Art. 44). With egress off the resolver uses only the offline GeoLite2 MMDB
# tier, if present, and the monthly MaxMind download is skipped too.
# IP_GEO_LOOKUP_DISABLED="1"
# -----------------------------------------------------------------------------
@@ -302,14 +558,27 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# a stock `:latest` the directory is usually empty and every login IP goes
# to the online provider instead.
#
# To resolve locations on your own host: create a free MaxMind account,
# pull both databases with `geoipupdate`, mount the directory into the
# container read-only (the commented `volumes:` block in docker-compose.yml
# shows the line), and point this at the container path. Pair it with
# IP_GEO_LOOKUP_DISABLED="1" above for zero IP egress. Refreshing the files
# on the host is enough -- the reader picks them up on the next container
# restart. See docs/self-hosting/geolite2.md.
# Three ways to get the databases:
#
# 1. RUNTIME FETCH (issue #659) -- set MAXMIND_LICENSE_KEY below and the
# worker downloads both databases into GEOLITE2_DIR itself on the next
# boot and monthly thereafter. No image rebuild, no manual mount. This is
# the way for a stock `:latest` pull.
# 2. Bring your own -- create a free MaxMind account, pull both databases
# with `geoipupdate`, mount the directory into the container read-only
# (the commented `volumes:` block in docker-compose.yml shows the line),
# and point GEOLITE2_DIR at the container path. Refreshing the files on
# the host is enough -- the reader picks them up on the next restart.
# 3. Bake them at build time (build your own image with a licence key).
#
# Pair any of them with IP_GEO_LOOKUP_DISABLED="1" above for zero IP egress.
# See docs/self-hosting/geolite2.md.
# GEOLITE2_DIR="/var/lib/geolite2"
#
# MaxMind licence key for the runtime fetch (option 1 above). Free: sign up at
# https://www.maxmind.com/en/geolite2/signup, then My Account -> Manage
# License Keys. Unset, nothing is fetched and the online provider answers.
# MAXMIND_LICENSE_KEY="your-maxmind-licence-key"
# -----------------------------------------------------------------------------
# Environmental-context module (Open-Meteo) -- optional
@@ -332,3 +601,53 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# off — force-disable the renderer
# on — force-enable (crashes the container if the CPU truly lacks AVX2)
# NATIVE_CANVAS="off"
# -----------------------------------------------------------------------------
# Logging -- optional
# -----------------------------------------------------------------------------
# LOG_LEVEL is one of debug / info / warn / error. Default info: drop to debug
# while chasing a problem, raise to warn on a busy instance. LOG_SAMPLE_RATE
# keeps that fraction of SUCCESSFUL events (default 1.0 = all; 0.1 thins a
# chatty log without losing errors). LOG_SLOW_THRESHOLD_MS is the duration
# above which a request is flagged slow (default 3000). LOG_INCLUDE_STACK set
# to "false" strips stack traces from the emitted events.
# LOG_LEVEL="info"
# LOG_SAMPLE_RATE="1.0"
# LOG_SLOW_THRESHOLD_MS="3000"
# LOG_INCLUDE_STACK="false"
# Optional log shipping to a Loki instance. LOKI_ENDPOINT turns shipping on.
# Either form works: the base URL (http://loki:3100) or the full push URL
# (http://loki:3100/loki/api/v1/push). A Loki on your own network is fine,
# private addresses and internal hostnames included; only link-local,
# cloud-metadata and the unspecified address (0.0.0.0, ::) are refused. The
# username/password pair is only needed when your Loki sits behind basic
# auth. When a push fails (Loki down, wrong path, rejected credentials) the
# app writes one line to stderr naming the Loki origin, the reason and how
# many events were dropped, at most once every five minutes per reason; the
# password never appears in it. Leave all three unset and logs stay on stdout
# for the Docker log driver to rotate.
# LOKI_ENDPOINT=""
# LOKI_USERNAME=""
# LOKI_PASSWORD=""
# -----------------------------------------------------------------------------
# Demo mode -- read-only showcase instance
# -----------------------------------------------------------------------------
# "true" makes the proxy refuse every mutation except login and paints a demo
# banner. This is the switch behind a public try-it-out deployment, not a
# safety belt for a real one -- leave it unset on an instance holding real
# data.
# DEMO_MODE="true"
# -----------------------------------------------------------------------------
# Server-side prefetch -- diagnostics escape hatch
# -----------------------------------------------------------------------------
# The dashboard, insights, coach and checkups pages prefetch their data on the
# server so the first paint arrives filled in. Set "false" to fall back to
# pure client fetching. Reach for it only when a prefetch is misbehaving on
# your host and you want to see whether the client path is healthy.
# DASHBOARD_SSR_PREFETCH="false"
+3
View File
@@ -1,5 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: Ideas and upvotes
url: https://github.com/MBombeck/HealthLog/discussions/categories/ideas?discussions_q=category%3AIdeas+sort%3Atop
about: Suggest an improvement or upvote the ones you want. One idea per discussion; the most-voted ones get looked at first.
- name: Documentation
url: https://docs.healthlog.dev
about: Setup, configuration, and feature documentation. Most usage questions are answered here.
+1 -1
View File
@@ -6,7 +6,7 @@ body:
- type: markdown
attributes:
value: |
Feature ideas welcome. HealthLog is a personal-health PWA — the bar for inclusion is high (privacy-first, offline-capable, self-hostable). Use this template to propose something concrete; for open-ended discussion, prefer a [Discussion](https://github.com/MBombeck/HealthLog/discussions) thread.
Feature ideas welcome. HealthLog is a personal-health PWA, and the bar for inclusion is high (privacy-first, offline-capable, self-hostable). Use this template to propose something concrete. For an idea you'd like others to weigh in on, or a small improvement, start it in [Ideas](https://github.com/MBombeck/HealthLog/discussions/categories/ideas) instead: people can upvote it there, and the most-voted ideas get looked at first (see #1114).
- type: textarea
id: problem
attributes:
+27
View File
@@ -15,8 +15,35 @@ updates:
schedule:
interval: "weekly"
open-pull-requests-limit: 3
groups:
# init, analyze and upload-sarif are one release pinned in three places.
# Bumped separately, a run mixes two versions and analyze refuses the
# config init wrote ("Loaded a configuration file for version 4.37.7, but
# running version 4.37.9"), so none of the single-action pull requests can
# reach green on its own. They travel together.
codeql-action:
patterns:
- "github/codeql-action*"
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 3
# The `docker` ecosystem above reads the Dockerfile only. The bundled
# database lives in `docker-compose.yml`, which GitHub treats as its own
# ecosystem, so without this block a new PostgreSQL minor release never
# reaches us and the pin ages silently.
- package-ecosystem: "docker-compose"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 3
ignore:
# A PostgreSQL major is a migration, not an update: the on-disk format
# changes, so the operator has to run pg_upgrade or dump and restore.
# The first run of this ecosystem proposed 16.15 -> 18.6, which would
# have handed self-hosters a database their data directory cannot be
# read by. Minor releases still arrive as PRs; a major is a deliberate
# project decision with a migration guide behind it.
- dependency-name: "postgres"
update-types: ["version-update:semver-major"]
+6 -4
View File
@@ -3,12 +3,14 @@ name: Coach eval
# B0 (v1.21.3) — the Coach evaluation harness, two layers.
#
# 1. The DETERMINISTIC suite (golden set + red-team battery + the grounding
# grader) runs ALWAYS. It is free, offline, and the per-change floor — the
# grader + the dialog scenarios) runs ALWAYS. It is free, offline, and the per-change floor — the
# same suite `pnpm test` runs, pinned here as a standing nightly check.
# 2. The LIVE JUDGE step runs ONLY when the `COACH_EVAL_API_KEY` repository
# secret is present, and is NON-BLOCKING (`continue-on-error: true`). With
# the secret absent it no-ops with a clear log line — the workflow stays
# green. The operator flips the secret on later; no rebuild needed.
# green. The operator flips the secret on later; no rebuild needed. The
# same step puts the dialog scenarios to the model and logs a pass rate
# per scenario, with the tool calls and their arguments.
#
# Schedule + manual only. This is NOT a required check.
@@ -37,7 +39,7 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
@@ -51,7 +53,7 @@ jobs:
# Layer 1 — the deterministic floor. Free, offline, ALWAYS runs. A
# failure here reds the workflow: a regression in the golden set or the
# red-team battery is a real find.
- name: Deterministic floor (golden set + red team)
- name: Deterministic floor (golden set + red team + dialog scenarios)
run: pnpm exec vitest run src/lib/ai/coach/eval/__tests__/
# Layer 2 — the live judge. Runs ONLY when the secret is present, and is
+80
View File
@@ -0,0 +1,80 @@
name: CodeQL
# Static analysis for the TypeScript tree. This is GitHub's default setup
# expressed as a workflow file rather than enabled from the repository
# settings, so the query suite, the excluded paths and the schedule are
# reviewable in the diff like everything else here.
#
# Runs on every push to `main` as well as on pull requests. Most changes
# reach `main` through a pull request that is analysed on the way in, but
# not all of them: an asset uploaded through the web UI or a maintenance
# commit pushed directly lands without one, and the weekly run would only
# catch it days later. The push run re-analyses a merged tree once more,
# which is the cost of every commit on `main` having an analysis of its own.
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
# Mondays, 04:27 UTC. Off the hour so the run does not queue behind
# everyone else's midnight cron.
- cron: "27 4 * * 1"
workflow_dispatch:
permissions:
contents: read
# A pull request keeps only its newest run: an older head is superseded and
# never merged. A push to `main` is grouped by commit and never cancelled, so
# two merges in quick succession each keep their own analysis instead of the
# second one cancelling (or replacing the queued run of) the first.
concurrency:
group: codeql-${{ github.event_name }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
analyze:
name: Analyse javascript-typescript
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
# Required to write the results into the repository's code-scanning
# alerts. Free for public repositories.
security-events: write
# Required by the CodeQL action to read workflow run metadata.
actions: read
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# `build-mode: none` is the correct mode for JavaScript/TypeScript —
# CodeQL extracts from source and needs neither a compile step nor
# installed dependencies.
#
# The excluded paths are all generated or vendored output. Chief
# among them is `src/generated`, the ~9 MB Prisma client with a
# 224 KB inline schema literal in it: extracting that costs real
# minutes and can produce nothing actionable, because nobody edits
# it and the fix for anything found there is `pnpm prisma generate`.
- name: Initialise CodeQL
uses: github/codeql-action/init@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
languages: javascript-typescript
build-mode: none
config: |
paths-ignore:
- src/generated
- .next
- dist
- coverage
- playwright-report
- test-results
- public
- name: Analyse
uses: github/codeql-action/analyze@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
category: "/language:javascript-typescript"
+26 -3
View File
@@ -2,19 +2,25 @@ name: Auto-merge Dependabot
on: pull_request
# Nothing outside the one job needs more than a checkout, so the default for
# the workflow is read-only and the write scopes sit on the job that spends
# them: `gh pr merge --auto` writes to the repository's merge queue state, and
# both the merge and the review comment write to the pull request.
permissions:
contents: write
pull-requests: write
contents: read
jobs:
auto-merge:
runs-on: ubuntu-latest
if: github.actor == 'dependabot[bot]'
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
@@ -25,6 +31,23 @@ jobs:
- run: pnpm db:generate
# The hero-geometry check in the unit suite renders the real panel in a
# real browser and measures the boxes, and it refuses to skip when CI is
# set — a check that skips measures nothing. This job runs the same suite
# as the quality job in `security.yml` and needs the same browser: without
# it every Dependabot pull request went red on a launch failure that said
# nothing about the bump (four of them on 2026-09-06 alone). Headless
# shell only, matching that job.
- name: Cache Playwright headless shell
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/ms-playwright
key: playwright-shell-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
playwright-shell-${{ runner.os }}-
- run: pnpm exec playwright install --only-shell chromium
- run: pnpm test
# Auto-merge is gated on the Dependabot-declared update type:
+6 -6
View File
@@ -132,7 +132,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
# GHCR rejects repository refs with uppercase letters. `IMAGE_NAME`
# is derived from `github.repository`, which preserves the case of
@@ -150,7 +150,7 @@ jobs:
# Image is built but not pushed in that case.
- name: Log in to GitHub Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@abd2ef45e78c5afb21d64d4ca52ee8550d9572c7 # v4.5.1
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
@@ -258,7 +258,7 @@ jobs:
# arm64 layer never poisons an amd64 build).
- name: Build & push by digest
id: build
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
context: .
file: ./Dockerfile
@@ -341,7 +341,7 @@ jobs:
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
# GHCR requires the repository ref to be lowercase. See the same
# step in the `build` job above for the longer rationale.
@@ -350,7 +350,7 @@ jobs:
echo "IMAGE_REF=${REGISTRY}/${IMAGE_NAME,,}" >> "$GITHUB_ENV"
- name: Log in to GitHub Container Registry
uses: docker/login-action@abd2ef45e78c5afb21d64d4ca52ee8550d9572c7 # v4.5.1
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
@@ -491,7 +491,7 @@ jobs:
echo "Triggering Coolify deploy for ${IMAGE_TAG}@${IMAGE_DIGEST} (source ${BUILD_SHA})."
response="$(curl --silent --show-error --max-time 30 \
--write-out "\n__HTTP_STATUS__:%{http_code}" \
--request GET "$deploy_url" \
--request POST "$deploy_url" \
--header "Authorization: Bearer $COOLIFY_TOKEN")"
status="${response##*__HTTP_STATUS__:}"
body="${response%__HTTP_STATUS__:*}"
+61 -5
View File
@@ -15,9 +15,22 @@ concurrency:
cancel-in-progress: true
jobs:
e2e:
# The suite outgrew the runner the same way the integration suite did: the
# single job passed at ~18 minutes against a 20-minute cap, and the settings
# geometry measurements pushed it over. Same remedy, split rather than raise:
# Playwright shards, each with its own database and production build, and
# a gate job below that carries the exact name branch protection requires.
# Two shards grew to 14–19 minutes against the 20-minute cap once the
# mobile route sweep landed, and a slow runner tipped them over; three
# shards with a 30-minute cap leave room for both.
shard:
runs-on: ubuntu-latest
timeout-minutes: 20
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3]
name: e2e shard ${{ matrix.shard }}/3
services:
postgres:
image: postgres:16-alpine
@@ -47,7 +60,7 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
@@ -87,7 +100,7 @@ jobs:
# chart-runtime boundary (a duplicated ~92 KB gz recharts chunk).
- run: pnpm bundle-check
- run: pnpm exec playwright test
- run: pnpm exec playwright test --shard=${{ matrix.shard }}/3
env:
E2E_BASE_URL: http://localhost:3000
@@ -95,7 +108,50 @@ jobs:
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: playwright-report
name: playwright-report-shard-${{ matrix.shard }}
path: playwright-report/
retention-days: 7
if-no-files-found: ignore
# The machine-readable report, for the skipped-spec check in the gate
# job below. Only uploaded when the shard ran to completion, so a missing
# artifact there means a shard that did not finish, not an empty suite.
- name: Upload Playwright JSON report
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: playwright-json-shard-${{ matrix.shard }}
path: playwright-json/results.json
retention-days: 7
if-no-files-found: error
# Branch protection requires a check named exactly "e2e". This job carries
# that name and answers for both shards: it fails when any shard failed or
# was cancelled, so a half-green matrix cannot satisfy the gate.
e2e:
runs-on: ubuntu-latest
needs: shard
if: always()
timeout-minutes: 5
steps:
- name: Every shard finished green
run: |
if [ "${{ needs.shard.result }}" != "success" ]; then
echo "shard result: ${{ needs.shard.result }}"
exit 1
fi
# A spec file that skipped every one of its tests reports green. The
# check aggregates both shards' reports, because Playwright splits a
# file's tests across shards; see the script's header for the allowlist.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
sparse-checkout: scripts
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: 22
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: playwright-json-shard-*
path: playwright-json
- name: No spec file skipped all of its tests
run: node scripts/check-e2e-skipped-specs.mjs playwright-json/*/results.json
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install pnpm
uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- name: Set up Node
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+41 -13
View File
@@ -10,22 +10,29 @@ permissions:
contents: read
jobs:
integration:
# The suite outgrew a single runner, then a half-suite outgrew a slow one,
# and then a third of it did too. Three shards of about 68 files cleared in
# 13 minutes on an ordinary runner, but a slow runner day ran every test at
# twice its usual duration and the first shard was still working through
# its list when the 25-minute guard cut it off: three of four pushes to main
# between 2026-08-31 and 2026-09-01 failed that way, with green tests logged
# up to the last second. Four shards keep each slice around 50 files, and
# the guard sits at three times the ordinary run rather than under two. A
# wedged test still surfaces through vitest's own 60-second budget, so the
# job timeout only needs to catch a container that never boots. Each shard
# boots its own Postgres testcontainer.
shard:
runs-on: ubuntu-latest
# This guard exists to kill a hung testcontainer or a deadlocked query, not
# to hold the suite to a performance budget. At 15 it had stopped telling
# those apart: the suite itself takes around 13 minutes of job time (128
# files against a real Postgres), so two consecutive runs of the SAME
# commit range came in at 12m50s and then over 15m, and the second was
# killed mid-run with every test to that point green. A cap that a healthy
# run clears only on a fast runner reports runner weather, not health.
# 25 leaves real headroom and still catches a hang inside one CI cycle.
# If the suite ever approaches this number, split it rather than raise it.
timeout-minutes: 25
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
name: integration shard ${{ matrix.shard }}/4
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
@@ -36,7 +43,12 @@ jobs:
- run: pnpm db:generate
- run: pnpm test:integration
# vitest is invoked directly: pnpm passes the `--` separator through to
# the script literally, so `pnpm test:integration -- --shard=…` hands
# vitest a stray positional argument and the shard flag never applies —
# both "shards" then run the full suite. Proven by a paired local run
# before this workflow shipped.
- run: pnpm exec vitest run --config vitest.integration.config.mts --shard=${{ matrix.shard }}/4
env:
# The integration suite boots a Postgres testcontainer and points
# Prisma at it via DATABASE_URL set inside `tests/integration/setup.ts`.
@@ -50,3 +62,19 @@ jobs:
API_TOKEN_HMAC_KEY: "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
ENCRYPTION_KEY: "0000000000000000000000000000000000000000000000000000000000000000"
SESSION_SECRET: "integration-tests"
# Branch protection requires a check named exactly "integration". This job
# carries that name and answers for every shard: it fails when any shard
# failed or was cancelled, so a half-green matrix cannot satisfy the gate.
integration:
runs-on: ubuntu-latest
needs: shard
if: always()
timeout-minutes: 5
steps:
- name: Every shard finished green
run: |
if [ "${{ needs.shard.result }}" != "success" ]; then
echo "shard result: ${{ needs.shard.result }}"
exit 1
fi
+6 -2
View File
@@ -18,7 +18,7 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
@@ -30,7 +30,11 @@ jobs:
- run: pnpm db:generate
# v1.4.42 — exports + types tiers promoted to enforcing. The
# `knip.json` ignore-block carries the shadcn UI surface and the
# `knip.jsonc` ignore-block carries the shadcn UI surface and the
# `src/lib/validations/**` contract types; everything else has
# to clear or get justified there.
#
# This pass cannot see a module whose only importer is its own test —
# vitest is a knip plugin, so test files are entries. The header of
# `knip.jsonc` demonstrates that and names the pass that does see it.
- run: pnpm knip --reporter compact
+1 -1
View File
@@ -71,7 +71,7 @@ jobs:
steps:
- name: Log in to GHCR
uses: docker/login-action@abd2ef45e78c5afb21d64d4ca52ee8550d9572c7 # v4.5.1
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
+60
View File
@@ -0,0 +1,60 @@
name: OpenSSF Scorecard
# Automated checks against the OpenSSF's supply-chain criteria: are Actions
# pinned by SHA, is there a security policy, are dependencies updated
# automatically, is the release pipeline signed, is there a fuzzing or a
# static-analysis story. Most of what it looks for this repository already
# does; the value is that it keeps looking after the person who set it up
# has moved on to something else.
#
# `publish_results: true` sends the result to the OpenSSF's public API,
# which is what makes the score citable by anyone evaluating the project
# without asking for CI access. Nothing about the code or its contents
# leaves; the checks read repository metadata and the workflow files.
on:
# Re-score when a branch-protection rule changes, since several checks
# read exactly that.
branch_protection_rule:
schedule:
# Tuesdays, 07:20 UTC.
- cron: "20 7 * * 2"
workflow_dispatch:
permissions: read-all
jobs:
analysis:
name: Score supply-chain practices
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
# Write the findings into the repository's code-scanning alerts.
security-events: write
# Publish the result to the public API. This is an OIDC token
# exchange, the same mechanism the release workflow uses for keyless
# image signing; no long-lived credential is involved.
id-token: write
contents: read
actions: read
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
# Scorecard reads the repository through the API, not through the
# checkout, and leaving the token in `.git/config` would hand it
# to anything else running in the job.
persist-credentials: false
- name: Run analysis
uses: ossf/scorecard-action@2d1146689b8cda280b9bc96326124645441f03bc # v2.4.4
with:
results_file: scorecard-results.sarif
results_format: sarif
publish_results: true
- name: Upload results
uses: github/codeql-action/upload-sarif@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
sarif_file: scorecard-results.sarif
category: scorecard
+69 -6
View File
@@ -5,6 +5,11 @@ on:
branches: [main]
pull_request:
branches: [main]
schedule:
# Daily, 05:47 UTC. Carries the dependency audit only — every other job
# here answers "is this change safe" and has nothing to say about a tree
# nobody touched. See the note on `dependency-audit`.
- cron: "47 5 * * *"
permissions:
contents: read
@@ -13,11 +18,12 @@ jobs:
quality:
name: Lint, Typecheck & Test
runs-on: ubuntu-latest
if: github.event_name != 'schedule'
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
@@ -28,6 +34,26 @@ jobs:
- run: pnpm db:generate
# The hero-geometry check in the unit suite renders the real panel in a
# real browser and measures the boxes. Without a browser here it caught
# its own launch failure and passed anyway, so from its first day until
# v1.38 it measured nothing on any run of this job. The browser is part
# of the gate now; the test refuses to skip when CI is set.
#
# Headless shell only: `chromium.launch()` resolves to
# chromium_headless_shell, which is what the failing runs named, and the
# full headed build is several times the download for nothing this job
# uses. The e2e job keeps `--with-deps chromium` — it drives a real app.
- name: Cache Playwright headless shell
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/ms-playwright
key: playwright-shell-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: |
playwright-shell-${{ runner.os }}-
- run: pnpm exec playwright install --only-shell chromium
# Blocking since v1.15.20 — the settings-split refactor that kept
# this warn-only is long done and the tree lints clean.
- name: ESLint
@@ -61,14 +87,30 @@ jobs:
fi
echo "::notice::OpenAPI spec in sync with Zod source schemas."
# Not on pull requests. `pnpm audit` answers a question about the published
# advisory database, not about the diff: the same lockfile passes on Monday
# and fails on Tuesday because someone else published, and the branch that
# goes red changed nothing. Seventeen of the forty-one failures this workflow
# produced in thirty days were exactly that, and a gate that fails for
# reasons the author cannot act on is a gate people learn to re-run rather
# than read. It runs on every push to `main` and once a day on the schedule
# above, which is the cadence the question actually has. What ships is still
# gated: `docker-security` scans the built image on every push to `main`, and
# `trivy.yml` scans the lockfile (dev dependencies included) and the
# published image daily.
dependency-audit:
name: Dependency Audit
runs-on: ubuntu-latest
# Runs on pull requests too, but advisory: an advisory published against a
# dependency the branch did not touch must not block the branch. The push
# run on main and the daily schedule stay blocking, and a tag is only ever
# cut from a main whose push run is green.
continue-on-error: ${{ github.event_name == 'pull_request' }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
@@ -89,6 +131,7 @@ jobs:
secret-scan:
name: Secret Scanning
runs-on: ubuntu-latest
if: github.event_name != 'schedule'
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -111,12 +154,32 @@ jobs:
- name: Build Docker image
run: docker build -t healthlog:scan .
# The release binary, pinned, straight from the Trivy release. The apt
# route ran `apt-get update` across every repository on the runner
# image, and an unrelated one (the Chrome repository the runner ships
# with) answering with a corrupt index failed the step twice in a row
# on a release commit. The installer downloads the tarball for this
# exact version and checks it against the published checksums.
#
# The installer itself is fetched from a COMMIT and verified before it
# runs. A tag can be moved to other content, and piping a moving ref
# straight into a shell runs whatever the ref points at that morning
# with the runner's privileges. `TRIVY_INSTALL_COMMIT` is the commit
# `v0.74.0` points at; bump both together, and take the new checksum
# from the file at that commit.
- name: Install Trivy
env:
TRIVY_VERSION: v0.74.0
TRIVY_INSTALL_COMMIT: e1fd17a0ea4a8cf24bc4b4dd7e2cfbf4bb31b994
TRIVY_INSTALL_SHA256: e00df553be558995b994758bc8995956554a16937f456dc6615b0cc411bfec7a
run: |
sudo apt-get install -y wget apt-transport-https gnupg
wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | gpg --dearmor | sudo tee /usr/share/keyrings/trivy.gpg > /dev/null
echo "deb [signed-by=/usr/share/keyrings/trivy.gpg] https://aquasecurity.github.io/trivy-repo/deb generic main" | sudo tee /etc/apt/sources.list.d/trivy.list
sudo apt-get update && sudo apt-get install -y trivy
curl -sfL \
"https://raw.githubusercontent.com/aquasecurity/trivy/${TRIVY_INSTALL_COMMIT}/contrib/install.sh" \
-o trivy-install.sh
echo "${TRIVY_INSTALL_SHA256} trivy-install.sh" | sha256sum -c -
sh trivy-install.sh -b /usr/local/bin "${TRIVY_VERSION}"
rm trivy-install.sh
trivy --version
# Blocking since v1.15.20 — a HIGH/CRITICAL finding in the built
# image fails the job. For a finding without an upstream fix
+73
View File
@@ -0,0 +1,73 @@
# Synthetic post-deploy journey.
#
# `post-publish-verify.yml` proves the published image boots. This one
# proves that on a running instance a person can sign in, write a reading
# and read it back, and that the instance serves the version that was just
# published.
#
# Deliberately manual for now: the maintainer picks the target instance and
# creates the two repository secrets. Nothing calls this from the deploy
# path yet.
#
# Secrets, both required:
# SYNTHETIC_USERNAME — the probe account's username or email
# SYNTHETIC_PASSWORD — its password
#
# The probe account must be password-only (the password flow stops at the
# MFA ticket, which the script reports as a configuration failure), and the
# target must not be the demo instance, where every mutation is blocked.
name: Synthetic journey
on:
workflow_dispatch:
inputs:
# A closed list, not free text. The dispatcher chooses where the probe
# account's password is POSTed, so the choice is between the hosted
# instances and nothing else. The script re-checks the host against its
# own const allowlist and exits 2 on anything else, so a dispatch that
# goes round this form still cannot reach a stranger's collector.
base_url:
description: Instance to walk
required: true
type: choice
default: https://review.healthlog.dev
options:
- https://review.healthlog.dev
- https://healthlog.bombeck.io
expected_version:
description: Version the instance must serve, e.g. v1.38.13
required: true
type: string
permissions:
contents: read
jobs:
journey:
name: Sign in, write a reading, read it back
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: 22
# A check that cannot fail is worse than none. The self-test walks the
# journey against an in-process instance once per leg with that leg
# broken, and fails if any of them still comes back green.
- name: Prove the check can go red
run: node scripts/synthetic-journey.mjs --self-test
# Every input and secret rides an env var — never interpolated into
# the shell command. The script refuses a `BASE_URL` whose host is off
# its allowlist before it sends the password anywhere.
- name: Walk the journey
env:
BASE_URL: ${{ inputs.base_url }}
EXPECTED_VERSION: ${{ inputs.expected_version }}
SYNTHETIC_USERNAME: ${{ secrets.SYNTHETIC_USERNAME }}
SYNTHETIC_PASSWORD: ${{ secrets.SYNTHETIC_PASSWORD }}
run: node scripts/synthetic-journey.mjs
+164
View File
@@ -0,0 +1,164 @@
name: Trivy Scheduled Scan
# Two scans that the per-change gates cannot do, on a daily cadence.
#
# What already exists and is NOT repeated here:
# - `security.yml` → `dependency-audit` runs `pnpm audit --prod` on every
# push to `main` and once a day, blocking on HIGH/CRITICAL.
# - `security.yml` → `docker-security` builds the image on a push to `main`
# and runs `trivy image` against it, blocking on HIGH/CRITICAL.
#
# Both are change-triggered, and both answer "is this change safe". Neither
# answers "is what we shipped last week still safe", because an advisory
# published today lands against an image nobody is about to rebuild. That is
# what the schedule is for. There is deliberately no push or pull_request
# trigger: adding one would run the same scan the `docker-security` job
# already ran, minutes later, on the same tree.
on:
schedule:
# Daily, 05:17 UTC.
- cron: "17 5 * * *"
workflow_dispatch:
permissions:
contents: read
concurrency:
group: trivy-scheduled
cancel-in-progress: true
jobs:
filesystem:
name: Lockfile (including dev dependencies)
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
security-events: write
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# `pnpm audit --prod` is the blocking gate and it is scoped to
# production dependencies on purpose: a dev-only advisory should not
# stop a release. The gap that scoping leaves is that "dev dependency"
# and "not in the image" are not the same statement.
#
# `pdfjs-dist` is the worked example. It sits in `devDependencies`,
# and `src/lib/documents/rasterize-pdf.ts` imports it at runtime, so
# Next's standalone output tracing copies it into the production
# image. `pnpm audit --prod` cannot see it. This scan can: without
# the flag Trivy reads 627 packages out of `pnpm-lock.yaml`, with it
# 1455, and `pdfjs-dist` is only in the second set.
#
# Trivy's own `--help` lists the flag as supported for npm, yarn and
# gradle. It works on `pnpm-lock.yaml` too; the help text is behind
# the parser. Verified against this repository before this workflow
# was written, and worth re-checking if the package count ever
# collapses back to the production figure.
#
# Report-only, and that is a deliberate choice rather than a soft
# one. The findings this widening surfaces are overwhelmingly
# transitive dev-tool advisories with fixes available upstream;
# failing the run on them from day one produces a red badge that gets
# muted within a week, and a muted signal is worse than none. The
# SARIF upload puts every finding in the repository's code-scanning
# alerts, which persist, notify, and can be triaged one at a time.
# The blocking answer to "does this ship" stays where it is, in
# `security.yml`.
- name: Trivy filesystem scan
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
env:
# No action input maps to `--include-dev-deps`; Trivy reads every
# flag from a `TRIVY_`-prefixed environment variable, so this is
# the documented way to reach it through the action.
TRIVY_INCLUDE_DEV_DEPS: "true"
with:
scan-type: fs
scan-ref: .
scanners: vuln
format: sarif
output: trivy-filesystem.sarif
severity: "CRITICAL,HIGH,MEDIUM"
limit-severities-for-sarif: true
exit-code: "0"
# Generated Prisma client. Nobody edits it, the fix for anything
# found in it is `pnpm prisma generate`, and it is ~9 MB.
skip-dirs: src/generated
- name: Upload results
uses: github/codeql-action/upload-sarif@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
sarif_file: trivy-filesystem.sarif
category: trivy-filesystem
published-image:
name: Published image
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
packages: read
security-events: write
steps:
# The `docker-security` job scans an image it just built from the
# current `main`. This one scans the image operators actually pull,
# which is the one built from the last release tag and unchanged
# since. The two answer different questions and the gap between them
# widens every day a release stays out.
#
# Trivy resolves the multi-arch manifest to the runner's platform, so
# this covers `linux/amd64`. The arm64 manifest shares every
# application layer and differs only in native binaries.
- name: Log in to GitHub Container Registry
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# `.trivyignore` lives at the repository root and Trivy reads it
# automatically, so the suppressions the blocking gate already
# carries apply here too and the two scans cannot disagree about
# what is accepted.
- name: Checkout for .trivyignore
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# Fails on CRITICAL only. A critical advisory against the image
# self-hosters are running right now is worth a red badge and a
# notification; HIGH goes to code scanning with everything else,
# because the release pipeline already refuses to publish an image
# carrying one and anything that appears here appeared after the
# fact.
- name: Trivy published-image scan
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
scan-type: image
image-ref: ghcr.io/mbombeck/healthlog:latest
scanners: vuln
format: sarif
output: trivy-published-image.sarif
severity: "CRITICAL,HIGH,MEDIUM"
limit-severities-for-sarif: true
exit-code: "0"
- name: Upload results
uses: github/codeql-action/upload-sarif@2892aa5e19bbd11bc0cff5427e3b750a04d9e3c2 # v4.38.2
with:
sarif_file: trivy-published-image.sarif
category: trivy-published-image
# Separate table pass so the SARIF upload above always runs, even
# when this one fails the job. A scan whose failure suppresses its
# own report is a scan you have to re-run by hand to read.
- name: Fail on a critical finding in the published image
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
scan-type: image
image-ref: ghcr.io/mbombeck/healthlog:latest
scanners: vuln
format: table
severity: "CRITICAL"
exit-code: "1"
+12 -3
View File
@@ -17,8 +17,9 @@
# playwright e2e
/test-results
/playwright-report
/playwright-json
/playwright/.cache
/e2e/setup/storageState.json
/e2e/setup/storageState*.json
# next.js
/.next/
@@ -55,6 +56,9 @@ next-env.d.ts
# the cache-version baseline.
/public/sw-version.js
/public/i18n/
# In-browser OCR engine and language data, copied from node_modules by
# scripts/stage-tesseract-assets.mjs at prebuild/predev.
/public/tesseract/
# v1.4.27 B3 — MaxMind GeoLite2 databases are fetched at build time
# via `scripts/fetch-geolite2.sh`. Too large for git; license key
@@ -87,5 +91,10 @@ next-env.d.ts
.audit-*.mjs
# Isolated development worktrees
/.worktrees/
# Isolated development worktrees. `/.wt-*/` is the convention actually in use;
# each one is a full copy of the tree with its own node_modules, so leaving it
# untracked-but-visible means one `git add -A` commits the repository eleven
# times over. The same two names are excluded from eslint and vitest, for the
# same reason in a different tool.
/.wt-*/
/.worktrees/
+4
View File
@@ -28,6 +28,10 @@ regexes = [
# Coach cadence-suggestion label keys are dotted message keys, not secrets;
# one trips the generic-api-key entropy heuristic.
'''coach\.reminderSuggestion\.cadence''',
# Level-A mood dimension label and anchor keys are dotted message keys, not
# secrets; they sit on fields named `labelKey` / `lowAnchorKey`, and the
# generic-api-key rule reads any `*Key: "<high-entropy string>"` as a token.
'''mood\.dimension\.''',
]
# Specific commit fingerprints from prior false-positive findings (kept for reproducibility).
+18
View File
@@ -21,3 +21,21 @@ CVE-2026-33671
# never reachable at runtime. Re-check when the Node base image ships an npm
# build whose bundled sigstore is >= 4.1.1, then drop this entry.
CVE-2026-48815
# CVE-2026-85393 (node-forge RSA PKCS#1 v1.5 signature forgery, HIGH; GitHub
# advisory GHSA-86w9-cpqp-85rv) — node-forge <= 1.4.0 arrives only through
# @parse/node-apn, which uses it in its certificate-based credential path
# (credentials/certificate/*: p12 / PEM certificate). HealthLog authenticates
# to APNs with a token (.p8 key via APNS_KEY_ID / APNS_TEAM_ID), so that code
# never runs. No fixed release is published (latest is 1.4.0). Remove this
# entry, the matching `auditConfig.ignoreGhsas` entry in pnpm-workspace.yaml,
# and raise the floor once node-forge 1.4.1 is out.
CVE-2026-85393
# braces <= 3.0.3 stack overflow on deeply nested patterns (CVE-2026-93687).
# braces arrives only through micromatch -> fast-glob in development tools
# (@next/eslint-plugin-next, @ts-morph/common, the shadcn CLI); `pnpm why
# braces --prod` is empty and the production image does not contain it, and
# those tools only expand patterns written in this repository. No fixed
# release is published (latest is 3.0.3). Remove this entry once one is.
CVE-2026-93687
+5606 -813
View File
File diff suppressed because it is too large. Load diff
+11 -120
View File
@@ -1,125 +1,16 @@
# CLAUDE.md
# Contributing with AI tooling
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
HealthLog is built with AI assistance, and contributions made the same way are welcome. This file used to carry a copy of the internal conventions document; the copy aged badly and started contradicting the codebase, so it now points at the living sources instead.
## Project
## Where the real conventions live
HealthLog — a personal health-tracking PWA (weight, blood pressure, pulse, mood, medication compliance) with Withings integration, Dracula-themed UI, mobile-first design, offline caching, and doctor report PDF export.
- `CLAUDE.md` at the repo root is the maintainer's operating manual for this codebase: architecture walk, code conventions, security patterns, test commands, the do-not list. It is checked in and kept current; whatever an AI agent (or a human) needs to work on the server is in there.
- `docs/CONTRIBUTING-CLIENTS.md` covers building a client app (Android, iOS, CLI) against the server: the API contract, auth from a client's point of view, sync semantics, and how coordination between repos works.
- `docs/api/openapi.yaml` is the wire contract, generated from the server's Zod schemas. CI fails on drift, so it is always accurate for the commit it sits in.
## Commands
## Ground rules, whatever tooling you use
```bash
# Development
pnpm dev # Start dev server (http://localhost:3000)
pnpm build # Production build
pnpm lint # ESLint
pnpm format # Prettier format
pnpm format:check # Prettier check
pnpm typecheck # TypeScript strict check
# Tests
pnpm test # Run all tests (vitest)
pnpm test:watch # Watch mode
# Database
pnpm db:generate # Generate Prisma client
pnpm db:migrate # Create & apply migration (dev)
pnpm db:migrate:deploy # Apply migrations (production)
pnpm db:push # Push schema without migration (prototyping)
pnpm db:studio # Prisma Studio GUI
# Docker
docker compose up -d # Start app + postgres
docker compose logs -f app # Tail app logs
```
## Architecture
- **Next.js 16** App Router with TypeScript strict. Pages are RSC by default; `"use client"` only for interactivity.
- **Prisma 7** ORM with PostgreSQL (26 models). Uses `PrismaPg` adapter from `@prisma/adapter-pg`. Client singleton at `src/lib/db.ts`. Generated client at `src/generated/prisma/client` (note the `/client` suffix). Prisma config in `prisma.config.ts` (not in schema.prisma).
- **shadcn/ui** components (new-york style) in `src/components/ui/`. Add new ones via `pnpm dlx shadcn@latest add <component>`.
- **Dracula theme** via CSS variables in `globals.css`. Dark mode is default. Use `--dracula-*` tokens for chart colors.
- **TanStack Query** for client-side data fetching. Provider in `src/components/providers.tsx`.
- **Zod v4** (`zod/v4`) for all input validation (API routes and forms).
- **API response envelope**: `{ data, error, meta }` via helpers in `src/lib/api-response.ts`.
- **apiHandler** wraps ALL API route handlers (`src/lib/api-handler.ts`) — error handling, Wide Event logging, x-request-id propagation.
- **Structured Logging** (Wide Events) in `src/lib/logging/` — one JSON event per request/operation via `WideEventBuilder` + `AsyncLocalStorage`. Tail sampling, stdout JSON + optional Loki Push.
- **Vitest** for unit testing. Config in `vitest.config.mts`.
- **pg-boss** (PostgreSQL-native) for job queue: medication reminders, insight caching, weekly data backups.
- **jsPDF** + jspdf-autotable for client-side doctor report PDF generation (`src/lib/doctor-report-pdf.ts`).
- **PWA offline** via service worker caching strategies in `public/sw.js` (cache-first for static, network-first for pages, network-only for API).
- **Proxy route protection** — `src/proxy.ts` checks session cookie, enforces auth on all non-public paths. Next.js 16 uses proxy.ts (not middleware.ts).
## Key Conventions
- Default locale is **English**. All code-level strings in English. UI text via i18n `t()` with German + English translations.
- Timezone: `Europe/Berlin` for display, UTC in database.
- Sensitive data (Withings tokens, API keys, VAPID private keys) encrypted with AES-256-GCM (`src/lib/crypto.ts`) before DB storage.
- Passkeys are primary auth (SimpleWebAuthn v13). Sessions stored server-side in PostgreSQL.
- All API mutations require authentication. External ingest uses Bearer token (hashed with HMAC-SHA256 keyed by `API_TOKEN_HMAC_KEY`).
- Rate limiting (in-memory sliding window) on auth and external-facing endpoints.
## File Layout
- `src/app/` — pages and API routes (App Router)
- `src/components/ui/` — shadcn/ui primitives
- `src/components/layout/` — shell (sidebar-nav, topbar, mobile-nav, bottom-nav)
- `src/components/medications/` — medication form, card, timeline
- `src/components/measurements/` — measurement form, list
- `src/components/mood/` — mood form, mood list
- `src/components/charts/` — Recharts wrappers
- `src/components/settings/` — per-route Settings section components (one per `/settings/[section]`)
- `src/components/admin/` — per-route Admin section components (system-status, integrations, monitoring, users, audit, danger-zone, feedback)
- `src/lib/logging/` — Wide Events structured logging (types, config, event-builder, context, sampler, transports, background)
- `src/lib/api-handler.ts` — apiHandler wrapper, requireAuth(), requireAdmin(), HttpError
- `src/lib/` — server utilities (db, crypto, auth, analytics, export, rate-limit, gravatar)
- `src/lib/export.ts` — CSV/JSON export formatting (measurements, medications, mood)
- `src/lib/doctor-report-pdf.ts` — client-side PDF generation (jsPDF, European medical format)
- `src/lib/withings/` — Withings OAuth client and sync service
- `src/lib/notifications/` — dispatcher, types, senders (telegram, ntfy, web-push)
- `src/lib/jobs/` — pg-boss reminder worker (reminders, insights, data backups)
- `src/lib/analytics/` — trend calculations, compliance, correlations
- `src/lib/i18n/` — i18n context, config, locale detection
- `src/lib/validations/` — Zod schemas shared between API + client
- `src/hooks/` — React hooks (`use-auth`)
- `messages/de.json` + `messages/en.json` — i18n translations
- `prisma/schema.prisma` — database schema (26 models)
- `tests/integration/` — Postgres testcontainers integration suite (rate-limit race, idempotency replay, GDPR cascade delete, session lifecycle); `pnpm test:integration`
- `e2e/` — Playwright + axe-core suite for public smoke checks (version, auth-redirect, login, locale-switch, a11y); `pnpm e2e`
- `prisma.config.ts` — Prisma config (DB URL here, not in schema)
- `public/sw.js` — Service worker for Web Push notifications + offline caching
- `docs/` — long-form audit notes (`docs/audit/`); end-user docs live in the separate site at https://docs.healthlog.dev
- `AGENTS.md` — AI agent instructions (Codex, Cursor, etc.)
- `CHANGELOG.md` — release notes per semver tag
## Important Patterns
- Import Prisma client from `@/generated/prisma/client` (not `@/generated/prisma`)
- Prisma 7 does NOT support `url = env("...")` in schema.prisma — use `prisma.config.ts`
- Next.js 16 uses `proxy.ts` (not `middleware.ts`) — having both causes build error
- SimpleWebAuthn v13 has no `@simplewebauthn/server/script/deps` — define Transport type inline
- `zxcvbn-typescript` uses default export only (no named `zxcvbnAsync`/`zxcvbnOptions`)
- pg-boss v12: `{ PgBoss }` named import, `localConcurrency` instead of `teamSize`, handler receives `Job<T>[]` array
- **i18n**: All UI text uses `useTranslations()` hook with `t("section.key")`. Messages in `messages/en.json` (English, default) + `messages/de.json` (German, user-selectable). Keys missing in the active locale fall back to English; missing from both surfaces the raw key — the `src/lib/__tests__/i18n*.test.ts` suite guards against that. Numbers/dates go through `useFormatters()` — never hand-roll `Intl.*` with a fixed locale.
- **Notifications**: 3 channels (Telegram, ntfy, Web Push). Dispatcher at `src/lib/notifications/dispatcher.ts`. Opt-out model (all events enabled by default)
- **Gravatar**: Server-side SHA-256 hash via `src/lib/gravatar.ts`. URL returned in `/api/auth/me` response as `gravatarUrl` field
- **Sidebar**: Collapsible (localStorage-persisted). Settings mode with section shortcuts. User section at bottom with three-dot dropdown menu
- **Settings vs Admin scope rule (v1.4.16 phase B6 audit)**: `/settings/<slug>` is **per-user** — toggles, credentials, layout, target ranges that affect one account. `/admin/<slug>` is **system-wide** — defaults, feature gating, host metrics, audit log read-access. Two surfaces overlap by design: (a) notification channels — admin can disable a channel system-wide via `/api/settings/global-services`, the user sets their own credentials in `/settings/notifications`; (b) AI providers — admin sets the default Codex/OpenAI key, user can override with their own. **No user-facing toggle should appear in both surfaces.** Keys like `settings.adminAreaTitle` are dead code (planned admin-shortcut tile that never shipped) and stay in JSON marked deprecated until a hygiene PR removes them. See `docs/audit/v1416-settings-audit.md`.
- **ESLint**: Strict `react-hooks/set-state-in-effect` rule — avoid `setState` inside `useEffect`. Use lazy `useState()` initializer for localStorage reads
- **Proxy route protection**: `src/proxy.ts` checks `healthlog_session` cookie; PUBLIC_PATHS array bypasses auth. Security headers (CSP, HSTS, X-Frame-Options) applied to all responses
- **PWA safe area**: Root layout has `viewportFit: "cover"`. Bottom-nav uses `pb-[env(safe-area-inset-bottom)]` for iOS safe area
- **Doctor report PDF**: Client-side via `src/lib/doctor-report-pdf.ts` (jsPDF). Data from `POST /api/doctor-report`. European medical format, German terminology
- **Achievements**: Persistent in `UserAchievement` table. Computed on API call, new unlocks written to DB with stable `unlockedAt` timestamps
- **Data backup**: pg-boss `data-backup` queue runs weekly (Sundays 03:00), stores JSON in `DataBackup` model
- **Wide Events / Structured Logging**: `apiHandler()` wraps all API routes. Use `annotate()` from `@/lib/logging/context` for business-action annotations. Use `requireAuth()` / `requireAdmin()` from `@/lib/api-handler` (auto-annotates auth). Background jobs use `withBackgroundEvent()`. External calls tracked via `getEvent()?.addExternalCall()`. No `console.log` in production code — use event annotations instead. Env vars: `LOG_LEVEL`, `LOG_SAMPLE_RATE`, `LOG_SLOW_THRESHOLD_MS`, `LOG_INCLUDE_STACK`, `LOKI_ENDPOINT`, `LOKI_USERNAME`, `LOKI_PASSWORD`
- **Multi-tenant prep (v1.4)**: `HEALTHLOG_PROCESS_TYPE=web|worker|all` (default `all`) splits HTTP and pg-boss workloads; the proxy refuses HTTP traffic with 503 + `X-HealthLog-Process-Type: worker` in worker mode. `ENCRYPTION_KEYS` is a JSON map of versioned keys (`{"v1": "...", "v2": "..."}`) plus `ENCRYPTION_ACTIVE_KEY_ID` for new writes; rotation via `pnpm tsx scripts/rotate-encryption-key.ts <id>`. `BACKUP_S3_*` env block configures off-host weekly encrypted backups (PutObject + GetObject only — retention is the bucket's lifecycle policy, never the worker).
- **Native API clients (v1.4)**: `POST /api/auth/login` and `/api/auth/passkey/login-verify` issue a 24h access token (`hlk_<64hex>`) AND a refresh token (`hlr_<64hex>`) when `X-Client-Type: native` or the User-Agent starts with `HealthLog-iOS/`. The browser flow is unchanged. Refresh-token reuse-detection revokes every refresh token for the user. The idempotency replay-cache rejects bodies containing `hlk_` OR `hlr_` so cached responses can never echo a token back.
## Headless-Client API Patterns
The iOS app talks to bearer-protected routes while the web PWA uses cookie sessions; both share the same handlers (`requireAuth()` accepts either credential).
- **Bearer-token issuance**: `POST /api/auth/login` and `POST /api/auth/passkey/login-verify` return a `token` field for native clients. `isNativeClientRequest()` (`src/lib/auth/issue-token.ts`) opts in via `X-Client-Type: native` header **or** a `User-Agent` starting with `HealthLog-iOS/`. The raw `hlk_<64-hex>` value is returned exactly once; default lifetime 90 days, permissions `["*"]`.
- **Token storage**: API tokens are stored as **HMAC-SHA-256** hashes (`hashToken()` in `src/lib/auth/hmac.ts`, keyed by env `API_TOKEN_HMAC_KEY`) — not plain SHA-256. The keyed HMAC defends against precomputed rainbow tables if the DB leaks. Same mechanism is reused for external-ingest token verification.
- **Idempotency-Key**: `withIdempotency()` (`src/lib/idempotency.ts`) wraps POST/PUT/PATCH/DELETE handlers so retries with the same `Idempotency-Key` (regex `^[A-Za-z0-9_\-:.]{8,128}$`) for the same `(userId, method, path)` replay the original response with `X-Idempotent-Replay: true` for 24h. **NOT cached**: 401, 403, 408, 429, any 5xx, and any body containing `hlk_` (defence against caching a token-issuing response). Validation 4xx (422 etc.) **is** cached so a broken retry doesn't re-hit the DB. `userIdResolver` defaults to the cookie session — pass a 2nd argument for Bearer-only routes.
- **Device-registration cross-user-hijack guard**: `POST /api/devices` rejects re-registration of an existing APNs token under a different user with **409** (`Device token already registered to another account`) instead of silently transferring ownership. APNs tokens aren't a secret, so trusting wire input would let anyone who learns a token redirect another user's pushes. Audit trail: `device.register.denied` with reason `token_owned_by_other_user`.
- The human who commits a change has read it and stands behind it. The git history knows authors, not tools: no AI attribution trailers, no assistant vocabulary in commit messages, PR text, or release notes.
- No real names of users or reporters in committed text, and no live health figures anywhere, including fixtures and examples. Invent data.
- No secrets in code, fixtures, or docs, and nothing secret-shaped either.
- Run the gates before pushing (`pnpm typecheck`, `pnpm lint`, `pnpm test`) and fix what they find rather than suppressing it. A guard that fails is telling you something; the fix goes in the code, not in the guard.
+1 -1
View File
@@ -121,7 +121,7 @@ Contributors: branch off `main`; PRs target `main`.
## Translations
HealthLog ships with English (`en`) and German (`de`) maintained by the project, plus French (`fr`), Spanish (`es`), Italian (`it`), and Polish (`pl`) that are **AI-initial, community-maintained**. The maintained locales are reviewed line-by-line; the community-maintained ones surface a small banner inviting users to improve them.
HealthLog ships with English (`en`) and German (`de`) maintained by the project, plus French (`fr`), Spanish (`es`), Italian (`it`), Polish (`pl`), and Korean (`ko`) that are **AI-initial, community-maintained**. The maintained locales are reviewed line-by-line; the community-maintained ones surface a small banner inviting users to improve them.
### Improving an existing locale
+147 -24
View File
@@ -48,12 +48,28 @@ ENV NEXT_TELEMETRY_DISABLED=1
# starts fresh and therefore does not inherit this setting.
RUN NODE_OPTIONS=--max-old-space-size=8192 pnpm build
# Record which pdfjs-dist the top-level dependency actually resolves to. pnpm
# links a direct dependency at `node_modules/<name>`, so this reads the exact
# pinned copy rather than guessing. The runner stage hoists that version by
# name; see the note there for why guessing was wrong.
RUN node -p "require('/app/node_modules/pdfjs-dist/package.json').version" \
> /app/.pdfjs-version
# The same for @napi-rs/canvas, whose native binary must match its JS loader.
RUN node -p "require('/app/node_modules/@napi-rs/canvas/package.json').version" \
> /app/.canvas-version
# ── Stage 3: Production runner ─────────────────────────────
FROM node:22-alpine@sha256:16e22a550f3863206a3f701448c45f7912c6896a62de43add43bb9c86130c3e2 AS runner
# `tzdata` is required so Europe/Berlin schedules (pg-boss cron, locale-aware
# timestamp formatting) resolve to the actual offset instead of silently
# falling back to UTC on Alpine images that ship without it.
RUN apk add --no-cache tzdata
#
# `apk upgrade` pulls in OS-package security fixes the pinned base digest
# has not absorbed yet (the digest pin stays for build reproducibility;
# security patches from the Alpine repo override it deliberately —
# CVE-2026-14456 in openssl was the first instance the container scan
# caught between base-image rebuilds).
RUN apk add --no-cache tzdata && apk upgrade --no-cache
WORKDIR /app
ENV NODE_ENV=production
@@ -85,6 +101,17 @@ COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
# Next's standalone output must carry the externalized worker dependencies.
# Prisma's pure-JS adapter stays bundled; only modules loaded through native
# Node resolution belong in this runtime assertion.
#
# `pg` is a direct entry in `dependencies` for this line's sake, and it has to
# stay there. It used to sit in devDependencies and the assertion still passed,
# but only by coincidence: the version our own entry pinned happened to match
# the one @prisma/adapter-pg pulled in, so both names resolved to a single
# copy in the store and the file tracer packed it whole. Bumping the adapter to
# 7.10.0 moved its transitive pg to 8.23.0 while ours stayed at 8.22.0. The
# tracer then packed only the copy the adapter reached, the top-level link
# pointed at the other one, and this line failed with "Cannot find module
# '/app/node_modules/pg/lib/index.js'" on both architectures. Declaring the
# runtime requirement makes the two resolve to the same copy by construction.
RUN node -e "require.resolve('pg-boss'); require.resolve('pg')"
# @napi-rs/canvas (document PDF rasterization): Next's file tracer copies the
@@ -96,53 +123,141 @@ RUN node -e "require.resolve('pg-boss'); require.resolve('pg')"
# @napi-rs/canvas" → "Cannot polyfill DOMMatrix" → rasterize ReferenceError);
# (2) @napi-rs/canvas's own loader then resolves its platform binary. Hoist BOTH
# the canvas package and the musl binary package to /app/node_modules/@napi-rs
# via symlink into the .pnpm store, and also drop the prebuilt .node into the
# canvas dir so the loader's local-file fallback (`require('./skia.<triple>.node')`)
# is belt-and-suspenders. Per-arch buildx installs only the matching musl triple.
# via symlink into the .pnpm store, and drop the prebuilt .node into the canvas
# dir: the loader tries that local file (`require('./skia.<triple>.node')`)
# before the platform package, so it decides which binary runs.
#
# Hoist the version the app pins, by name, exactly like pdfjs-dist below. The
# store holds a second, older canvas that pdf-parse's own pdfjs-dist pulls in,
# and this step used to take whichever `find | head -1` returned first. It
# returned the old binary, which then sat next to the new loader: rendering
# still worked, but `loadImage` called an `Image.decode` the old binary does
# not have, and every preview thumbnail failed with "image.decode is not a
# function". Name the version, and fail the build when the binary that lands
# in the canvas dir is not that version's.
COPY --from=builder /app/.canvas-version /tmp/.canvas-version
RUN set -e; \
CANVAS_DIR="$(find /app/node_modules/.pnpm -maxdepth 4 -type d -path '*@napi-rs+canvas@*/node_modules/@napi-rs/canvas' 2>/dev/null | head -1)"; \
MUSL_DIR="$(find /app/node_modules/.pnpm -maxdepth 4 -type d -path '*@napi-rs+canvas-linux-*-musl@*/node_modules/@napi-rs/canvas-linux-*-musl' 2>/dev/null | head -1)"; \
NODE_BIN="$(find /app/node_modules/.pnpm -maxdepth 5 -name 'skia.linux-*-musl.node' 2>/dev/null | head -1)"; \
if [ -n "$CANVAS_DIR" ]; then \
mkdir -p /app/node_modules/@napi-rs; \
ln -sfn "$CANVAS_DIR" /app/node_modules/@napi-rs/canvas; \
[ -n "$MUSL_DIR" ] && ln -sfn "$MUSL_DIR" "/app/node_modules/@napi-rs/$(basename "$MUSL_DIR")"; \
[ -n "$NODE_BIN" ] && cp "$NODE_BIN" "$CANVAS_DIR/"; \
chown -R nextjs:nodejs /app/node_modules/@napi-rs; \
echo "canvas hoisted for pdfjs: $CANVAS_DIR (musl=$MUSL_DIR)"; \
else echo "WARN: @napi-rs/canvas not found; PDF rasterization will degrade to local text"; fi
CANVAS_VERSION="$(cat /tmp/.canvas-version)"; \
rm -f /tmp/.canvas-version; \
CANVAS_DIR="/app/node_modules/.pnpm/@napi-rs+canvas@${CANVAS_VERSION}/node_modules/@napi-rs/canvas"; \
MUSL_DIR="$(find /app/node_modules/.pnpm -maxdepth 4 -type d -path "*@napi-rs+canvas-linux-*-musl@${CANVAS_VERSION}/node_modules/@napi-rs/canvas-linux-*-musl" 2>/dev/null | head -1)"; \
if [ ! -d "$CANVAS_DIR" ] || [ -z "$MUSL_DIR" ]; then \
echo "ERROR: pinned @napi-rs/canvas@${CANVAS_VERSION} or its musl binary did not reach the traced image."; \
echo "Present instead:"; \
find /app/node_modules/.pnpm -maxdepth 1 -name '@napi-rs+canvas*' 2>/dev/null; \
exit 1; \
fi; \
NODE_BIN="$(find "$MUSL_DIR" -maxdepth 1 -name 'skia.linux-*-musl.node' | head -1)"; \
[ -n "$NODE_BIN" ] || { echo "ERROR: no skia binary in $MUSL_DIR"; exit 1; }; \
mkdir -p /app/node_modules/@napi-rs; \
ln -sfn "$CANVAS_DIR" /app/node_modules/@napi-rs/canvas; \
ln -sfn "$MUSL_DIR" "/app/node_modules/@napi-rs/$(basename "$MUSL_DIR")"; \
cp "$NODE_BIN" "$CANVAS_DIR/"; \
chown -R nextjs:nodejs /app/node_modules/@napi-rs; \
BIN_VERSION="$(node -p "require('$MUSL_DIR/package.json').version")"; \
[ "$BIN_VERSION" = "$CANVAS_VERSION" ] || { echo "ERROR: canvas binary is $BIN_VERSION, loader is $CANVAS_VERSION"; exit 1; }; \
cmp -s "$NODE_BIN" "$CANVAS_DIR/$(basename "$NODE_BIN")" || { echo "ERROR: the canvas dir holds a different binary"; exit 1; }; \
echo "canvas hoisted for pdfjs: $CANVAS_DIR (binary $BIN_VERSION from $MUSL_DIR)"
# pdfjs-dist is `serverExternalPackages` (NOT bundled — the bundled copy's render
# path breaks in the standalone image), so the server does a runtime bare
# `import('pdfjs-dist/legacy/build/pdf.mjs')`. Node resolves that up to
# /app/node_modules, so hoist the real pnpm-store copy to the top level too.
#
# Hoist the version the app pins, by name. More than one pdfjs-dist reaches the
# store — `pdf-parse` carries its own, older copy for the text-extraction path —
# and this step used to take whatever `find | head -1` returned first. That is
# readdir order, so it could hoist the OLDER copy and the version named in
# package.json would never run in the image: the renderer resolving one version
# while every local check exercised another. Name the version and fail the build
# when it is absent, instead of degrading to whichever copy comes back first.
COPY --from=builder /app/.pdfjs-version /tmp/.pdfjs-version
RUN set -e; \
PDFJS_DIR="$(find /app/node_modules/.pnpm -maxdepth 4 -type d -path '*pdfjs-dist@*/node_modules/pdfjs-dist' 2>/dev/null | head -1)"; \
if [ -n "$PDFJS_DIR" ]; then \
ln -sfn "$PDFJS_DIR" /app/node_modules/pdfjs-dist; \
chown -h nextjs:nodejs /app/node_modules/pdfjs-dist; \
echo "pdfjs-dist hoisted: $PDFJS_DIR"; \
else echo "WARN: pdfjs-dist not found; PDF rasterization will degrade to local text"; fi
PDFJS_VERSION="$(cat /tmp/.pdfjs-version)"; \
PDFJS_DIR="/app/node_modules/.pnpm/pdfjs-dist@${PDFJS_VERSION}/node_modules/pdfjs-dist"; \
if [ ! -d "$PDFJS_DIR" ]; then \
echo "ERROR: pinned pdfjs-dist@${PDFJS_VERSION} did not reach the traced image."; \
echo "Present instead:"; \
find /app/node_modules/.pnpm -maxdepth 4 -type d -path '*pdfjs-dist@*/node_modules/pdfjs-dist' 2>/dev/null; \
exit 1; \
fi; \
ln -sfn "$PDFJS_DIR" /app/node_modules/pdfjs-dist; \
chown -h nextjs:nodejs /app/node_modules/pdfjs-dist; \
rm -f /tmp/.pdfjs-version; \
RESOLVED="$(node -p "require('/app/node_modules/pdfjs-dist/package.json').version")"; \
[ "$RESOLVED" = "$PDFJS_VERSION" ] || { echo "ERROR: hoisted pdfjs-dist is $RESOLVED, expected $PDFJS_VERSION"; exit 1; }; \
echo "pdfjs-dist hoisted: $PDFJS_DIR (resolves as $RESOLVED)"
# Copy Prisma for migrations (schema, migration SQL, config, engines)
COPY --from=builder /app/prisma ./prisma
COPY --from=builder /app/prisma.config.ts ./prisma.config.ts
COPY --from=builder /app/src/generated ./src/generated
# Operator maintenance scripts that a runbook tells the operator to run inside
# this container (`docs/ops/password-reset.md`, `docs/ops/intake-repair.md`).
# The standalone output carries none of `scripts/`, so without these lines the
# documented `docker compose exec app node scripts/reset-password.mjs` failed
# with "Cannot find module". Only self-contained scripts belong here: plain
# `node` or the `healthlog-tsx` launcher below, resolving `pg` and
# `@node-rs/argon2` from the traced runtime tree. Scripts that import the
# application graph (`@/…`, the generated Prisma client) run from a source
# checkout instead. `src/__tests__/container-scripts-ship-guard.test.ts` holds
# the runbooks and this list in step. Root-owned on purpose: the app user can
# run them but not rewrite them.
COPY --from=builder /app/scripts/reset-password.mjs ./scripts/reset-password.mjs
COPY --from=builder /app/src/lib/auth/argon2-params.mjs ./src/lib/auth/argon2-params.mjs
COPY --from=builder /app/scripts/repair-intake-anomalies.ts ./scripts/repair-intake-anomalies.ts
# Prove the reset CLI's imports resolve in this tree: with every import found
# it stops at its own usage line; a missing module throws before reaching it.
RUN node scripts/reset-password.mjs 2>&1 | grep -q "reset-password: usage:"
# Install the migration CLI, its config dependency, and a pinned launcher for
# the maintenance scripts already shipped in the standalone tree. The Prisma
# config loads dotenv from /app, so expose the isolated copy there before
# stripping npm/Corepack and their caches from the runtime surface.
#
# This install belongs to npm, not pnpm, so the `overrides` block in
# `pnpm-workspace.yaml` does not reach it: a package pinned there for the app
# tree still arrives here at whatever version Prisma asks for. That is not
# hypothetical. `prisma@7.8.0` resolves `@prisma/config@7.8.0`, which resolves
# `deepmerge-ts@7.1.5`, and the image scan reported CVE-2026-40345 (HIGH,
# stack exhaustion on recursive merges) against `/opt/prisma-cli` on a commit
# whose dependency audit over the app tree was green. Two installs, two
# override mechanisms, one of them set. `overrides` is npm's own mechanism and
# `npm pkg set` writes it into the package.json that `npm init -y` just
# created, before anything resolves.
#
# Measured by rebuilding this exact install both ways: without the field
# `deepmerge-ts@7.1.5` lands, with it `8.0.1` lands and `prisma --version`
# still reports 7.8.0. Keep the range in step with the entry in
# `pnpm-workspace.yaml` — they are one decision applied to two package
# managers, and a fix that lands in only one of them is the defect above.
#
# The same class recurred on 2026-09-02: the image scan reported
# `@hono/node-server@1.19.11` (GHSA-frvp-7c67-39w9, CVE-2026-39406) and
# `valibot@1.2.0` (CVE-2026-59952) under this path, both reached through
# `prisma -> @prisma/dev`, while the app tree carried 1.19.17 and a pin the
# npm install never reads. Rebuilding this install both ways confirms it:
# without the two fields below npm resolves 1.19.11 and 1.2.0, with them it
# resolves 1.19.17 and 1.4.2, and `prisma --version` still reports 7.8.0.
RUN mkdir -p /opt/prisma-cli && \
cd /opt/prisma-cli && \
npm init -y && \
npm install --omit=dev prisma@7.8 @prisma/engines@7.8 tsx@4.23.1 dotenv@17.4.2 && \
npm pkg set 'overrides.deepmerge-ts=^8.0.0' && \
npm pkg set 'overrides.mysql2=^3.22.0' && \
npm pkg set 'overrides.@hono/node-server=^1.19.15' && \
npm pkg set 'overrides.valibot=^1.4.2' && \
npm install --omit=dev prisma@7.10.0 @prisma/engines@7.10.0 tsx@4.23.1 dotenv@17.4.2 && \
ln -sfn /opt/prisma-cli/node_modules/.bin/tsx /usr/local/bin/healthlog-tsx && \
ln -sfn /opt/prisma-cli/node_modules/dotenv /app/node_modules/dotenv && \
ln -sfn /opt/prisma-cli/node_modules/prisma /app/node_modules/prisma && \
rm -rf /usr/local/lib/node_modules/npm /usr/local/lib/node_modules/corepack /root/.cache/node/corepack /root/.npm && \
rm -f /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack /usr/local/bin/pnpm /usr/local/bin/pnpx
# Same proof for the intake-repair script under the launcher it is documented
# with: its `pg` import resolves, so it reaches its own DATABASE_URL check.
RUN env -u DATABASE_URL healthlog-tsx scripts/repair-intake-anomalies.ts 2>&1 | grep -q "DATABASE_URL must be set"
# v1.4.27 B3 — offline GeoLite2 databases for IP→location and IP→ASN
# lookups. The MMDB files live in `/opt/geolite2/` and are read by
# `src/lib/geo.ts` via `mmdb-lib`. They are downloaded outside the
@@ -155,8 +270,16 @@ RUN mkdir -p /opt/prisma-cli && \
#
# Attribution (CC BY-SA 4.0): see `docs/audit/v1427-summary.md` and
# `/about` in the running app.
RUN mkdir -p /opt/geolite2
COPY assets/geolite2/ /opt/geolite2/
#
# v1.37.7 (issue #659) — the directory is owned by the unprivileged `nextjs`
# user so the runtime worker can WRITE it: a self-hoster who sets
# MAXMIND_LICENSE_KEY on the published image has the databases fetched into
# this directory at runtime (src/lib/geo/geolite2-fetch.ts) with no rebuild or
# manual mount. `tar`/`gzip` for the extraction ship in the busybox base. A
# read-only bind mount at this path (the bring-your-own-database route) still
# works — the runtime fetch just fails soft and the mounted files stand.
RUN mkdir -p /opt/geolite2 && chown nextjs:nodejs /opt/geolite2
COPY --chown=nextjs:nodejs assets/geolite2/ /opt/geolite2/
# ISO-8601 build timestamp — /api/version returns it as `builtAt`.
# Declared this late in the stage on purpose: the value differs on
+46 -8
View File
@@ -12,6 +12,7 @@
<a href="LICENSE"><img src="https://img.shields.io/badge/License-PolyForm--Noncommercial--1.0.0-blue.svg" alt="License: PolyForm Noncommercial 1.0.0" /></a>
<a href="https://github.com/MBombeck/HealthLog/releases"><img src="https://img.shields.io/github/v/release/MBombeck/HealthLog?sort=semver&color=success&cacheSeconds=60" alt="Latest release" /></a>
<a href="https://github.com/MBombeck/HealthLog/actions/workflows/integration.yml"><img src="https://img.shields.io/github/actions/workflow/status/MBombeck/HealthLog/integration.yml?branch=main&label=CI" alt="CI status" /></a>
<a href="https://apps.apple.com/app/id6769501341"><img src="https://img.shields.io/badge/iOS-App%20Store-0D96F6?logo=apple&logoColor=white" alt="HealthLog Companion App on the App Store" /></a>
<a href="https://testflight.apple.com/join/bucuTBpa"><img src="https://img.shields.io/badge/iOS-TestFlight-007AFF?logo=apple&logoColor=white" alt="iOS app on TestFlight" /></a>
</p>
@@ -19,14 +20,29 @@
<a href="https://healthlog.dev">Website</a> &middot;
<a href="https://demo.healthlog.dev">Live Demo</a> &middot;
<a href="https://docs.healthlog.dev">Documentation</a> &middot;
<a href="https://apps.apple.com/app/id6769501341">iOS App Store</a> &middot;
<a href="https://testflight.apple.com/join/bucuTBpa">iOS TestFlight</a>
</p>
<img width="2434" height="1247" alt="HealthLog dashboard: health metric tiles with 7-day trends, blood-pressure and weight charts, dark theme" src="docs/assets/dashboard-hero.jpeg" />
<p align="center">
<img src="docs/assets/Insights.png"
alt="Insights"
width="23%">
<img src="docs/assets/resting-pulse.png"
alt="Insights RHR"
width="23%">
<img src="docs/assets/Medications.png"
alt="Medications"
width="23%">
<img src="docs/assets/Coach.png"
alt="Coach Chat"
width="23%">
</p>
## Why HealthLog
HealthLog is a self-hosted health tracking app (PWA + native iOS client) that runs from a single `docker compose up` on a NAS, homelab, or small VPS. It brings weight, blood pressure, pulse, blood glucose, body composition, sleep, mood, menstrual cycle, and medications onto one timeline — synced from the devices you already own — and keeps everything encrypted at rest on hardware you control. No vendor cloud, no subscription, no telemetry.
HealthLog is a self-hosted health tracking app (PWA + native iOS client) that runs from a single `docker compose up` on a NAS, homelab, or small VPS. It brings weight, blood pressure, pulse, blood glucose, body composition, sleep, mood, menstrual cycle, and medications onto one timeline, synced from the devices you already own, and keeps it in a Postgres database on hardware you control. No vendor cloud, no subscription, no usage telemetry. The few requests the server makes on its own (an update check, a password breach check, an IP geolocation lookup for logins) can each be switched off.
HealthLog is a personal health record-keeping and wellness tool. It is not a medical device and does not diagnose, treat, cure, or prevent any disease — it helps you log, visualise, and export your own data, and leaves clinical judgement to a clinician.
@@ -36,15 +52,15 @@ Try the [live demo](https://demo.healthlog.dev) to see a working install — sig
- **Every vital on one timeline.** Weight, blood pressure, pulse, glucose, body composition, sleep, SpO₂, respiratory rate, mood, and cycle tracking — charted with trends, moving averages, and clinical reference ranges (ESH 2023, ADA 2024), overridable with the targets your clinician set.
- **Clinical signals, opt-in and additive.** Validated self-checks for mental wellbeing and sleep (WHO-5, PHQ-9, GAD-7, Sleep Condition Indicator — official questionnaire wording, calm crisis-resource handling), grip strength, a 0–10 pain score, waist and body measurements, and a longevity lab panel — each added through one signal registry, so a new signal wires into charts, correlations, the coach, the FHIR map, and the API at once.
- **Records, structured.** Allergies and family history as encrypted structured records that flow into the doctor report, plus lab values you key in or scan from a printed report — OCR extracts the stated values, units, and dates for you to review and confirm before anything is saved. HealthLog transcribes what a report says; it never interprets or diagnoses from it. (Immunization records are deliberately out of scope.)
- **Records, structured.** Allergies and family history as structured records that flow into the doctor report (reactions and notes are encrypted, the substance and condition names are not), plus lab values you key in or scan from a printed report — OCR extracts the stated values, units, and dates for you to review and confirm before anything is saved. HealthLog transcribes what a report says; it never interprets or diagnoses from it. A vaccination record keeps a lifetime immunization log, doses grouped under the disease they protect against, and prints in the doctor report.
- **A document vault for the paper trail.** An opt-in module stores every letter, report, and scan encrypted at rest — PDFs and photos preview inline, Office and text files stay download-only, and nothing user-uploaded can ever execute in the app. One searchable timeline with type, condition, and year filters, drag-and-drop and paste-to-upload, bulk filing, undo-able delete with a 30-day grace, and per-file/per-account limits the operator tunes.
- **Context that explains the numbers.** An opt-in environmental module folds weather, daylight, and temperature in as influence signals (winter darkness against mood, heat against blood pressure) using a home location you set, so a pattern has somewhere to point.
- **Your devices, one server.** Withings, WHOOP, Oura and Polar sync over OAuth2, Google Health connects Fitbit and Pixel Watch through your own Google Cloud client, Nightscout streams CGM glucose, an Apple Health `export.zip` folds your full history in, and the native iOS app streams HealthKit live. A per-metric source priority decides which reading is canonical when wearables overlap.
- **Medication tracking that tells the truth.** Flexible schedules (weekly injections, weekday-only, intervals, PRN, cyclic), a configurable intake window per dose, and a traceable dose history where every slot reads taken, late, skipped, or missed — the same ledger the compliance rate is computed from, so the percentage can never disagree with the timeline.
- **AI insights you own.** Daily briefing, health scores, correlations, and a conversational coach grounded in your own measurements and interpreted against cited guideline reference bands — where a value sits and what that means in plain words, never a diagnosis. The coach proposes concrete if-then plans you accept or decline, and suppresses proactive check-ins when there's nothing genuine to say. Bring your own OpenAI or Anthropic key, or point at a local endpoint (Ollama, LM Studio, vLLM) so nothing leaves your network.
- **Clinician-ready output.** A doctor-report PDF generated client-side, a read-only HL7 FHIR R4 API, and scoped, time-limited share links you revoke after the visit.
- **Private by construction.** AES-256-GCM encryption at rest with zero-downtime key rotation, passkey login, server-side sessions, strict CSP — and no third-party tracking anywhere.
- **Built to be lived in.** Installable PWA with offline support, medication reminders over APNs, Telegram, ntfy, and Web Push, a sub-second dashboard on years of imported history — in English, German, Spanish, French, Italian, and Polish end to end.
- **AI insights you own.** Daily briefing, health scores, correlations, and a conversational coach grounded in your own measurements and interpreted against cited guideline reference bands — where a value sits and what that means in plain words, never a diagnosis. The coach proposes concrete if-then plans you accept or decline, and suppresses proactive check-ins when there's nothing genuine to say. Bring your own OpenAI or Anthropic key, or point at a local endpoint (Ollama, LM Studio, vLLM) so AI requests stay on your network.
- **Clinician-ready output.** A doctor-report PDF rendered on your server, a read-only HL7 FHIR R4 API, and scoped, time-limited share links you revoke after the visit.
- **Private by construction.** AES-256-GCM encryption at rest for notes and other free text, documents, questionnaire answers, AI-written text and credentials, with zero-downtime key rotation. Measurement values, lab values, medication names and mood scores are stored unencrypted in the database, so the database volume and its backups need the same protection as the host. Passkey login, server-side sessions, strict CSP, and no third-party tracking anywhere.
- **Built to be lived in.** Installable PWA with offline support, medication reminders over APNs, Telegram, ntfy, and Web Push, a sub-second dashboard on years of imported history — in English, German, Spanish, French, Italian, Polish, and Korean end to end.
The full feature tour, integration guides, and API reference live at [docs.healthlog.dev](https://docs.healthlog.dev).
@@ -81,13 +97,15 @@ NAS and homelab users have ready-made paths: [Unraid Community Applications](doc
## Self-hosting
One container hosts both the web server and the job worker by default; split them via `HEALTHLOG_PROCESS_TYPE=web|worker` for horizontal scale. Encrypted daily backups to any S3-compatible bucket are opt-in via the admin panel, new users join by invite link or QR code, and the stack works out of the box behind Caddy, Traefik, Nginx, or [Coolify](https://coolify.io/).
One container hosts both the web server and the job worker by default; split them via `HEALTHLOG_PROCESS_TYPE=web|worker` for horizontal scale. Encrypted nightly backups to any S3-compatible bucket are opt-in through five `BACKUP_*` environment variables (the admin panel shows their status), new users join by invite link or QR code, and the stack works out of the box behind Caddy, Traefik, Nginx, or [Coolify](https://coolify.io/).
HealthLog ships releases roughly weekly. Pin a tag, back up before upgrades, and skim the [CHANGELOG](CHANGELOG.md) before pulling `latest`. The operator manual — reverse proxy, migrations, encryption-key rotation, backup and restore — lives at [docs.healthlog.dev](https://docs.healthlog.dev).
## Native iOS app
A SwiftUI companion in public beta via [TestFlight](https://testflight.apple.com/join/bucuTBpa), built on the same API as the web client: live HealthKit two-way sync, medication reminders with action buttons that work without opening the app, and an on-device coach on Apple-Intelligence-capable iPhones. Code lives in [MBombeck/healthlog-iOS](https://github.com/MBombeck/healthlog-iOS).
A SwiftUI companion on the [App Store](https://apps.apple.com/app/id6769501341), built on the same API as the web client: live HealthKit two-way sync, medication reminders with action buttons that work without opening the app, and an on-device coach on Apple-Intelligence-capable iPhones. Code lives in [MBombeck/healthlog-iOS](https://github.com/MBombeck/healthlog-iOS).
The App Store listing carries a small price, which exists to cover Apple's yearly developer fee rather than to earn anything; write to marc@healthlog.dev for a free code if that price is in your way. [TestFlight](https://testflight.apple.com/join/bucuTBpa) stays free and carries the newest builds, and the source builds on your own machine.
## Tech stack
@@ -107,6 +125,25 @@ Next.js 16 (App Router, React Server Components), TypeScript strict, PostgreSQL
Actively developed — new releases roughly weekly, issue reports and PRs welcome. Behaviour and schema can change between versions; migrations are forward-only.
## Thanks
HealthLog started as something I built for myself. That it has turned into a project other people use, care about and help shape still surprises me, and I am grateful for every part of it.
Thank you to everyone who sent code that shipped: [@TimonBed](https://github.com/TimonBed), [@Antiheld86](https://github.com/Antiheld86), [@BernhardBuckel](https://github.com/BernhardBuckel), [@balajiv113](https://github.com/balajiv113), [@aucun6352](https://github.com/aucun6352), [@mathewcsims](https://github.com/mathewcsims) and [@muhdusama](https://github.com/muhdusama).
Thank you to everyone who opened an issue, asked a question in the discussions or wrote me an email, and especially to [@lutzkind](https://github.com/lutzkind), [@HercoGC](https://github.com/HercoGC), [@mills1975](https://github.com/mills1975), [@sreeramachandramurthy](https://github.com/sreeramachandramurthy), [@CritLoren](https://github.com/CritLoren), [@mbreitkreuz](https://github.com/mbreitkreuz), [@k-nacion](https://github.com/k-nacion), [@NebuPookins](https://github.com/NebuPookins), [@Nazza01](https://github.com/Nazza01), [@Cnote43](https://github.com/Cnote43) and [@juliaanvaneijndt](https://github.com/juliaanvaneijndt), whose reports shaped HealthLog again and again. Most of what got better in the last months started with someone describing what went wrong for them, often with a log, a screenshot and a second try when the first fix was not enough.
And thank you to everyone who supported the project with a coffee or by buying the iPhone app. I don't name anyone here, but I read every message that comes with it. It pays for the servers and the Apple developer account, and it tells me that HealthLog is worth the evenings.
<a href="https://github.com/MBombeck/HealthLog/graphs/contributors">
<img src="https://contrib.rocks/image?repo=MBombeck/HealthLog" alt="Contributors to HealthLog" />
</a>
Every merged pull request keeps its author's name on the commit, so the
[contributor graph](https://github.com/MBombeck/HealthLog/graphs/contributors)
is the full list. Release notes name the people whose work is in that release,
including anyone who found the defect without sending the fix.
## License
HealthLog is licensed under the [PolyForm Noncommercial License 1.0.0](LICENSE): free to use, self-host, and modify for noncommercial purposes. Commercial use requires a separate agreement — open an issue or reach out via [healthlog.dev](https://healthlog.dev). Releases up to and including v1.15.18 were published under AGPL-3.0 and remain available under that license.
@@ -117,6 +154,7 @@ HealthLog is licensed under the [PolyForm Noncommercial License 1.0.0](LICENSE):
<a href="https://healthlog.dev">healthlog.dev</a> &middot;
<a href="https://demo.healthlog.dev">Live Demo</a> &middot;
<a href="https://docs.healthlog.dev">Docs</a> &middot;
<a href="https://apps.apple.com/app/id6769501341">iOS App Store</a> &middot;
<a href="https://testflight.apple.com/join/bucuTBpa">iOS TestFlight</a> &middot;
<a href="https://buymeacoffee.com/mbombeck">Buy Me a Coffee</a>
</p>
+1 -1
View File
@@ -64,7 +64,7 @@ For more details, see the [security documentation](https://docs.healthlog.dev/se
HealthLog Docker images are built and published from this repository's CI:
- **Source**: [`.github/workflows/docker-publish.yml`](.github/workflows/docker-publish.yml) — runs on every push to `main` and every `v*` tag
- **Source**: [`.github/workflows/docker-publish.yml`](.github/workflows/docker-publish.yml) — publishes on every `v*` tag; pull requests build the image without publishing it
- **Registry**: [`ghcr.io/mbombeck/healthlog`](https://github.com/MBombeck/HealthLog/pkgs/container/healthlog)
- **Architectures**: `linux/amd64` and `linux/arm64`
- **Provenance attestation**: each image carries a [SLSA build provenance](https://slsa.dev/spec/v1.0/provenance) statement linking it back to the GitHub Actions run, the commit SHA, and the workflow definition
+8 -7
View File
@@ -1,11 +1,12 @@
{
"$comment": "Client-bundle budgets, enforced by scripts/check-bundle-budget.mjs (--check) after `next build` in CI. Values are KB gzip and include every emitted lazy route and locale chunk, while route budgets include the shared rootMainFiles baseline. Re-measured at v1.35.0: / 431, /insights 421, /measurements 417, /insights/mood 439, total 3286, baseline 130, lazy catalogs 804. Every per-route ceiling is unchanged and every measured route is within a kilobyte of its v1.34.1 value, so nothing a person actually downloads grew. The 48 KB aggregate rise from 3238 is the score-configuration settings route, which is a new mutually exclusive chunk the whole-build sum counts independently, plus about 12 KB of its strings across the six locale catalogs. No catalog is statically route-referenced and Recharts remains exactly one fingerprinted chunk. The aggregate cap therefore moves from 3260 to 3310 (24 KB headroom, matching the previous margin); per-route ceilings, the static-catalog guard and the one-Recharts-chunk guard remain unchanged.",
"routesKbGz": {
"/page": 460,
"/insights/page": 445,
"/measurements/page": 445,
"/insights/mood/page": 460
"$comment": "Client-bundle budgets, enforced by scripts/check-bundle-budget.mjs (--check) after `next build` in CI. Values are KB gzip and include every emitted lazy route and locale chunk, while route budgets include the shared rootMainFiles baseline. Re-measured at v1.37.2: / 455, /insights 443, /measurements 441, /insights/mood 453, total 3328, baseline 130, lazy catalogs 849. Every per-route ceiling is unchanged. The /insights overview crept a kilobyte over its 445 ceiling when the ECG teaser began importing its overview cap from the classification module, dragging that module's label map and helpers into the eager page; the cap now lives in its own value-only module, and the Health Score's single provenance entry is split out of the full metric-provenance map, so the overview imports the bare number and citation it renders rather than every metric's label map behind them. Both are back under 445 with room to spare. The 42 KB aggregate rise from 3286 (v1.35.0) is all locale-catalog strings: v1.36 and v1.37 added the encounter, mood-context, mood-prognosis, practitioner, workout-batch and account-sharing surfaces, and their copy lands across the six locale catalogs the whole-build sum counts independently (804 to 849 KB). The non-catalog client chunks are flat against v1.35.0, so nothing a person downloads on a given route grew beyond its own ceiling. The aggregate cap therefore moves from 3310 to 3352 (24 KB headroom, matching the previous margin); per-route ceilings, the static-catalog guard and the one-Recharts-chunk guard remain unchanged. v1.37.4's honest-error-state charge then added recoverable read-failure handling to thirteen surfaces (the shared QueryErrorCard and QueryErrorRow primitives plus an isError branch per surface) and rewrote the MCP scope note and the managed-record error copy across the six locales; the measured total rose to 3404 while every per-route ceiling stayed met (/page 457, /insights 445, /measurements 443, /insights/mood 455). The aggregate cap moves from 3352 to 3428, keeping the same margin; nothing a person downloads on a given route grew beyond its ceiling. v1.37.15's async-truth charge then added the refresh settling state with its two-locale-key copy, the index-outcome plain-words line (seven keys across the six catalogs) and the reindex-count wiring; the measured total rose to 3429 while every per-route ceiling stayed met (/page 456, /insights 445, /measurements 442, /insights/mood 455). The aggregate cap moves from 3428 to 3452, keeping the same margin; nothing a person downloads on a given route grew beyond its ceiling. v1.37.27 found /insights sitting a few hundred bytes under 445 on main and a few hundred over it on the release branch — the page had been at its ceiling for three releases and the release only had to breathe on it. The weight it was carrying was not its own: the authenticated shell imported one destination predicate from the `@/lib/record-settings` barrel, and the barrel also re-exports the managed settings-patch schemas, so Zod, the module registry and three validation modules rode into the eager bundle of every authenticated route for a function that reads a URL slug. The shell imports the `classification` leaf now. Measured across all 585 client-rendered routes: none grew by a byte, 100 fell, by 4.7 KB at the median and 8.1 KB at the most; /insights 444 to 437, /measurements 442 to 435, / 456 to 450, /insights/mood 455 to 450. The whole-build sum moved the other way, 3451 to 3476, and that direction is the metric rather than the change: the aggregate counts each emitted chunk once, so a graph that leaves the chunk group every route shares gets counted again wherever it lands — here inside the deferred settings chunks that actually use it. Bytes on disk rose 25 KB; bytes a reader downloads only ever fell. The aggregate cap moves from 3452 to 3500, the same 24 KB headroom as the four re-measurements before it. Per-route ceilings keep their old values rather than tightening to the new floor: the CI runner measures each route about 1.5 KB heavier than a local arm64 build does, and a ceiling set from a local number would fail on a build that had not regressed. The static-catalog guard and the one-Recharts-chunk guard remain unchanged. Raised to 3700 at v1.37.32 for the seventh interface language (Korean): the lazy message catalogs went 6->7 chunks (1026 KB gz measured), pushing the aggregate to 3631 against the old 3500. The raise is entirely the new catalog; no route budget moved, and the four eager route ceilings are unchanged and still passing. Most of the aggregate is the dynamic locale-switch and fallback path that a first paint never loads (see issue #253), so this ceiling guards bytes almost no visitor requests; 3700 leaves ~69 KB for ordinary drift until that double-count is cleaned up. v1.38.14 re-measures the four eager routes and changes what the number means. The ceilings had been re-stated but never re-based since v1.37.4, so /inLine truncated
"routeBaselineKbGz": {
"/page": 429,
"/insights/page": 368,
"/measurements/page": 411,
"/insights/mood/page": 379
},
"totalClientKbGz": 3310,
"routeDriftAllowanceKbGz": 20,
"totalClientKbGz": 4155,
"maxRechartsChunks": 1
}
+216 -15
View File
@@ -64,7 +64,23 @@ x-healthlog-env: &healthlog_env
# docker-compose reads .env for `${VAR}` substitution at compose-up time).
SESSION_COOKIE_SECURE: "${SESSION_COOKIE_SECURE:-}"
NATIVE_CANVAS: "${NATIVE_CANVAS:-}"
# Read-only showcase instance. DEMO_MODE=true makes the proxy refuse every
# mutation except login and paints the demo banner. Leave it unset on a
# real self-host — it is a public-demo switch, not a safety belt.
DEMO_MODE: "${DEMO_MODE:-}"
# Statement timeout applied to every database session, in milliseconds
# (default 60000; 0 disables it and restores the unbounded behaviour).
# Raise it if a very large account's analytics fallback is being cut off.
DATABASE_STATEMENT_TIMEOUT_MS: "${DATABASE_STATEMENT_TIMEOUT_MS:-}"
WITHINGS_WEBHOOK_SECRET: "${WITHINGS_WEBHOOK_SECRET:-}"
# Overrides the derived `${NEXT_PUBLIC_APP_URL}/api/withings/callback`;
# set it when the URL registered with Withings differs from the app's own
# public URL. The WHOOP / Polar / Oura / Strava equivalents are below.
WITHINGS_REDIRECT_URI: "${WITHINGS_REDIRECT_URI:-}"
# Path-segment + HMAC secret for the Telegram bot webhook. Set it to the
# same value you register with BotFather; without it the settings page
# cannot install the webhook and inbound updates are refused.
TELEGRAM_WEBHOOK_SECRET: "${TELEGRAM_WEBHOOK_SECRET:-}"
# v1.18.11 (W3) — client-IP resolution + geo lookup. Behind Cloudflare
# the real visitor IP is in `cf-connecting-ip`; set
# TRUST_CF_CONNECTING_IP=1 ONLY when Cloudflare is in front (off by
@@ -75,10 +91,25 @@ x-healthlog-env: &healthlog_env
# free ip-api.com endpoint) — off by default, an explicit operator choice.
# Listed here so operator values in .env reach the container (the
# `environment:` block is a whitelist — vars not listed never propagate).
# TRUST_PROXY_HOPS is the number of trusted reverse-proxy hops in front of
# the app: the client IP is read that many entries from the right of the
# X-Forwarded-For chain. Wrong value and the app refuses to read XFF and
# collapses every anonymous caller into one rate-limit bucket. Listed here
# so an operator value in .env reaches the container (the `environment:`
# block is a whitelist).
TRUST_PROXY_HOPS: "${TRUST_PROXY_HOPS:-}"
TRUST_CF_CONNECTING_IP: "${TRUST_CF_CONNECTING_IP:-}"
IP_GEO_LOOKUP_URL: "${IP_GEO_LOOKUP_URL:-}"
IP_GEO_LOOKUP_DISABLED: "${IP_GEO_LOOKUP_DISABLED:-}"
IP_GEO_ALLOW_INSECURE: "${IP_GEO_ALLOW_INSECURE:-}"
# Outbound requests an operator can turn off (1 / true / yes). Both are on
# by default. PASSWORD_BREACH_CHECK_DISABLED stops the HaveIBeenPwned range
# query made when a password is set (only the first five characters of the
# password's SHA-1 are sent). UPDATE_CHECK_DISABLED stops the daily request
# to the GitHub releases API behind the About page and the admin version
# tile. Listed here so an operator value in .env reaches the container.
PASSWORD_BREACH_CHECK_DISABLED: "${PASSWORD_BREACH_CHECK_DISABLED:-}"
UPDATE_CHECK_DISABLED: "${UPDATE_CHECK_DISABLED:-}"
# Directory the offline GeoLite2 databases are read from. Default
# `/opt/geolite2` — the path the published image bakes its own copy
# into, if the build had a MaxMind licence key. Point this at a
@@ -88,16 +119,64 @@ x-healthlog-env: &healthlog_env
# value in .env reaches the container (the `environment:` block is a
# whitelist). See docs/self-hosting/geolite2.md.
GEOLITE2_DIR: "${GEOLITE2_DIR:-/opt/geolite2}"
# MaxMind licence key for the RUNTIME GeoLite2 fetch (issue #659). Set this
# and the worker downloads GeoLite2-City + GeoLite2-ASN itself into
# GEOLITE2_DIR on the next boot and monthly thereafter — no image rebuild,
# no manual mount. Get a free key at
# https://www.maxmind.com/en/geolite2/signup (My Account -> Manage License
# Keys). Leave it unset and nothing is fetched (mounting your own databases
# or IP_GEO_LOOKUP_DISABLED=1 both still work). Listed here so an operator
# value in .env reaches the container (the `environment:` block is a
# whitelist). See docs/self-hosting/geolite2.md.
MAXMIND_LICENSE_KEY: "${MAXMIND_LICENSE_KEY:-}"
# all = bundle web + worker in this container (default, single-host)
# web = serve HTTP only; pair with a separate app-worker service
HEALTHLOG_PROCESS_TYPE: "${HEALTHLOG_PROCESS_TYPE:-all}"
# compose | truenas | coolify | unraid | portainer. Only chooses which
# instructions the admin's "Back up your encryption key" step shows first.
HEALTHLOG_PLATFORM: "${HEALTHLOG_PLATFORM:-}"
# enforce (default) | warn. The start-up encryption key check refuses to
# serve when the key does not open the stored data; warn only logs it and
# serves anyway. A last resort for a refusal you are certain is false: it
# disables a safety check. See docs/self-hosting/getting-started.md.
ENCRYPTION_KEY_CHECK: "${ENCRYPTION_KEY_CHECK:-}"
BACKUP_ENCRYPTION_KEY: "${BACKUP_ENCRYPTION_KEY:-}"
BACKUP_ENCRYPTION_PREVIOUS_KEYS: "${BACKUP_ENCRYPTION_PREVIOUS_KEYS:-}"
BACKUP_S3_ENDPOINT: "${BACKUP_S3_ENDPOINT:-}"
BACKUP_S3_BUCKET: "${BACKUP_S3_BUCKET:-}"
BACKUP_S3_ACCESS_KEY: "${BACKUP_S3_ACCESS_KEY:-}"
BACKUP_S3_SECRET_KEY: "${BACKUP_S3_SECRET_KEY:-}"
BACKUP_S3_REGION: "${BACKUP_S3_REGION:-auto}"
BACKUP_RETENTION_DAYS: "${BACKUP_RETENTION_DAYS:-30}"
# Largest stored backup of one account, in MB of encrypted copy (default
# 2048). A storage limit, not a memory one; see .env.production.example.
BACKUP_MAX_STORED_MB: "${BACKUP_MAX_STORED_MB:-}"
# How long the audit trail is kept, in days. Default 365, floor 7 (a value
# below the floor is ignored rather than obeyed, so a window set in seconds
# by mistake cannot empty a fresh table). It is not only a retention knob:
# the shared-access panel PUBLISHES this number — "who entered what stays
# answerable for N days" is on the dialog that ends somebody's access, and
# the activity view states the same window. An instance running 90 says 90,
# so the var has to actually reach the container. Listed here for the reason
# the block exists: `environment:` is a whitelist, and a value in .env that
# is not named here never arrives.
AUDIT_LOG_RETENTION_DAYS: "${AUDIT_LOG_RETENTION_DAYS:-}"
# How long Coach conversations are kept, in days (default 365, floor 30).
# Like the audit window this number is PUBLISHED to the user on the Data &
# Privacy page, so an instance running 90 has to be able to say 90.
COACH_MESSAGE_RETENTION_DAYS: "${COACH_MESSAGE_RETENTION_DAYS:-}"
# How long the host CPU/memory samples behind the admin charts are kept,
# in days (default 7). Raise it for a longer trend, lower it on a small
# disk.
HOST_METRIC_RETENTION_DAYS: "${HOST_METRIC_RETENTION_DAYS:-}"
# Thinning of dense intraday samples (heart rate, glucose) once they age
# out of the detail window. On by default; set "false" to keep every raw
# sample forever, at the cost of table growth.
DENSE_INTRADAY_RETENTION_ENABLED: "${DENSE_INTRADAY_RETENTION_ENABLED:-}"
# Consecutive failures before an integration is reported as persistently
# failing and notified about (default 3, minimum 1). Raise it if a flaky
# upstream is noisy.
INTEGRATION_FAILURE_ALERT_THRESHOLD: "${INTEGRATION_FAILURE_ALERT_THRESHOLD:-}"
# Per-export ceiling on MedicationAdministration rows in the FHIR
# health-record Bundle. Bounded 1..50000, default 5000. Listed here so
# an operator override in .env actually reaches the container (the
@@ -134,6 +213,37 @@ x-healthlog-env: &healthlog_env
STRAVA_CLIENT_ID: "${STRAVA_CLIENT_ID:-}"
STRAVA_CLIENT_SECRET: "${STRAVA_CLIENT_SECRET:-}"
STRAVA_REDIRECT_URI: "${STRAVA_REDIRECT_URI:-}"
# Fitbit + Google Health are per-user BYO-key integrations, so there is no
# client id/secret env for either. These override the derived
# `${NEXT_PUBLIC_APP_URL}/api/{fitbit,google-health}/callback` when the URL
# registered with the provider differs from the app's public URL. Both are
# asserted same-origin with NEXT_PUBLIC_APP_URL, so they cannot redirect
# the authorization code somewhere else.
FITBIT_REDIRECT_URI: "${FITBIT_REDIRECT_URI:-}"
GOOGLE_HEALTH_REDIRECT_URI: "${GOOGLE_HEALTH_REDIRECT_URI:-}"
# Nightscout origins on your own network that the per-user connection
# validator should accept, comma-separated (e.g. "http://nightscout.lan").
# Without it a LAN/private Nightscout URL is refused as an SSRF target.
NIGHTSCOUT_PRIVATE_ORIGINS: "${NIGHTSCOUT_PRIVATE_ORIGINS:-}"
# Webhook (Gotify, Home Assistant, n8n) and ntfy targets on your own
# network, comma-separated exact origins (e.g. "https://gotify.example.com,
# http://ntfy.lan:8080"). Without it a target that resolves to a private
# address is refused at send time as an SSRF target. Link-local, metadata
# and unspecified addresses stay refused even when listed. See
# docs/self-hosting/notifications.md.
NOTIFICATION_PRIVATE_ORIGINS: "${NOTIFICATION_PRIVATE_ORIGINS:-}"
# Paperless-ngx and Papra instances the document picker may reach,
# comma-separated exact origins (e.g. "https://paperless.example.com,
# http://papra.lan:1221"). Unset, the picker is off. Only listed origins are
# ever contacted, public or private; redirects are not followed and
# link-local, metadata and unspecified addresses stay refused even when
# listed. See docs/self-hosting/document-sources.md.
DOCUMENT_SOURCE_ORIGINS: "${DOCUMENT_SOURCE_ORIGINS:-}"
# Open-Meteo endpoints for the environment/weather correlation. Default to
# the hosted service; point them at your own Open-Meteo deployment to keep
# the coordinate lookups off a third party.
OPENMETEO_BASE_URL: "${OPENMETEO_BASE_URL:-}"
OPENMETEO_GEOCODING_URL: "${OPENMETEO_GEOCODING_URL:-}"
# OIDC SSO login (self-hosted IdP: Authentik/Keycloak/Authelia/etc).
# All three of ISSUER_URL/CLIENT_ID/CLIENT_SECRET together enable the
# "Sign in with SSO" button; set none to leave it disabled. OIDC_ONLY
@@ -167,18 +277,63 @@ x-healthlog-env: &healthlog_env
# container (the `environment:` block is a whitelist). See
# docs/ops/tls-cert-pin.md.
TLS_LEAF_SPKI_PINS: "${TLS_LEAF_SPKI_PINS:-}"
# Local-AI SSRF opt-in (optional). The local AI provider rejects
# private/internal hosts by default; set this to an exact host allowlist
# (e.g. "ollama.lan,10.0.0.5") or "true" for any private host, intended
# for a self-hosted Ollama / LM Studio. Listed here so an operator value
# in .env reaches the container (the `environment:` block is a whitelist).
# See docs/integrations/ai-providers.md.
# AI endpoints on your own network (optional): a self-hosted Ollama,
# LM Studio or LiteLLM gateway, comma-separated exact origins (e.g.
# "http://ollama.lan:11434,http://10.0.0.5:4000"). Without it an AI base
# URL on a private address is refused. Link-local, metadata and
# unspecified addresses stay refused even when listed. See
# docs/integrations/ai-providers.md.
AI_PRIVATE_ORIGINS: "${AI_PRIVATE_ORIGINS:-}"
# Older form of the above, kept for existing installs: an exact host list
# (e.g. "ollama.lan,10.0.0.5") still works. "true" is deprecated: it now
# covers only the admin AI key and admin accounts' own AI settings, and
# will be removed in a later release; move to AI_PRIVATE_ORIGINS.
ALLOW_LOCAL_AI_PRIVATE_HOSTS: "${ALLOW_LOCAL_AI_PRIVATE_HOSTS:-}"
# Extra hosts the admin-configured AI base URL may point at, on top of the
# built-in public providers. Comma-separated bare hostnames. Set it when
# you run a gateway this instance should trust; it widens only the admin
# setting, never the per-user BYO-key posture.
ADMIN_AI_BASE_URL_ALLOWLIST: "${ADMIN_AI_BASE_URL_ALLOWLIST:-}"
# Codex (ChatGPT sign-in) model slugs. Set CODEX_MODEL to pin one slug
# ahead of the built-in chain, or CODEX_MODEL_FALLBACK_CHAIN (comma-
# separated) to replace the chain outright. Reach for these when the
# provider rotates a slug and every request starts coming back 503 —
# without them a rotation needs a new release to fix.
CODEX_MODEL: "${CODEX_MODEL:-}"
CODEX_MODEL_FALLBACK_CHAIN: "${CODEX_MODEL_FALLBACK_CHAIN:-}"
# Surfaces reviewed n-of-1 experiment outcomes in the Coach snapshot.
# Off by default — the read-back is the most overclaim-prone Coach
# surface, so it is an explicit operator opt-in. Set to "1" to enable.
COACH_EXPERIMENT_VERDICT: "${COACH_EXPERIMENT_VERDICT:-}"
# Daily-briefing output-token ceiling (optional; default 2500, clamped
# 500-8000). Raise when a verbose model's briefing JSON is cut off.
# Listed here so an operator value in .env reaches the container (the
# `environment:` block is a whitelist). See docs/integrations/ai-providers.md.
INSIGHTS_MAX_TOKENS: "${INSIGHTS_MAX_TOKENS:-}"
# Per-user hourly ceiling for POST /api/insights/generate (optional;
# default 10). Was documented but missing from this whitelist, so an
# operator value never reached the container. See
# docs/integrations/ai-providers.md.
INSIGHTS_RATE_LIMIT_PER_HOUR: "${INSIGHTS_RATE_LIMIT_PER_HOUR:-}"
# Per-user hourly ceiling for the document-AI actions (read/index, extract,
# suggest, summarise — one shared bucket; optional; default 6, clamped
# 1-1000). Raise on a self-host with a generous provider budget, lower on a
# tight one. Listed here so an operator value in .env reaches the container
# (the `environment:` block is a whitelist). See
# docs/integrations/ai-providers.md.
DOCUMENT_AI_LIMIT_PER_HOUR: "${DOCUMENT_AI_LIMIT_PER_HOUR:-}"
# Hourly upload ceiling for each narrow document-upload token (a Paperless
# workflow, the import script; optional; default 120, clamped 1-1000).
# Uploads from the web app and the phone keep their own bucket. Listed here
# so an operator value in .env reaches the container. See
# docs/integrations/document-import.md.
DOCUMENT_UPLOAD_LIMIT_PER_HOUR: "${DOCUMENT_UPLOAD_LIMIT_PER_HOUR:-}"
# Per-user hourly ceiling for lab-report scans (photo/PDF and browser-OCR
# text share one bucket; optional; default 6, clamped 1-1000). A scan that
# fails before the provider is called hands its slot back. Listed here so an
# operator value in .env reaches the container. See
# docs/integrations/ai-providers.md.
LABS_OCR_LIMIT_PER_HOUR: "${LABS_OCR_LIMIT_PER_HOUR:-}"
# v1.17.1 — SMTP transport for the email notification channel (optional,
# all-or-none: HOST + PORT + FROM enable it; USER/PASS optional; SECURE
# toggles implicit TLS). Listed here so operator values in .env reach the
@@ -205,12 +360,47 @@ x-healthlog-env: &healthlog_env
# PWA users need none of this (Web Push covers them). See
# docs/self-hosting/notifications.md.
APNS_KEY_B64: "${APNS_KEY_B64:-}"
# The other two key sources, in precedence order after APNS_KEY_B64:
# APNS_KEY is the raw PEM body, APNS_KEY_FILE a path to the .p8 inside the
# container (mount it yourself). Both are documented in
# .env.production.example and in the manifest check-env reads, and both
# were absent from this whitelist — so an operator who followed the
# documented precedence chain got a silently disabled APNs.
APNS_KEY: "${APNS_KEY:-}"
APNS_KEY_FILE: "${APNS_KEY_FILE:-}"
APNS_KEY_ID: "${APNS_KEY_ID:-}"
APNS_TEAM_ID: "${APNS_TEAM_ID:-}"
APNS_BUNDLE_ID: "${APNS_BUNDLE_ID:-}"
# Force the production APNs gateway. Normally derived from NODE_ENV; set
# "true" when a production-signed build has to reach the production
# gateway from a non-production deployment.
APNS_PRODUCTION: "${APNS_PRODUCTION:-}"
# Set "true" only if your own iOS build carries Apple's Critical Alerts
# entitlement; otherwise urgent alerts use the time-sensitive level.
APNS_CRITICAL_ENTITLEMENT: "${APNS_CRITICAL_ENTITLEMENT:-}"
# Structured logging. LOG_LEVEL is one of debug/info/warn/error (default
# info) — drop to debug while chasing a problem, raise to warn on a busy
# instance. LOG_SAMPLE_RATE keeps that fraction of successful events
# (default 1.0 = all; 0.1 thins a chatty log without losing errors).
# LOG_SLOW_THRESHOLD_MS is the duration above which a request is flagged
# slow (default 3000). LOG_INCLUDE_STACK="false" strips stack traces from
# the emitted events.
LOG_LEVEL: "${LOG_LEVEL:-}"
LOG_SAMPLE_RATE: "${LOG_SAMPLE_RATE:-}"
LOG_SLOW_THRESHOLD_MS: "${LOG_SLOW_THRESHOLD_MS:-}"
LOG_INCLUDE_STACK: "${LOG_INCLUDE_STACK:-}"
# Optional log shipping to a Loki instance. Set LOKI_ENDPOINT to the base
# URL or the full push URL to turn it on; a Loki on your own network works.
# The username/password pair is only needed when your Loki is behind basic
# auth. Push failures show up as a rate-limited line on stderr. Leave all
# three unset and logs stay on stdout for the Docker log driver to rotate.
LOKI_ENDPOINT: "${LOKI_ENDPOINT:-}"
LOKI_USERNAME: "${LOKI_USERNAME:-}"
LOKI_PASSWORD: "${LOKI_PASSWORD:-}"
# Server-side prefetch for the dashboard, insights, coach and checkups
# pages. On by default; set "false" to fall back to pure client fetching,
# which is the escape hatch when a prefetch is misbehaving on your host.
DASHBOARD_SSR_PREFETCH: "${DASHBOARD_SSR_PREFETCH:-}"
services:
# Single-container default (HEALTHLOG_PROCESS_TYPE=all). Existing
@@ -277,13 +467,15 @@ services:
options:
max-size: "10m"
max-file: "3"
# Conservative memory ceiling for a small host. HEALTHLOG_PROCESS_TYPE=all
# bundles the AI/rollup worker into this same process, and unbounded that
# workload can grow large enough under load to starve Postgres of memory
# on a shared host. 1g is a starting point, not a measured ceiling — raise
# it with APP_MEMORY_LIMIT in .env if the app gets OOM-killed under real
# load.
mem_limit: "${APP_MEMORY_LIMIT:-1g}"
# Memory ceiling for the app. HEALTHLOG_PROCESS_TYPE=all bundles the
# AI/rollup/backup worker into this same process, and unbounded that
# workload can grow large enough to starve Postgres on a shared host.
# Node sizes its heap from this limit: 1g gives a 524 MB heap, which a
# long-used account fills in normal operation, so garbage collection
# stalls requests for seconds and a weekly backup can crash the process.
# 1536m gives 792 MB. On a host with 2 GB or less, lower it with
# APP_MEMORY_LIMIT in .env; on a busy instance, raise it.
mem_limit: "${APP_MEMORY_LIMIT:-1536m}"
healthcheck:
test:
[
@@ -321,7 +513,7 @@ services:
# options:
# max-size: "10m"
# max-file: "3"
# mem_limit: "${WORKER_MEMORY_LIMIT:-1g}"
# mem_limit: "${WORKER_MEMORY_LIMIT:-1536m}"
db:
# Pinned to the concrete minor instead of the floating `16-alpine`
@@ -330,7 +522,16 @@ services:
# existing deployments see no image change). Minor releases share
# the on-disk format — bumping this pin is safe without a dump /
# restore; a major-version bump (17+) is not.
image: postgres:16.14-alpine
#
# The pin only works as long as something watches it: PostgreSQL
# publishes minor releases with security and data-corruption fixes and
# recommends running the current one, and this line sat two minors
# behind for five weeks because the Dockerfile was the only thing
# Dependabot looked at. The `docker-compose` ecosystem in
# `.github/dependabot.yml` now raises a PR for each new minor;
# `src/__tests__/database-pin-is-watched.test.ts` keeps both halves
# (concrete pin, active watch) from being dropped.
image: postgres:16.15-alpine
container_name: healthlog-db
# cap_drop: [ALL] is deliberately NOT applied here (unlike `app`): the
# official Postgres entrypoint starts as root, chowns the data
+55
View File
@@ -0,0 +1,55 @@
# Building a native client against HealthLog
Working notes for anyone building a client app (Android, iOS, CLI, anything else) against the HealthLog server, with or without AI tooling. Everything in here is a rule we actually follow between the server and the iOS app, written down so a second client does not have to rediscover it. Pair it with `CLAUDE.md` (server-side conventions) and `docs/api/openapi.yaml` (the wire contract).
## The contract, and where truth lives
- `docs/api/openapi.yaml` is the single source of truth for the API. It is generated from the server's Zod schemas and CI fails on drift, so what the YAML says is what the server does. Build your models from it rather than from observed responses.
- The contract you target is the one in a tagged release (`vX.Y.Z`), not whatever is on `main` between releases. A running server tells you its version at `GET /api/version` (`version`, `buildSha`, `builtAt`).
- Contract changes are additive. Fields get added, routes get added; existing consumers keep reading what they read before. When a route is retired it does not vanish: it answers `410` with a machine-readable `meta.errorCode`, so a client can tell "removed on purpose" from "you have a bug".
- If you need something the API does not carry, ask for it in an issue before building a workaround. Adding a route or a field on the server is usually cheaper than a client-side reconstruction, and a workaround becomes a compatibility burden for both sides the moment it ships.
## The envelope
Every JSON route answers the same shape: `{ data, error }`, with `meta` on the error path when there is something machine-readable to say. Success means `data` is set and `error` is `null`. Validation failures answer `422` and carry every issue at once, not just the first, so a form can annotate all fields in one round trip. Parse the envelope first, then the payload; never assume a `200` body is the payload directly.
## Auth, from a client's point of view
- Password, passkey, and an OIDC handoff exist for sign-in. The native OIDC flow hands the app a one-time code via a fixed URL scheme; tokens never ride a URL.
- Refresh tokens rotate per device and are one-time-use. Reusing an old one revokes that device's whole token family, on purpose. Persist the newest pair atomically and never retry a refresh with a token that already succeeded once.
- Bearer token scopes are fail-closed. A token minted for one purpose does not open unrelated routes, and a route that does not declare a scope refuses narrow tokens outright. Expect `403` to be a normal, recoverable answer, not an anomaly.
- Admin surfaces are cookie-session only, by construction. A native client cannot be an admin client, whatever scopes its token carries. Do not build admin features.
- Mutations accept an `Idempotency-Key` header. A repeat of the same key with the same body answers with the original result plus `X-Idempotent-Replay`, so retrying on a dropped connection is safe. A different body under the same key is treated as a new request, not a replay; still, give each distinct write its own key. Use it for anything a user would notice twice.
## Data semantics worth knowing before you sync
- Batch measurement ingest treats `externalId` as the dedupe handle. Ids with the `stats:` prefix are overwrites (a re-post replaces the row), every other id is first-write-wins immutable. The per-entry response says which happened (`inserted` vs `updated`). Design your sync around that difference rather than around client-side bookkeeping.
- Absence is explicit. A metric that answers "not present" means the record honestly has nothing there. It is not zero, not an error, and not a reason to fill the gap client-side.
- Modules can be switched off per account. Routes belonging to a disabled module answer `403`; render that as "this feature is off", not as a failure.
- Whatever the user typed stays verbatim. Names of custom metrics, notes, labels: the server returns the user's own text and does not translate or normalise it. Curated content, on the other hand, comes with stable keys a client can localise.
## Server-authoritative values
The strongest rule we have, learned the slow way: when the server computes something (a compliance rate, a health-score verdict, a reference-range judgement, an aggregation bucket), the client renders the resolved value from the payload. It does not re-derive the number from raw data, because two implementations of one formula will disagree eventually, and the user sees two apps arguing about their own health record.
The corollary: if a resolved value you need is missing from a payload, the fix is to ask the server to carry it, never to reimplement the server's logic in the client. And when the server changes a resolved value's meaning, that is a contract change and gets announced, not slipped in.
## How coordination works in practice
- One issue per question or contract need, opened early, ideally before you build on an assumption. A wrong assumption caught in an issue costs a comment; caught after a release it costs a migration.
- Claims about behaviour are made against a running instance, with the route and status code, not from reading code. "The code looks like it should" has burned us; "I called it and got this" has not.
- Answers you get from the server side name file and line or route and measurement, so you can verify them instead of trusting them. Hold your own reports to the same bar and it stays pleasant.
- Release notes and the changelog say when something client-relevant shipped. Reconcile open questions against each release rather than assuming the answer is still pending.
## Ground rules for the repo itself
The voice-and-privacy rules from `CLAUDE.md` apply to any repo under the project, including a client repo: commit messages and public text carry no tooling attribution and no assistant vocabulary, no real names of users or reporters, and no live health figures, ever. Fixtures use invented data. If an AI tool wrote part of a change, the human who commits it has read it and stands behind it; the git history knows only authors.
Secrets never appear in code, fixtures, or examples, not even placeholder-shaped real ones. Anything user-identifying stays out of logs on the client just as it does on the server.
## What a client should not do
- No scraping of web routes or HTML pages; the JSON API is the interface.
- No admin endpoints, see above.
- No CORS assumptions: the server serves same-origin browsers and header-authenticated APIs, nothing else.
- No silent behavioural drift from the web app. Where the web app and a native client both render the same concept, they should mean the same thing; when they cannot, that difference is documented in an issue, not discovered by users.
+22 -10
View File
@@ -13,9 +13,10 @@ notes, and machine-readable specs that ship alongside the source:
[`api/mcp-capabilities.md`](./api/mcp-capabilities.md) (tools,
resources, prompts, write model) and
[`api/mcp-skills.md`](./api/mcp-skills.md) (building a connector / skill).
- [`ops/`](./ops/) — backup / restore + encryption-key-rotation
playbooks. These are the runbooks an operator reaches for during an
incident.
- [`ops/`](./ops/) — operator runbooks: deploy, backup / restore,
encryption-key rotation, password reset and account recovery, env
checks, TLS pinning, data repair. These are what an operator reaches
for during an incident.
- [`self-hosting/`](./self-hosting/) — horizontal-scaling notes
(`HEALTHLOG_PROCESS_TYPE=web|worker|all`) and the deploy-pipeline
recipe. Routine install steps stay on `docs.healthlog.dev`. Includes
@@ -26,15 +27,26 @@ notes, and machine-readable specs that ship alongside the source:
`OIDC_ONLY` consequences, and the break-glass runbook. Also
[`self-hosting/geolite2.md`](./self-hosting/geolite2.md) — bringing your
own offline GeoLite2 databases via `GEOLITE2_DIR` instead of sending
login IPs to a third-party lookup.
- [`migration/`](./migration/) — release-by-release migration notes.
Read the entry for the version you're upgrading from.
- [`audit/`](./audit/) — per-release audit summaries archived for
forensic traceability.
login IPs to a third-party lookup. And
[`self-hosting/account-sharing.md`](./self-hosting/account-sharing.md) —
letting one account on the instance open another's health record: the
three access levels, the eight sections a grant can be narrowed to,
managed profiles for somebody with no login and the guardians who look
after them, what revocation does and does not undo, and which trust
properties of the instance are unchanged by any of it.
- [`migration/`](./migration/) — migration notes. Currently only
v1.3 to v1.4; later releases are covered by `CHANGELOG.md` and
<https://docs.healthlog.dev>.
- [`integrations/`](./integrations/) — per-integration reference
(Withings, Fitbit, Google Health, WHOOP, Apple Health, AI providers,
data import).
- [`adr/`](./adr/) — architecture decision records.
- [`security/`](./security/) — threat-model notes.
- [`diagrams/`](./diagrams/) — architecture diagrams rendered through
docs.healthlog.dev.
- [`releases/`](./releases/) — release imagery.
- [`apple-store-connect-checklist.md`](./apple-store-connect-checklist.md)
— the iOS submission gate.
- [`doctor-report.md`](./doctor-report.md) — PDF generator design
notes.
- [`codex-protocol-spec.md`](./codex-protocol-spec.md) — Codex / ChatGPT
OAuth protocol reverse-engineering notes.
- [`ui-guidelines.md`](./ui-guidelines.md) — UI / a11y house style.
+61 -31
View File
@@ -1,8 +1,12 @@
# HealthLog API Spec
`openapi.yaml` is the canonical OpenAPI 3.1 description for the HealthLog
Next.js API. It is the source of truth for the native iOS client's
DTO codegen.
`openapi.yaml` is the OpenAPI 3.1 description for the HealthLog
Next.js API and the source of truth for the native iOS client's DTO
codegen. The file is **generated**: `pnpm openapi:generate` emits it
from the Zod registry under `src/lib/openapi/` (`registry.ts` plus the
route modules in `src/lib/openapi/routes/`). Do not edit the YAML by
hand; the next generation overwrites it, and CI (`openapi:check`)
fails the build when the committed YAML drifts from the registry.
The MCP server is documented separately — it is a distinct contract over
JSON-RPC, not part of the REST OpenAPI spec:
@@ -34,36 +38,58 @@ npx @redocly/cli build-docs docs/api/openapi.yaml --output docs/api/index.html
npx @redocly/cli lint docs/api/openapi.yaml
```
The spec is expected to be lint-clean (errors = 0). Some warnings are
intentional:
- `no-server-example.com` — `http://localhost:3000` is the dev server.
- `operation-2xx-response` / `operation-4xx-response` — webhook + redirect
endpoints intentionally omit one or the other.
- `no-unused-components` — `ReminderPhase` is exposed for client codegen
even though no path response references it directly.
The spec is expected to be lint-clean (errors = 0). Warnings such as
`no-server-example.com` for the localhost dev server are tolerated;
re-run the lint to see what it produces against the current file
before treating a warning as a regression.
## Layout
- **`info`** — title, version (mirrored from `package.json`), description.
- **`servers`** — production `https://healthlog.bombeck.io` plus
`http://localhost:3000` for local development.
- **`tags`** — domain groupings (`Auth`, `Measurements`, `Medications`,
`Mood`, `Dashboard`, `Insights`, `Achievements`, `DoctorReport`,
`Integrations`, `User`, `Tokens`, `Notifications`, `Onboarding`,
`Health`, `Settings`, `Analytics`, `Export`, `AuditLog`,
`Monitoring`, `Webhooks`, `Ingest`, `Admin`).
- **`info`** — title, description, and `version` mirrored automatically
from `package.json` at generation time. Never bump it by hand.
- **`servers`** — `https://healthlog.example.com` as the self-hosted
placeholder plus `http://localhost:3000` for local development.
- **`tags`** — domain groupings; the current set lives at the top of
the generated file (`Auth`, `Measurements`, `Medications`, `Mood`,
`Analytics`, `Insights`, `Consent`, `Dashboard`, `Notifications`,
`Devices`, `Export`, `Sync`, `Cycle`, `MeasurementReminders`,
`Labs`, `Illness`, `Documents`, `Records`, `Admin`, `Meta`,
`Retired`).
- **`securitySchemes`**:
- `bearerAuth` — long-lived `hlk_*` API tokens issued via `POST /api/tokens`.
Required on `/api/ingest/medication`.
- `bearerAuth` — `hlk_*` API tokens. A scope grants what it names and
nothing adjacent, so where a token comes from decides what it reaches:
- a completed password / passkey / refresh exchange mints the
cookie-equivalent `["*"]` token the native client carries;
- a medication's own API-endpoint toggle mints `medication:ingest` plus
`medication:<id>:ingest`, the pair `/api/ingest/medication` gates on;
- `POST /api/mcp/tokens` mints `health:read` (optionally plus
`health:write`), audience-bound to `/mcp` and refused on REST writes;
- `POST /api/tokens/measurements` mints `measurements:write`, accepted by
`POST /api/measurements` and `POST /api/measurements/batch` only, on the
holder's own record only;
- `POST /api/tokens/workouts` mints `workouts:write`, accepted by
`POST /api/workouts/batch` only, on the holder's own record only; the
workouts it writes carry `source: EXTERNAL`;
- `POST /api/tokens/documents` mints `documents:write`, accepted by
`POST /api/documents/inbound` and `GET /api/documents/inbound/source`
only.
`POST /api/tokens` is **not** among them — that generic mint was removed in
v1.30.17. The path still lists (`GET`) and revokes (`DELETE /api/tokens/{id}`)
every token above, whichever surface issued it.
- `sessionCookie` — HttpOnly `healthlog_session` cookie set by the
password and passkey login flows. Used by the web app and any iOS
client running inside a web view.
- **`components.schemas`** — DTOs for all routes plus the underlying
Prisma models (e.g. `Measurement`, `Medication`, `MedicationIntakeEvent`,
`MoodEntry`, `User`, `DashboardLayout`, `ApiEnvelope`, `ApiError`).
- **`paths`** — all routes from `src/app/api/**/route.ts`, including
the `/api/admin/*` family which is tagged `Admin` and marked internal.
- **`components.schemas`** — DTOs for the documented routes plus the
underlying Prisma models (e.g. `Measurement`, `Medication`,
`MedicationIntakeEvent`, `MoodEntry`, `User`, `DashboardLayout`,
`ApiEnvelope`, `ApiError`).
- **`paths`** — the client-facing REST surface. Not every
`src/app/api/**/route.ts` is in the contract: most `/api/admin/*`
routes, the OAuth connect/callback legs, and the webhook surfaces
are not documented here. The `Retired` tag lists removed paths that
answer `410 Gone`.
## Conventions
@@ -79,8 +105,12 @@ intentional:
When adding or changing routes:
1. Update the relevant route handler under `src/app/api/**/route.ts`.
2. Mirror the change in `openapi.yaml`. Keep `operationId` camelCase and
stable — the iOS codegen keys off it.
3. Run `npx @redocly/cli lint docs/api/openapi.yaml` and resolve all
errors. Warnings are tolerated when documented above.
4. Bump `info.version` if the change is breaking for clients.
2. Change the Zod schemas and their `.meta()` registrations under
`src/lib/openapi/` (registry entry plus the matching module in
`src/lib/openapi/routes/`). Keep `operationId` camelCase and
stable; the iOS codegen keys off it.
3. Run `pnpm openapi:generate` and commit the regenerated
`openapi.yaml` alongside the schema change. CI's `openapi:check`
fails on drift.
4. Never edit the YAML directly and never bump `info.version` by
hand; the version follows `package.json` at generation time.
+103 -29
View File
@@ -66,38 +66,111 @@ optional so a `{ present: false }` miss and a full hit both validate.
argument. Every read is a thin wrapper over an existing
server-authoritative path; no new analytics is computed at the wire.
| Tool | What it returns |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `list_metrics` | One row per domain: whether data is present, an approximate sample count, and the tool that retrieves it. **Call this first.** |
| `get_metric_series` | One metric's aggregate (count, min, max, mean, slope) plus recent-daily and weekly timelines, with units and population reference bands. |
| `get_metrics` | Several metric series in one call — a paginated fan-out over `get_metric_series`, one grounded result per metric. |
| `get_glucose_panel` | Per-context daily means plus the trailing-30-day clinical panel (time-in-range, GMI, CV%, estimated A1c). |
| `get_sleep` | Per-night asleep + stage minutes plus the sleep-rhythm summary (sleep debt + chronotype). |
| `get_workouts` | Most recent sessions (sport, duration, energy, distance, avg/max HR) plus a per-sport rollup over the window. |
| `get_medication_compliance` | Cadence-aware adherence: dose-weighted compliance rate, expected vs taken/missed, current-cycle status, any GLP-1 titration context. |
| `get_labs` | Latest reading per biomarker over the last 12 months (optionally one analyte). With `history:true` + an analyte, that analyte's paginated reading trajectory. |
| `get_illness_recovery` | Rest mode, active and recently-resolved illnesses, recovery / strain composites, and the illness retrospective (recovery-gap, nadir, red flags). |
| `get_cycle` | Menstrual-cycle context: phase + day-of-cycle, next predicted event, headline phase-correlation. Gated on cycle tracking; descriptive only. |
| `get_correlations` | FDR-controlled day-to-next-day driver pairs between behaviours and outcomes, each with direction, lag, sample size, and a descriptive (never causal) note. |
| `get_correlation` | The vetted, lag-aware association between **two named metrics**: direction, lag, sample size, Pearson r, and a descriptive note. |
| `compare_metric` | One metric vs another over the same horizon, **or** one metric across two horizons (fixed windows or `{from,to}` ranges), with per-side stats + a delta. |
| `get_metric_baseline` | Where the latest reading sits against the user's own usual range (median ± robust deviation), plus the strongest lagged driver. Needs ≥ 7 days of history. |
| `detect_changepoints` | Points where a metric's level shifted over a window or `{from,to}` range — date, direction, before/after means. High firing bar. |
| `get_medication_schedule` | When each active medication is next due and which are overdue right now — name, dose, next-due, overdue flag, as-needed flag. Reuses the recurrence engine. |
| `get_integration_status` | Sync health of connected devices/services — connected, last sync, reauth-required/failing — to answer "why is my data stale?". No secrets or tokens. |
| `get_preventive_care` | The user's own configured preventive-care (Vorsorge) reminders — upcoming/overdue checkups with next-due dates. Surfaces configured reminders, invents nothing. |
| `search` | Free-text search over the user's record (metric domains, medications, lab analytes). Returns `{ results: [{ id, title, url }], nextCursor? }`. |
| `fetch` | Hydrate one record by the id `search` returned (`metric:weight`, `med:<id>`, `lab:LDL`). Returns `{ id, title, text, url, metadata }` with a citation deep-link. |
| Tool | What it returns |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `list_metrics` | One row per domain: whether data is present, an approximate sample count, and the tool that retrieves it. **Call this first.** |
| `get_metric_series` | One metric's aggregate (count, min, max, mean, slope) plus recent-daily and weekly timelines, with units and population reference bands. |
| `get_metrics` | Several metric series in one call — a paginated fan-out over `get_metric_series`, one grounded result per metric. |
| `get_glucose_panel` | Per-context daily means plus the trailing-30-day clinical panel (time-in-range, GMI, CV%, estimated A1c). |
| `get_sleep` | Per-night asleep + stage minutes plus the sleep-rhythm summary (sleep debt + chronotype). |
| `get_workouts` | Most recent sessions (sport, duration, energy, distance, avg/max HR) plus a per-sport rollup over the window. |
| `get_medication_compliance` | Cadence-aware adherence: dose-weighted compliance rate, expected vs taken/missed, current-cycle status, any GLP-1 titration context. |
| `get_labs` | Latest reading per biomarker over the last 12 months (optionally one analyte). With `history:true` + an analyte, that analyte's paginated reading trajectory. |
| `get_illness_recovery` | Rest mode, active and recently-resolved illnesses, recovery / strain composites, and the illness retrospective (recovery-gap, nadir, red flags). |
| `get_cycle` | Menstrual-cycle context: phase + day-of-cycle, next predicted event, headline phase-correlation. Gated on cycle tracking; descriptive only. |
| `get_correlations` | FDR-controlled day-to-next-day driver pairs between behaviours and outcomes, each with direction, lag, sample size, and a descriptive (never causal) note. |
| `get_correlation` | The vetted, lag-aware association between **two named metrics**: direction, lag, sample size, Pearson r, and a descriptive note. |
| `compare_metric` | One metric vs another over the same horizon, **or** one metric across two horizons (fixed windows or `{from,to}` ranges), with per-side stats + a delta. |
| `get_metric_baseline` | Where the latest reading sits against the user's own usual range (median ± robust deviation), plus the strongest lagged driver. Needs ≥ 7 days of history. |
| `detect_changepoints` | Points where a metric's level shifted over a window or `{from,to}` range — date, direction, before/after means. High firing bar. |
| `get_medication_schedule` | When each active medication is next due and which are overdue right now — name, dose, next-due, overdue flag, as-needed flag. Reuses the recurrence engine. |
| `get_integration_status` | Sync health of connected devices/services — connected, last sync, reauth-required/failing — to answer "why is my data stale?". No secrets or tokens. |
| `get_preventive_care` | What preventive care is coming up: the user's own configured Vorsorge reminders (upcoming/overdue checkups with next-due dates) plus the appointments booked as future visits. Surfaces configured items, invents nothing. |
| `get_visits` | The user's own past doctor visits over a bounded window (default 12 months, optional practitioner-name filter): date, status, kind, practitioner + specialty, the visit's own reason/outcome, and any linked condition labels. `{ present: false }` when none was ever recorded. |
| `get_intraday_pulse` | The 10-minute heart-rate shape for one local day (hourly grain outside the dense-retention window), with at most one cautious descriptive elevated-at-rest window. Gated on the `insights` module. |
| `get_ecg_recordings` | Metadata for the user's ECG recordings (time, duration, sampling rate, lead, the device's own rhythm classification). Never the waveform, never a re-classification. Gated on the `insights` module. |
| `get_nutrients` | Without an argument, the presence overview per logged nutrient code; with one, that code's per-day summed series plus its EFSA reference. Gated on the opt-in `nutrients` module. |
| `search` | Free-text search over the user's record: metric domains, medications, lab analytes, and the clinical records (visits including procedures, conditions, documents, vaccinations). Ranked, deterministic, record results capped at 50. Returns `{ results: [{ id, title, url }], nextCursor? }`. |
| `fetch` | Hydrate one record by the id `search` returned (`metric:weight`, `med:<id>`, `lab:LDL`, `visit:<id>`, `condition:<id>`, `document:<id>`, `vaccination:<id>`). Returns `{ id, title, text, url, metadata }` with a citation deep-link; clinical records carry their one-hop links. |
`search` + `fetch` are the de-facto two-tool retrieval convention and the
**only** tools ChatGPT calls in its default (non-Developer) mode. Each
result carries a real, user-openable HTTPS deep link into the HealthLog
web app so the assistant can cite it.
What `search` matches for the clinical records:
- `visit:<id>`: visit kind (a procedure also answers to "surgery" and
"operation"), reason, outcome, body site and side, practitioner name and
specialty.
- `condition:<id>`: label, type, body site and side.
- `document:<id>`: title, file name, document kind ("discharge letter"),
and whole words of the document's indexed text when one is stored. The
document itself is never read for a search. A document uploaded with AI
reading deferred is matched on its title and details only.
- `vaccination:<id>`: vaccine name, catalogue name, practitioner.
Condition and vaccination notes are never searched or returned, the same
rule the Coach and the doctor report follow. A deleted practitioner is not
named or matched. Query words shorter than four letters match whole words or
word starts only. Titles and file names are also looked up in the database,
so an older document is found by them even outside the newest 500.
Body sites are matched after decryption, folded the way the body-sites view
folds them, with German and English body-part names treated as one ("knee"
finds "Knie"). Results are ordered by how many query words they match, then
by field weight, then newest first, so the same query always returns the
same list. A kind whose module is switched off (`illness`,
`inboundDocuments`, `vaccinations`, and for the older kinds `medications`
and `labs`) is neither searched nor fetched; `fetch` answers such an id with
`metadata.reason: "module_disabled"`. The same switches apply to every other
MCP read: `get_labs`, `get_medication_schedule`, `get_medication_compliance`
and the lab and medication resources answer
`{ present: false, reason: "module_disabled" }`, and `get_visits` withholds
condition labels (`conditionsReason: "module_disabled"`) when the illness
module is off.
`fetch` on a clinical record returns its key fields, with never-recorded
fields as `null`, and `metadata.links`: the records it is directly linked to,
each with an id `fetch` accepts. A document returns its metadata and at most
a 1,500-character excerpt of its indexed text, never the file, a download
URL, or its stored summary. A document held back from AI reading returns no
excerpt and `metadata.reason: "ai_read_deferred"`. All user-written text is wrapped in the
`<<<USER_TEXT_START>>>` / `<<<USER_TEXT_END>>>` fence.
Every read tool is annotated read-only / non-destructive / idempotent /
closed-world — the read-only guarantee is structural (only read tools are
registered for a read session), and the annotation merely advertises it.
### Naming a metric or a nutrient
The tools that take a free-text name — `compare_metric`,
`get_metric_baseline`, `detect_changepoints`, `get_nutrients` — accept the
metric's or nutrient's own display name in **any language HealthLog ships**
(de / en / es / fr / it / pl), alongside the internal code and the English
aliases. `poids`, `Blutzucker`, `Fer` and `Żelazo` reach the same series as
`weight`, `blood_glucose` and `iron`. Case, accents and punctuation are
folded, so `magnésium` and `MAGNESIUM` are one word.
The accepted names are read out of the app's own message bundles rather
than listed in the resolver, so a language works as soon as its bundle
ships. Two consequences worth relying on:
- **The vocabulary is still closed.** A word in no bundle is a miss, not a
guess: `{ present: false, reason: "unknown_metric" }` or
`"unknown_nutrient"`. That reason is distinct from `"no_data"`, which
means the name WAS understood and the record honestly holds nothing.
Widening the accepted spellings moves words from the first answer to the
second; it never turns absence into data.
- **An ambiguous word is refused, not resolved.** Where a language uses one
phrase for two different measurements — French and Italian call both body
fat and fat mass `masse grasse` / `massa grassa`, and French, Italian and
Polish use one phrase for fat-free mass and lean body mass — the word
resolves to neither. Name those in English, or by their metric key.
Responses are unchanged: labels and units come back in protocol-level
English whatever language the request used.
### Clinical signals
The v1.25 clinical-signals set — **grip strength**, **pain (0–10 NRS)**,
@@ -159,13 +232,14 @@ completion and listing are user-scoped, so a host only ever sees the
metrics / analytes / medications the user actually has — completion
doubles as honest discovery.
| Template | Resolves to |
| ------------------------------------------ | --------------------------------------------------------------------------------------- |
| `healthlog://metric/{type}` | One metric's series over the default window. |
| `healthlog://metric/{type}/{window}` | One metric's series over a chosen trailing window. |
| `healthlog://lab/{analyte}` | One lab analyte's recent readings (value, unit, reference range, status). |
| `healthlog://medication/{id}` | One medication by id, with its schedules. User-scoped (`{present:false}` if not yours). |
| `healthlog://report/doctor-visit/{window}` | The doctor-visit summary over a chosen window. |
| Template | Resolves to |
| ------------------------------------------ | ----------------------------------------------------------------------------------------- |
| `healthlog://metric/{type}` | One metric's series over the default window. |
| `healthlog://metric/{type}/{window}` | One metric's series over a chosen trailing window. |
| `healthlog://lab/{analyte}` | One lab analyte's recent readings (value, unit, reference range, status). |
| `healthlog://medication/{id}` | One medication by id, with its schedules. User-scoped (`{present:false}` if not yours). |
| `healthlog://report/doctor-visit/{window}` | The doctor-visit summary over a chosen window. |
| `healthlog://nutrient/{code}` | One nutrient's per-day intake series plus its EFSA reference (opt-in `nutrients` module). |
## Prompts (skills)
+46752 -4982
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -34,7 +34,7 @@ Plus pre-submit final checks.
- [ ] Add the description above to the medical-device-justification field if Apple shows one
- [ ] Cross-reference the in-app `/privacy` page (https://<your-instance>/privacy) §7 MDR-boundary
**Why this matters**: Apple's first-submission rejection rate for health apps is ~40%. The most common reason is unclear medical-device classification. The above wording mirrors the in-app disclaimer + the per-feature gating; consistency between the form and the app is what Apple looks for.
**Why this matters**: health apps get rejected on first submission most commonly for unclear medical-device classification. The above wording mirrors the in-app disclaimer + the per-feature gating; consistency between the form and the app is what Apple looks for.
## Section 2 — Privacy Nutrition Labels
Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

+11 -7
View File
@@ -630,8 +630,9 @@ Confirmed-rejected slugs (despite the source-tree references in the table above)
Confirmed-accepted slugs on a ChatGPT Plus subscription (per `available_in_plans` in `models.json`):
- `gpt-5.3-codex` — coding-optimized, accepted; HealthLog uses this as default
- `gpt-5.5` / `gpt-5.4` / `gpt-5.4-mini` / `gpt-5.2` — also expected to work per plan
- `gpt-5.5` — HealthLog's default (first chain entry) as of 2026-06
- `gpt-5.4` / `gpt-5.4-mini` / `gpt-5.2` — accepted per plan
- `gpt-5.3-codex` — was the default (verified 2026-05-09); the backend rotated off the `-codex` line on 2026-06-02 and this slug is now only accepted intermittently, so it sits on a late chain rung
The `codex-rs/tui/src/model_migration.rs` references to `gpt-5-codex` etc. are _migration prompts_ shown to existing users — they are NOT the slugs sent on the wire after migration. The wire slugs come from `models.json`. Always cross-check `models.json` (`gh api repos/openai/codex/contents/codex-rs/models-manager/models.json`) before picking a default.
@@ -641,17 +642,20 @@ The ChatGPT-Codex allow-list is rotated by OpenAI without prior notice (`gpt-5-c
To eliminate that risk class, HealthLog's `CodexClient` walks an ordered chain on every fresh request series.
**Chain** (top = first try; default order is the empirically-safest most-current-first ordering as of 2026-05):
**Chain** (top = first try; default order is the empirically-safest most-current-first ordering as of 2026-06, after the backend rotated off the `-codex` line on 2026-06-02):
```ts
const DEFAULT_SLUG_FALLBACK_CHAIN = [
"gpt-5.3-codex", // current allow-list entry (verified 2026-05-09)
"gpt-5-codex", // historical default (rejected as of 2026-05 but safe to retry — backend may flip)
"gpt-5", // bare slug — rejected on ChatGPT-auth as of 2026-05 but lives on api-key auth
"gpt-4o", // ladder-rung for last-ditch capability
"gpt-5.5", // current default across paid tiers as of 2026-06-02
"gpt-5.4", // documented fallback
"gpt-5.4-mini", // documented lighter-weight fallback
"gpt-5.3-codex", // late rung — still accepted intermittently
"gpt-5.2", // legacy floor
];
```
The shipped constant in `src/lib/ai/codex-client.ts` is authoritative; when the upstream rotates again, that file moves first and this listing follows.
The chain is overridable via the env var `CODEX_MODEL_FALLBACK_CHAIN` (comma-separated). The first env-var-named slug supersedes `CODEX_MODEL`; if both are set, `CODEX_MODEL` is folded into position 0 and de-duplicated.
**Trigger condition** (when to walk to the next slug):
+79 -29
View File
@@ -45,8 +45,8 @@ fallback for users who skip the setup.
## The fallback chain
`User.aiProviderChain` is a JSON array of providers tried in priority
order. The default is encoded in
`src/lib/ai/provider-chain.ts:60-66`:
order. The default is encoded as `PROVIDER_CHAIN_DEFAULT` in
`src/lib/ai/provider-chain.ts`:
1. `codex` — ChatGPT OAuth (covered by your ChatGPT Plus / Pro
subscription; no per-token cost on top).
@@ -79,7 +79,7 @@ the default rather than 500-ing.
4. In HealthLog, open `/settings/ai`. Set provider to **OpenAI**,
paste the key, optionally override the model.
The default model is `gpt-4o` (`src/lib/ai/provider.ts:80`) — a
The default model is `gpt-4o` (see `src/lib/ai/provider.ts`) — a
full-size model that keeps the headline Insights assessments grounded
and well-reasoned out of the box. Override to a lighter model such as
`gpt-4o-mini` if you want to trade some reasoning headroom for a lower
@@ -140,16 +140,35 @@ Base URL `http://<vllm-host>:8000/v1`, API key `your-shared-secret`,
model `Qwen/Qwen2.5-14B-Instruct`. The local-client encrypts the
API key at rest like every other provider credential.
**SSRF guard.** Local endpoints route through the same validation
as every other outbound URL HealthLog hits. The guard rejects
private-IP-range targets by default. `ALLOW_LOCAL_AI_PRIVATE_HOSTS`
opens the escape hatch and accepts two forms: a comma-separated host
allowlist (e.g. `ALLOW_LOCAL_AI_PRIVATE_HOSTS=ollama.lan,10.0.0.5`),
which permits only those exact hostnames, or the legacy
`ALLOW_LOCAL_AI_PRIVATE_HOSTS=true`, which permits any private host —
including the cloud-metadata endpoint, so prefer the host list. Leave
it unset on public-facing instances unless you specifically run an
internal endpoint.
**Private endpoints.** Any user of the instance can type a base URL,
so HealthLog refuses one on a private address unless the operator has
listed it. List the endpoint's exact origin in `AI_PRIVATE_ORIGINS`,
comma-separated, the same way `NOTIFICATION_PRIVATE_ORIGINS` works for
notification relays:
```bash
AI_PRIVATE_ORIGINS="http://ollama.lan:11434,http://10.0.0.5:4000"
```
An origin is `scheme://host[:port]` and nothing else: no path, no
wildcard, no range. A listed endpoint is called through a pinned
connection that refuses to follow redirects, and the cloud-metadata
address, link-local addresses and the unspecified address stay
unreachable even when listed or when a listed name resolves to one.
`ALLOW_LOCAL_AI_PRIVATE_HOSTS`, the older setting, still works as a
host list (`ollama.lan,10.0.0.5`, any port), with the same pinning.
Its `true` form used to open every private host on the network to
every user. It is deprecated since v1.39.3 and will be removed in a
later release. Until then it still covers the operator's own AI
configurations, the server key in the admin panel and AI settings
saved on an admin account, over the same pinned connection, so the
metadata address and link-local addresses stay unreachable. Any other
account's base URL needs its origin in `AI_PRIVATE_ORIGINS`. The boot
summary names the setting while it is set, and the admin AI settings
page shows the exact `AI_PRIVATE_ORIGINS` line for the endpoints saved
on the instance.
**Model sizing.** Roughly: 7-8B for 8 GB GPU / Apple Silicon base
(briefings fine, deeper Coach reasoning gets terse), 14-24B for
@@ -186,9 +205,9 @@ therefore never be sent to a host you typed into a different form,
and that property is structural rather than a comment — the OPENAI
arm has no code path that reads the gateway's base URL.
**SSRF guard.** The gateway's base URL passes the same floor as the
Local provider's: a public host always, a private one only when the
operator allowlisted it via `ALLOW_LOCAL_AI_PRIVATE_HOSTS` (documented
**Private endpoints.** The gateway's base URL passes the same floor
as the Local provider's: a public host always, a private one only when
the operator listed its origin in `AI_PRIVATE_ORIGINS` (documented
under Local endpoints above). LAN gateways are the normal case for LiteLLM and vLLM, so
the escape hatch matters here as much as it does for Ollama.
@@ -197,6 +216,15 @@ JSON surfaces send the standard
the field is detected on the first refusal and retried without it,
so strict gateways and older local servers both work unmodified.
**When the gateway refuses.** OpenRouter answers a refused generation
with HTTP 200 and the reason inside the body, so every refusal used to
reach the provider health card as an empty reply with no status. It now
carries the gateway's own status and message — 402 out of credits, 403
blocked, 429 rate-limited, 502 model down. The two account settings
behind most refusals are an empty credit balance and a data-policy or
zero-retention restriction that leaves no eligible provider for the
model you picked; both are changed in the gateway account, not here.
**The Local provider still works for this** and nothing about it
changed — it speaks the same wire and honours the same base URL. Pick
the gateway provider when the endpoint is a gateway (it says so in
@@ -234,7 +262,7 @@ UI setup:
`connected`.
5. Token refresh runs automatically; the client triggers a refresh
on 401 and persists the new tokens transparently
(`src/lib/ai/provider.ts:122-217`).
(`src/lib/ai/provider.ts`).
Disconnect cleanly from `/settings/ai` — `POST /api/auth/codex/disconnect`
clears the encrypted token columns. The wire-level protocol is
@@ -393,27 +421,49 @@ verbose model gets its briefing cut off mid-JSON — the API reports
that case as "AI response was cut off" rather than the generic
invalid-JSON error.
`DOCUMENT_AI_LIMIT_PER_HOUR` (default `6`, clamped to 1–1000) bounds
the document-AI actions per user per hour. Read/index, extract,
suggest and summarise share one bucket, and a slot is only consumed
when a request actually reaches the provider — a request that fails
during input preparation (unreadable file, exhausted daily budget,
malformed body) hands its slot back. Raise it when users batch-read
many documents against a generous provider budget; lower it on a
tight one. The 429 names the actual wait (the window is an hour) and
carries the reset instant in `X-RateLimit-Reset`.
`LABS_OCR_LIMIT_PER_HOUR` (default `6`, clamped to 1–1000) does the
same for lab-report scans. The photo or PDF scan and the browser-OCR
text scan share one bucket per user, and a scan that fails before the
provider is called (malformed body, file too large or not an image or
PDF, a PDF that cannot be rendered, exhausted daily budget) hands its
slot back. Raise it when users scan a stack of reports at once; the
daily AI budget still bounds the cost.
All four variables must also be listed in the compose
`environment:` whitelist to reach the container; the shipped
`docker-compose.yml` lists them.
## Connection test
`POST /api/ai/test` runs a one-shot probe against the resolved
provider and returns the latency in milliseconds plus the model the
provider routed to. The Settings UI surfaces a **Test connection**
button next to each provider section that fires this endpoint. A
failed probe surfaces a localisable `errorCode` so the UI renders
the failure in the user's language rather than the raw upstream
error.
provider and returns the resolved provider type, the model, the token
usage, and a short response sample. The Settings UI surfaces a
**Test connection** button next to each provider section that fires
this endpoint. A failed probe carries a categorised `reasonCode` so
the UI renders the failure in the user's language rather than the raw
upstream error.
## Troubleshooting
- **"No AI provider configured."** Either set up at least one BYOK
provider in `/settings/ai`, or configure an admin-shared OpenAI
key in the admin panel.
- **Local endpoint rejected as "internal/private host".** Set
`ALLOW_LOCAL_AI_PRIVATE_HOSTS` to the endpoint's exact hostname
(e.g. `ollama.lan`; comma-separate several) in the container
environment, or to `true` to allow any private host. Prefer the host
list; leave it unset on internet-facing instances unless you
specifically want to allow private-range targets.
- **Local endpoint rejected as "internal/private host".** Add the
endpoint's exact origin to `AI_PRIVATE_ORIGINS` in the container
environment (e.g. `http://ollama.lan:11434`; comma-separate several)
and restart. With `ALLOW_LOCAL_AI_PRIVATE_HOSTS=true` an admin
account's endpoint still works, but no other account's does; the
admin AI settings page lists the origins to add.
- **Codex disconnects after a few weeks of inactivity.** ChatGPT
refresh tokens lapse after extended idle periods. Reconnect via
the **Connect ChatGPT** button — HealthLog re-runs the device-code
+3 -2
View File
@@ -265,7 +265,8 @@ IMPORT** for cumulative metrics (steps, active energy, distance,
flights, sleep, HRV, resting HR) and **WITHINGS ≻ APPLE_HEALTH ≻
MANUAL** for point measurements where the Withings device is the
primary sensor (weight, BP, body fat, body temperature, SpO₂, VO₂
max). The defaults live in `src/lib/validations/source-priority.ts:205-220`.
max). The defaults live in `DEFAULT_SOURCE_PRIORITY` in
`src/lib/validations/source-priority.ts`.
Concrete consequences:
@@ -283,7 +284,7 @@ Concrete consequences:
source tag — the lowest rank — is reserved for legacy CSV/JSON
imports that pre-date the Apple Health passthrough.
Override per-user via the Sources section of `/settings/thresholds`.
Override per-user via Settings → Sources (`/settings/sources`).
## Failure modes
+37 -27
View File
@@ -1,6 +1,6 @@
# Data import
HealthLog has three ways to bring data in, all reachable from
HealthLog has four ways to bring data in, all reachable from
**Settings → Export & Import**:
1. An **Apple Health `export.zip`** upload — the full archive from the
@@ -12,10 +12,17 @@ HealthLog has three ways to bring data in, all reachable from
from another tracker. This page documents that format.
3. A **CSV import** — one measurement per row, for a spreadsheet or a
meter / sensor export. Documented in section 3 below.
4. A **medication dose-history import** — its own card in the same
panel, posting to `POST /api/medications/intake/dose-history-import`
with its own `?dryRun=1` preview.
All three paths skip rows that already exist, so re-running an import is
All paths skip rows that already exist, so re-running an import is
safe — it merges rather than duplicating.
Documents (letters, lab reports, scans) from Paperless-ngx or Papra come in
through a document token and an import script instead; see
[`document-import.md`](./document-import.md).
Every import reports what it actually wrote. A file where nothing was
written is shown as a failure, a file where some rows landed and some
were refused is shown as a partial result, and the refused rows are
@@ -33,9 +40,10 @@ the browser — and a background job parses it while a progress indicator
polls for the imported / skipped counts.
Re-uploading the same archive resolves to the same job by content hash,
so it merges instead of creating duplicates. Clinical records
(electrocardiograms, lab documents) are intentionally skipped. The full
type mapping lives in [`apple-health.md`](./apple-health.md).
so it merges instead of creating duplicates. ECG CSVs and metric-typed
clinical records are imported too; see
[`apple-health.md`](./apple-health.md) for the details and the full
type mapping.
## 2. Generic JSON import
@@ -56,15 +64,16 @@ skipped and counted under `skipped` in the response.
### Measurement entry
| Field | Required | Type | Notes |
| ---------------- | -------- | ------ | --------------------------------------------------------------------------------- |
| `type` | yes | enum | One of the `MeasurementType` values in the table below. |
| `value` | yes | number | Plausibility-checked per type; out-of-range values are rejected. |
| `unit` | yes | string | The canonical unit for the type (see the table). |
| `measuredAt` | yes | string | ISO-8601 datetime, e.g. `2026-05-01T08:00:00.000Z`. |
| `source` | no | string | Free-text origin label. Imported rows are tagged `IMPORT` server-side regardless. |
| `notes` | no | string | Optional free text. |
| `glucoseContext` | no | enum | Only for `BLOOD_GLUCOSE`. See [Glucose context](#glucose-context). |
| Field | Required | Type | Notes |
| ---------------- | -------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type` | yes | enum | One of the `MeasurementType` values in the table below. |
| `value` | yes | number | Plausibility-checked per type; out-of-range values are rejected. |
| `unit` | yes | string | The canonical unit for the type (see the table). |
| `measuredAt` | yes | string | ISO-8601 datetime, e.g. `2026-05-01T08:00:00.000Z`. |
| `source` | no | string | Free-text origin label. Imported rows are tagged `IMPORT` server-side regardless. |
| `notes` | no | string | Optional free text. |
| `glucoseContext` | no | enum | Only for `BLOOD_GLUCOSE`. See [Glucose context](#glucose-context). |
| `externalId` | no | string | A source-stable id (1–120 chars). When present, a re-import upserts on `(user, type, source, externalId)` so an edit upstream is reflected rather than skipped. |
### Glucose context
@@ -95,7 +104,7 @@ moment you know it.
| `mood` | yes | enum | One of `SUPER_GUT`, `GUT`, `OKAY`, `SCHLECHT`, `LAUSIG`. |
| `score` | yes | integer | `1`–`5`. |
| `tags` | no | string | Comma-separated tags. |
| `loggedAt` | no | string | ISO-8601 datetime; defaults to now. |
| `loggedAt` | no | string | ISO-8601 datetime; defaults to the start of the given `date` in the default timezone. |
| `externalId` | no | string | A source-stable id (1–120 chars). When present, a re-import upserts on `(user, source, externalId)` so an edit upstream is reflected rather than skipped. |
### `MeasurementType` values and canonical units
@@ -172,9 +181,10 @@ hand-authored.
| `WALKING_STEADINESS_EVENT` | event |
| `BREATHING_DISTURBANCE_EVENT` | event |
The live, machine-readable list of writable types and their units is
also served by `GET /api/meta/capabilities` under `ingest.quantityTypes`
— the authoritative source if this table ever lags a release.
The table is a curated subset and lags the enum by a few
device-derived types. The live, machine-readable list of writable
types and their units is served by `GET /api/meta/capabilities` under
`ingest.quantityTypes` and is the authoritative source.
### Worked example
@@ -234,15 +244,15 @@ mints a file with the right header.
A header row is required; column order does not matter and header
matching is case-insensitive.
| Column | Required | Notes |
| ---------------- | -------- | --------------------------------------------------------------------------------------------------------- |
| `type` | yes | A `MeasurementType` from the table above. |
| `value` | yes | A number, in the row's `unit`. |
| `unit` | yes | The canonical unit, or a recognised alias: `mmol/L` → `mg/dL`, `lb` → `kg`, `in` → `cm`, `°F` → `°C`. |
| `measuredAt` | yes | ISO-8601 **with an explicit offset** (`Z` or `±HH:MM`, and `±HHMM` is accepted). No offset, no import. |
| `glucoseContext` | no | Only for `BLOOD_GLUCOSE`; blank means no context. See [Glucose context](#glucose-context). |
| `notes` | no | Free text, up to 200 characters. |
| `externalId` | no | A source-stable id. With it, a re-upload updates the same row; without it, a re-upload creates a new one. |
| Column | Required | Notes |
| ---------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `type` | yes | A `MeasurementType` from the table above. |
| `value` | yes | A number, in the row's `unit`. |
| `unit` | yes | The canonical unit, or a recognised alias: `mmol/L` → `mg/dL`, `lb` → `kg`, `in` → `cm`, `°F` → `°C`. |
| `measuredAt` | yes | ISO-8601 **with an explicit offset** (`Z` or `±HH:MM`, and `±HHMM` is accepted). No offset, no import. |
| `glucoseContext` | no | Only for `BLOOD_GLUCOSE`; blank means no context. See [Glucose context](#glucose-context). |
| `notes` | no | Free text, up to 200 characters. |
| `externalId` | no | A source-stable id. With it, a re-upload updates the same row even when the value changed; without it, an identical re-upload is skipped via the natural key `(user, type, measuredAt, source)`. |
A sensor export therefore needs no glucose column at all:
+264
View File
@@ -0,0 +1,264 @@
# Importing documents from Paperless-ngx or Papra
HealthLog's document vault can take documents from another document system
without you uploading them one by one. There are two ways in, and both use
the same kind of credential: a **document token**.
- **Paperless-ngx** can send each newly tagged document to HealthLog by
itself, through a workflow. Good for new documents as they arrive.
- The **import script** copies documents from Paperless-ngx or Papra in one
go. Good for the archive you already have, and, run on a schedule, for
keeping Papra in step.
HealthLog never holds a password or token for Paperless-ngx or Papra. They
push into HealthLog; HealthLog does not reach into them.
## 1. Turn on Documents and create a document token
1. In HealthLog, turn on **Documents** under **Settings → Modules** if you
have not already. Uploads are refused while the vault is off.
2. Open **Settings → API & Tokens → Document tokens**, give the token a name (for
example "Paperless workflow"), and select **Create**.
3. Copy the token (it starts with `hlk_`). It is shown once.
A document token can add documents to your own vault and do nothing else. It
cannot list, open, download, change or delete a document, cannot use the AI
features, and cannot create another token. When it uploads a file it gets
back only whether the file was stored, not the title or anything else about
your vault. You can revoke it at any time under **Settings → API & Tokens →
API Tokens**. It expires after a year unless you revoke it sooner.
## 2. New documents from Paperless-ngx (workflow)
This needs Paperless-ngx 3.0 or later, the first release with the
`{{doc_id}}` placeholder. In Paperless-ngx, open **Workflows** and add one:
- **Triggers:** add _Document Added_ and _Document Updated_. On each, set
the filter to "has any of these tags" and pick the tag you use for health
documents, for example `HealthLog`.
- **Action:** _Webhook_.
- **Webhook url:** `https://<your HealthLog address>/api/documents/inbound`.
Use the address HealthLog is served at: Paperless does not follow
redirects.
- **Use parameters for webhook body:** on. **Send webhook payload as
JSON:** off. **Webhook params:**
| Name | Value |
| ---------------- | -------------------------------------------------------- |
| `title` | `{{doc_title}}` |
| `documentDate` | `{{created_year}}-{{created_month}}-{{created_day}}` |
| `sourceSystem` | `PAPERLESS` |
| `sourceId` | `{{doc_id}}` |
| `sourceInstance` | `https://paperless.example.com` (your Paperless address) |
- **Include document:** on. Paperless then sends the original file along
with the parameters, which is exactly what HealthLog expects.
- **Webhook headers:** `Authorization` = `Bearer hlk_…` (your document
token).
Optionally add a parameter `kind` with one of `DOCTOR_REPORT`,
`DISCHARGE_LETTER`, `LAB_RESULT`, `IMAGING`, `PRESCRIPTION`, `REFERRAL`,
`INSURANCE`, `VACCINATION` or `OTHER` if the workflow only ever sends one
kind of document. Without it, documents are filed as _Other_ and you can
change the type in HealthLog.
Tagging a document again, or editing it in Paperless, fires the workflow
again. HealthLog recognises the Paperless document id and answers "already
stored", so no second copy is made, and if you delete the document in
HealthLog, a later re-send does not bring it back. Each re-send still carries
the whole file, so it counts towards the token's hourly upload limit (see
For operators below).
**What the workflow is not for.** Paperless gives up on a webhook after
three quick retries and does not retry at all when a request takes longer
than five seconds. If you tag hundreds of documents at once, most of those
webhooks arrive while HealthLog is still asking them to slow down, and
Paperless drops them. Use the import script below for the existing archive
and let the workflow handle what comes after.
## 3. The archive: the import script
The script is a single file, `scripts/import-documents.mjs` in the
HealthLog repository. It works with Paperless-ngx 2.16 or later (API
version 9) and current Papra releases. It needs Node 22 and nothing else, and it runs on any
machine that can reach both systems. Download it:
```sh
curl -O https://raw.githubusercontent.com/MBombeck/HealthLog/main/scripts/import-documents.mjs
```
Tokens go in environment variables, never on the command line:
```sh
export HEALTHLOG_TOKEN=hlk_… # the document token
export PAPERLESS_TOKEN=… # Paperless: My Profile → API auth token
export PAPRA_TOKEN=… # Papra: an API key with documents:read and tags:read
```
**Paperless-ngx:**
```sh
node import-documents.mjs paperless \
--paperless-url https://paperless.example \
--healthlog-url https://health.example \
--tag HealthLog
```
**Papra** (the organization id is in the Papra address bar,
`/organizations/<id>/…`):
```sh
node import-documents.mjs papra \
--papra-url https://papra.example \
--papra-org <organization id> \
--healthlog-url https://health.example \
--tag Health
```
No Node on the machine? Run it in a throwaway container:
```sh
docker run --rm -it -v "$PWD:/w" -w /w \
-e HEALTHLOG_TOKEN -e PAPERLESS_TOKEN \
node:22-alpine node import-documents.mjs paperless …
```
Options:
- `--tag <name>` copies only documents with that tag. Recommended; without
it the script copies everything the source token can see.
- `--since YYYY-MM-DD` copies only documents dated on or after that day.
- `--kind LAB_RESULT` files everything as one type. `--kind-map
"Befund=DOCTOR_REPORT,Labor=LAB_RESULT"` picks the type by Paperless
document type or by Papra tag; anything unmatched gets `--kind`, or
_Other_.
- `--dry-run` lists what would be copied, with sizes and a total, and sends
nothing. Worth running first. It only talks to the source, so it needs no
HealthLog token and also lists documents HealthLog already has.
- `--ai-read` lets HealthLog read the documents with AI as they arrive (see
below). Off by default.
What it does:
- It copies one document at a time and keeps only one file in memory.
- It sends the original file (for Paperless, the original rather than the
archived PDF), the title, the document date, and the source id.
- The document date is the date the source has for the document. When the
source has none, the script uses the day the document was added there, and
lists those documents in its summary so you can correct the date.
- Running it again is safe. Before downloading a document the script asks
HealthLog whether it already has it, so documents already there are
neither downloaded nor sent again, and a re-run over a large archive is
quick. Documents you deleted in HealthLog stay deleted, also after they
are removed for good. The same goes for a file you had already uploaded
by hand: the import recognises it by its content (sending it once to
compare), and if you delete it later, the import leaves it deleted. Since
v1.39.3 a deleted document is also recognised by its content while it is
in the 30-day undo window: the same file arriving from another system or
under a new id is answered "deleted" and not stored again. After the purge
HealthLog keeps the ids it saw, not the content. An interrupted run simply
picks up where it stopped.
- Once HealthLog has refused one file as too large, the script skips any
further document the source already lists as larger (Papra lists sizes)
without downloading it.
- When HealthLog asks it to slow down, it waits as long as HealthLog says
and carries on. By default a document token may send 120 uploads an hour,
so an archive of a thousand documents takes a night. Every upload that
sends a file counts, including one HealthLog answers as already stored.
Documents the script recognises by asking first are not uploaded and do
not count; those questions draw on a separate allowance of 5,000 an hour
per token. When that allowance is spent, the script simply uploads the
document, which then counts as one upload. Uploads you make yourself in the web app or on
your phone are counted separately and are not held up.
- At the end it prints how many documents were imported, how many were
already there, how many you had deleted, and every document it skipped
with the reason. It exits with `0` when everything went through, `3` when
some documents were skipped, `1` when it had to stop (for example a
refused token, the vault switched off, or storage full), and `2` for a
mistake in the command.
### AI reading of imported documents
If you have turned on automatic AI reading of documents, HealthLog normally
reads each new document with your AI provider as it arrives. For an import
the script holds that back, so a whole archive does not turn into a
thousand AI requests at once. Imported documents still get a preview and
are searchable by their text where the file has a text layer.
HealthLog remembers that these documents were held back: turning on
automatic AI reading later does not send them to your AI provider either.
To have a document read, open it and choose **Read with AI** or **Generate
summary**; either ends the hold for that document. **Index all for search**
leaves held-back documents alone, so a scan without a text layer stays
unsearchable until you read it this way. Pass `--ai-read` if you do want
every imported document read as it arrives.
The Paperless workflow does not hold AI reading back unless you add the
parameter `aiRead` with the value `defer`: otherwise new documents are
treated like any other upload.
### Keeping Papra in step
Papra's webhooks only say that something changed, not what the file is, and
cannot carry a token, so Papra cannot post into HealthLog directly. Run the
script on a schedule instead, for example nightly with cron. Keep the tokens
in a file only you can read rather than in the crontab line:
```sh
# /opt/healthlog-import/env (chmod 600)
HEALTHLOG_TOKEN=hlk_…
PAPRA_TOKEN=…
```
```cron
15 3 * * * cd /opt/healthlog-import && set -a && . ./env && set +a && node import-documents.mjs papra --papra-url https://papra.example.com --papra-org <id> --healthlog-url https://health.example.com --tag Health --since 2026-01-01 >> import.log 2>&1
```
Documents already copied are recognised and skipped, so a nightly run only
adds what is new. `--since` keeps each run short.
## Storage
HealthLog keeps its own encrypted copy of each document, so an imported
archive takes space in both systems. The preview, text search, lab import,
the doctor report and sharing all need the file itself, which is why
HealthLog does not link to documents stored elsewhere.
The default storage limit is 1 GB per person, counting deleted documents
until they are removed for good 30 days later. Run the script with
`--dry-run` to see how much an import needs. An admin can raise the limit in
the admin area, for everyone or for one account. If storage runs out during
an import, the script stops and says so; raise the limit and run it again.
## Source ids
Documents are recognised by the pair of source system and document id:
`PAPERLESS` plus the Paperless document id, `PAPRA` plus the Papra document
id. Anything else is sent as `OTHER`, and `OTHER` is one shared set of ids
per account: if you push documents from two other systems, make sure their
ids cannot collide, for example by prefixing them (`nextcloud-123`,
`scanner-123`).
Since v1.39.3 a key can also name its instance: `sourceInstance`, the
address of the Paperless-ngx or Papra it came from (only its origin,
`scheme://host[:port]`, counts). With it, document 123 on one Paperless and
document 123 on another are two documents. The import script sends it
automatically; add it to a Paperless workflow as shown above. A key sent or
stored without an instance (everything imported with v1.39.2, or a workflow
without the parameter) matches that id on any instance of its system, so
nothing imported earlier is stored twice or brought back after a deletion.
The same file sent under a different id is stored once, and HealthLog
remembers the extra id for it, up to 20 extra ids per document. A 21st is
refused with `409` (`documents.inbound.sourceAliasLimit`) and nothing is
stored or remembered; the script lists such a document as skipped.
## For operators
`DOCUMENT_UPLOAD_LIMIT_PER_HOUR` sets how many uploads one document token
may send per hour (default `120`, clamped to 1–1000). Every upload that
sends a file counts, duplicates included. It applies to
document tokens only; uploads from the web app and the phone keep their own
limit of 60 per hour per person. Raise it to let a large import finish
faster; the storage limit still applies. The variable is on the
`docker-compose.yml` whitelist, so setting it in `.env` is enough.
+3 -2
View File
@@ -93,8 +93,9 @@ The Fitbit client id/secret are per-user (Settings), not env vars.
If Fitbit and another source (Withings, WHOOP, Apple Health) both supply the same
vital — resting heart rate, blood oxygen, body temperature or respiratory rate —
you may see both values until a future update settles on a single preferred
source.
the source priority ladder in **Settings → Sources** decides which one wins
per metric. FITBIT is ranked in every default metric ladder; override
per metric on that page.
## Disconnect
+1 -1
View File
@@ -134,7 +134,7 @@ triggers the verification + CASA requirements above.)
If Google Health and another source (Withings, WHOOP, Apple Health) both supply
the same vital — resting heart rate, blood oxygen, respiratory rate — the source
priority ladder in **Settings → Integrations → Sources** decides which one wins
priority ladder in **Settings → Sources** decides which one wins
per metric.
## Disconnect
+201
View File
@@ -0,0 +1,201 @@
# Home Assistant and other push integrations
HealthLog pulls from Withings, WHOOP, Fitbit, Oura, Polar and Strava over
OAuth. A local sensor has no such door: a BLE scale, a Garmin bridge or a
Zigbee thermometer lives in your own automation platform and has to push. This
page covers that path — a token you mint yourself, and the two endpoints it
reaches.
Nothing here is specific to Home Assistant. Node-RED, a cron job with `curl`,
or anything else that can set a header works the same way.
## Mint a token
Settings → API & Tokens → **Measurement ingest token**. Name it after the thing
you are pasting it into, because that name is what you will be reading later
when you decide whether to revoke it.
The token is shown **once**. It is stored as an HMAC, so there is no page that
can show it to you again — if you lose it, mint another and revoke the old one.
Tokens expire after a year by default. They appear in the API Tokens list on
the same page alongside every other credential on the account, and are revoked
there.
An account can hold at most ten live measurement tokens at once — across every
automation platform combined, not ten per platform. Past that, minting another
is refused with a 409 until you revoke one; revoking frees the slot
immediately, and an expired token stops counting on its own. It is not a
security boundary, just a backstop against a script stuck minting in a retry
loop, so a household running a scale, a watch bridge and a couple of scripts
will never come close.
## What the token can and cannot do
It can add readings, on your own record, through:
- `POST /api/measurements` — one reading, or a small array of them
- `POST /api/measurements/batch` — up to 500 entries per call
It **cannot** read a reading back, change or delete one, reach the export, or
mint another token. That is the point of it being a separate credential rather
than a general one: a container you do not fully trust — a Home Assistant
add-on, a script from a forum — holds something whose worst case is junk in
your own record, not your health history leaving the building.
It also cannot be pointed at somebody else's record. If an account has shared
their record with you, this credential still will not write to it; use the web
app for that.
## Readings are marked as coming from an external device
Rows written with this token carry `source: EXTERNAL`. They show a badge in the
measurements list and can be picked out with the source filter there, so months
later you can still tell which readings came off the scale and which you typed
in yourself. Three consequences worth knowing:
- You can correct them in the UI. Readings owned by a connected provider are
read-only, because the number is the provider's; these are your own hardware's
and stay editable.
- **The payload must not name a source at all.** The server decides it from the
token. A body carrying `"source": "MANUAL"`, `"source": "APPLE_HEALTH"` or
anything else is refused with a 422 rather than quietly relabelled — you get
told on the first call instead of discovering later that your rows say
something you did not ask for. The example below sends no `source`, which is
all you need.
- They do not claim to be from Apple Health. That source is half the
deduplication key the iOS app writes into, and a bridge borrowing it corrupts
the phone's sync rather than merely mislabelling a row. `EXTERNAL` gives these
writes their own namespace instead, so a bridge's ids can never collide with
the phone's.
For the same reason, a push through this token does not move the native sync
checkpoint. Your phone's own sync window is unaffected by your scale.
If you were already pushing readings with an older build, those rows stay
`MANUAL` — there is no way to tell them apart retroactively, which is the whole
reason for this label. If a re-push of the same entries produces duplicates,
delete the older pair.
## Home Assistant example
Add a `rest_command` to `configuration.yaml`. Keep the token in
`secrets.yaml`, not here.
```yaml
rest_command:
healthlog_measurement:
url: "https://healthlog.example.com/api/measurements"
method: POST
headers:
Authorization: !secret healthlog_token
Content-Type: "application/json"
payload: >-
{
"type": "{{ type }}",
"value": {{ value }},
"measuredAt": "{{ now().isoformat() }}"
}
```
```yaml
# secrets.yaml
healthlog_token: "Bearer hlk_replace_me"
```
Then call it from an automation. This one forwards a scale whenever it reports
a new weight:
```yaml
automation:
- alias: "Push weight to HealthLog"
trigger:
- platform: state
entity_id: sensor.bathroom_scale_weight
condition:
- condition: template
value_template: "{{ trigger.to_state.state not in ['unknown', 'unavailable'] }}"
action:
- service: rest_command.healthlog_measurement
data:
type: WEIGHT
value: "{{ trigger.to_state.state | float }}"
```
The `condition` is not decoration. Home Assistant sensors publish `unknown` and
`unavailable` as ordinary states, and forwarding one produces a 422 on every
restart.
## Measurement types
`type` is an enum, not free text. Some of the ones a Garmin or scale
integration tends to have:
| What the sensor reports | `type` | Unit expected |
| ------------------------------ | ------------------------ | ------------- |
| Weight | `WEIGHT` | kg |
| Body fat | `BODY_FAT` | % |
| Resting heart rate | `RESTING_HEART_RATE` | bpm |
| Heart-rate variability (SDNN) | `HEART_RATE_VARIABILITY` | ms |
| Heart-rate variability (RMSSD) | `HRV_RMSSD` | ms |
| Blood oxygen | `OXYGEN_SATURATION` | % |
| VO₂ max | `VO2_MAX` | ml/kg/min |
| Respiratory rate | `RESPIRATORY_RATE` | breaths/min |
| Sleep duration | `SLEEP_DURATION` | minutes |
| Steps | `ACTIVITY_STEPS` | count |
| Body temperature | `BODY_TEMPERATURE` | °C |
Units are derived server-side from the type, so send the number in the unit
above and do not send a `unit` field. The full enum is in
`docs/api/openapi.yaml` under `MeasurementType`.
## Sending several readings at once
A bare array writes up to five readings in one request — the shape to use for
blood pressure, which is two rows:
```bash
curl -X POST https://healthlog.example.com/api/measurements \
-H "Authorization: Bearer hlk_..." \
-H "Content-Type: application/json" \
-d '[
{ "type": "BLOOD_PRESSURE_SYS", "value": 118, "measuredAt": "2026-03-14T07:20:00Z" },
{ "type": "BLOOD_PRESSURE_DIA", "value": 76, "measuredAt": "2026-03-14T07:20:00Z" }
]'
```
For a backfill of hundreds of rows, use `/api/measurements/batch` instead. It
takes up to 500 entries and reports a per-entry status so a partial failure
tells you which rows to retry.
## Retries and duplicates
Send an `Idempotency-Key` header with a value your automation can reproduce for
the same reading. A retry with the same key and the same body returns the
original response instead of writing a second row. A different body under the
same key is a different reading and is written:
```yaml
headers:
Authorization: !secret healthlog_token
Content-Type: "application/json"
Idempotency-Key: "{{ type }}-{{ now().strftime('%Y-%m-%dT%H') }}"
```
Independently of that, a reading with the same type, timestamp and source as an
existing row is refused with a 409 — so a duplicate push is a visible error
rather than a duplicated data point.
## When it stops working
| Response | What it means |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `401` | The token is wrong, revoked, or expired. Mint a new one. |
| `403` | The endpoint is outside the token's scope — check you are calling one of the two above and not a read — or the operator has switched the API off instance-wide. |
| `409` | A reading with this type, timestamp and source already exists. |
| `422` | The payload is wrong: an unknown `type`, a non-numeric `value`, an `unavailable` sensor state, or an entry naming `APPLE_HEALTH`. |
| `429` | Too many requests. The batch route allows 60 calls per minute. |
The response envelope is `{ "data": ..., "error": null }` on success and
`{ "data": null, "error": "<message>" }` on failure, so logging `error` from
the body will usually say exactly what was wrong.
+7
View File
@@ -28,9 +28,16 @@ Each entry is an exact normalized `scheme://host:port` trust unit:
rejected;
- approving one hostname does not approve subdomains, sibling hosts, or a
different port; and
- the unspecified address, link-local and the cloud-metadata range cannot
be listed, and a listed name that resolves there is refused at connect
time; loopback (`http://localhost:1337`, `http://127.0.0.1:1337`) stays a
valid grant for a host-networking deployment, exactly as before; and
- any malformed non-empty entry fails evaluation instead of silently
weakening the configured policy.
The grammar is shared with `NOTIFICATION_PRIVATE_ORIGINS`, the same grant
for webhook and ntfy targets (`docs/self-hosting/notifications.md`).
Do not put a Nightscout API token, capability URL, health data, or a URL
containing credentials in the allowlist. Restart the application after
changing the environment.
+20 -16
View File
@@ -73,7 +73,7 @@ only when the OAuth callback must differ from that default.
When HealthLog calls Withings `Notify.subscribe()` for a newly-linked
account, it hands Withings the callback URL constructed by
`getWithingsWebhookCallbackUrl()` (`src/lib/withings/sync.ts:38-48`).
`getWithingsWebhookCallbackUrl()` (`src/lib/withings/sync.ts`).
The shape is:
```
@@ -107,8 +107,9 @@ With the credentials saved in Settings, open
5. The settings page now shows **Connected** with the timestamp of
the last successful sync.
Subsequent syncs run automatically on every webhook delivery plus a
safety-net cron pull every few hours.
Subsequent syncs run automatically on every webhook delivery plus an
hourly safety-net cron pull (measurements at :00, sleep at :15, ECG
at :41).
## Source-priority interaction
@@ -117,7 +118,7 @@ for point measurements (weight, BP, pulse, body fat, body
temperature, SpO₂, VO₂ max) and **APPLE_HEALTH ≻ WITHINGS ≻ MANUAL**
for cumulative metrics (steps, active energy, distance, flights,
sleep, HRV, resting HR). The defaults live in
`src/lib/validations/source-priority.ts:205-220`.
`DEFAULT_SOURCE_PRIORITY` in `src/lib/validations/source-priority.ts`.
Concrete consequences if you run Withings alongside an Apple Health
import:
@@ -130,7 +131,7 @@ import:
when Apple Health is also linked, so the Apple Health stream wins
for the cumulative axis. The Withings rows stay in the DB.
Override per-user via the Sources section of `/settings/thresholds`.
Override per-user via Settings → Sources (`/settings/sources`).
## Troubleshooting
@@ -169,7 +170,7 @@ fixes the mismatch by updating the URL Withings holds.
Withings revokes refresh tokens on password change, app un-authorise,
or after extended inactivity. The `WithingsConnection` row flips to
`error_reauth` status and the scheduled sync no-ops until the user
re-runs the OAuth flow (`src/lib/withings/sync.ts:155-161`).
re-runs the OAuth flow (`src/lib/withings/sync.ts`).
Click **Connect Withings** again from the settings page; the
callback exchanges fresh tokens and the next sync runs through the
last 30 days of history to catch up.
@@ -179,20 +180,23 @@ last 30 days of history to catch up.
The Settings page **Disconnect** button:
1. Calls `POST /api/withings/disconnect`.
2. Server-side: revokes the access token via Withings'
`Notify.revoke`, deletes the `WithingsConnection` row, and audits
the action.
2. Server-side: unsubscribes the webhook categories (best-effort
Withings `Notify` revoke per category), deletes the
`WithingsConnection` row with its stored encrypted tokens, and
audits the action. The Withings-side grant itself persists until
the user un-authorises HealthLog in their Withings account.
3. Existing `Measurement` rows tagged `source = WITHINGS` stay in
the database — disconnect does not delete data. Re-linking the
same Withings account merges back onto the same metric
timeline; the upsert path matches on `(userId, type, measuredAt,
source)` so previously-synced rows update in place.
## Admin probe
## Connection test
`POST /api/integrations/withings/test` (admin-only) runs a
read-only round-trip against the user's stored credentials and
returns the latency in milliseconds. Use it from the admin panel
when a user reports stale data — a green test plus a stale
`lastSyncedAt` usually means the webhook URL Withings holds is out
of sync (re-subscribe per the steps above).
`POST /api/integrations/withings/test` runs a read-only round-trip
against the calling user's own stored credentials and returns the
latency in milliseconds (rate-limited to 5/min per user). The
Withings settings card surfaces it as the connection test. Use it
when data looks stale — a green test plus a stale `lastSyncedAt`
usually means the webhook URL Withings holds is out of sync
(re-subscribe per the steps above).
+11 -3
View File
@@ -7,6 +7,12 @@ new env var in §Environment variables below has a safe default. This
guide documents what changes for operators and integrators, in case
you're extending the API or scaling the deployment.
> Historical note: route paths on this page reflect v1.4. Several have
> since moved or gone: `/api/admin/status-overview` is now
> `/api/admin/status`, the Umami probe is
> `/api/admin/monitoring/umami-test`, and the moodLog integration was
> removed entirely.
## TL;DR
```bash
@@ -64,9 +70,11 @@ worker`. Default `all` keeps the single-container behaviour.
- **`ENCRYPTION_KEY`** _(unchanged)_ — still honoured as a fallback
when `ENCRYPTION_KEYS` is empty. No action needed for existing
installs.
- Rotation: `pnpm tsx scripts/rotate-encryption-key.ts <newKeyId>`
re-encrypts every ciphertext under the new key without downtime.
Walk-through in `docs/ops/encryption-key-rotation.md`.
- Rotation: **Admin → Encryption → Rotate now** re-encrypts every
ciphertext under the new key without downtime; the script
`scripts/rotate-encryption-key.ts` does the same from a source checkout.
Walk-through in `docs/ops/encryption-key-rotation.md` (the current
playbook).
### Off-host backup target _(optional)_
+156
View File
@@ -0,0 +1,156 @@
# Apple Health walking-distance repair
`scripts/repair-apple-health-distance.ts` heals walking distances that the
`export.zip` import stored a thousand times too small.
## The defect
Apple stamps every quantity `<Record>` in an `export.xml` with the account's
own display unit: a metric archive reports `HKQuantityTypeIdentifierDistance-
WalkingRunning` in `km`, an imperial one in `mi`. Until this release the record
mapping accepted that attribute and never read it, so the day's total was
folded as if the number were already metres. A 2.484 km day landed as
`2.484 m`, and an imported decade reads as a couple of metres walked. The
workout path was never affected — it converted its own distance unit.
The code fix converts the record's unit before storage, so every import from
this release on is correct. This script is for the rows already in the
database.
## Prefer a re-import
If the account still has its `export.zip`, **re-import it**. The archive fold
UPSERTs the same `stats:<identifier>:<day>` rows, so a re-import on the fixed
build rewrites every affected day with the right number, needs no flags, and
also repairs rows this script deliberately leaves alone (see the criterion
below). The script exists for accounts that no longer have the archive.
**An account that has been re-imported must not then be repaired.** The
re-import already fixed it. Its rows keep the same `EXPORT_XML_SOURCE_MAX`
stamp and the same `stats:` external id, and they carry no audit row, so the
criterion selects them exactly as it selects a broken account — the stamp
proves where a row came from, not which build imported it. Multiplying them
again turns a 2.484 km day into 2484 km. The script refuses such an account on
its own (any day whose value would leave the plausible range after the
multiply stops the whole account), but that guard fires on the big days: keep
the two apart yourself before you type `--apply`.
## Which rows it touches
Only rows carrying the stamp the archive importer itself writes:
| Column | Value |
| ------------------------ | ------------------------------------------------------------ |
| `type` | `WALKING_RUNNING_DISTANCE` |
| `source` | `APPLE_HEALTH` |
| `aggregation_provenance` | `EXPORT_XML_SOURCE_MAX` |
| `external_id` | `stats:HKQuantityTypeIdentifierDistanceWalkingRunning:<day>` |
| `deleted_at` | `NULL` |
`EXPORT_XML_SOURCE_MAX` is written in exactly one place in the tree — the
archive fold — and the `stats:` external id is minted for that same fold, so
the pair is a proof of origin rather than a guess. Nothing is ever selected
because a value "looks too small".
Deliberately out of scope:
- Rows a native iOS sync has since overwritten (`HEALTHKIT_STATISTICS`): their
value came from HealthKit's own statistics query and is correct.
- Rows whose provenance is `LEGACY_UNKNOWN` or NULL: an archive origin cannot
be proven for them. Re-import the archive to repair those.
## Run a dry-run first
Always, and read it. The dry run is where the decision is made, not a
formality in front of a decision already taken: it is the only place the
script shows you real numbers from the account before it changes them. If the
worked example does not match what that person's Health app shows for that day,
the run is wrong and `--apply` will make it permanent.
The default mode reports and never writes:
```bash
# from a source checkout, with DATABASE_URL pointing at the instance
pnpm dlx tsx scripts/repair-apple-health-distance.ts
```
It prints one line per account: how many rows would be repaired, the date span
they cover, one worked example (`2.484 m -> 2484 m`), and any row whose
repaired value would leave the plausibility range.
This script imports the application dependency graph, so it runs from a source
checkout, not through the production image's `healthlog-tsx` launcher.
## Name the archive's unit
The stored row keeps no record of the unit its archive was written in — that
is the defect — so the operator names it. `--unit=km` is the default and is
what the Health app writes in every metric locale; pass `--unit=mi` for an
imperial archive:
```bash
pnpm dlx tsx scripts/repair-apple-health-distance.ts --unit=mi
```
Check the dry-run's worked example against what the account's Health app shows
for that day before applying. If the two units are mixed across accounts, run
the script once per unit with `--apply` and confirm each account's example
first.
## Apply
Take a backup first — `docs/ops/backup-restore.md`. The multiply is in place
and has no reverse operation: once an account is written wrong, the database
copy you took beforehand is the only way back.
```bash
pnpm dlx tsx scripts/repair-apple-health-distance.ts --apply
```
Per account, in one transaction: every selected row multiplied by the unit's
metre factor, `sync_version` incremented and `updated_at` bumped so paired iOS
clients pick the rows up on their next delta sync, and an audit row
(`measurement.apple_health_distance.repaired`) recording the unit, the factor
and the row count. The DAY/WEEK/MONTH/YEAR rollups and the cached status
insights for the touched days are recomputed afterwards, outside that
transaction.
If that recompute fails, the rows are right and every chart is not, and no
later run of this script would notice — it skips a repaired account. So the
audit row is written with `rollupsRefreshed: false` and only flipped to `true`
once the recompute has returned. A run that could not finish it prints the
account and the command to re-run, exits non-zero, and a later dry run repeats
the warning until the backfill has been run:
```bash
pnpm dlx tsx scripts/backfill-rollups.ts --user <userId>
```
A row whose repaired value would leave the plausible range (0–200 000 m)
refuses the **whole account**: nothing is written, the offending rows and the
reason are printed, and the run moves on to the next account. One such row is
evidence the account is not the 1000x class — a re-imported account looks
exactly like this — and repairing the rest of it would multiply days that were
already right.
## It runs once per account
The audit row is written inside the same transaction as the update, and an
account that carries it is skipped. A second run reports the account as already
repaired and changes nothing, so the multiplier can never be applied twice.
## Verify
```sql
SELECT date_trunc('year', measured_at) AS year,
round(avg(value)) AS avg_metres_per_day
FROM measurements
WHERE user_id = '<userId>'
AND type = 'WALKING_RUNNING_DISTANCE'
AND aggregation_provenance = 'EXPORT_XML_SOURCE_MAX'
GROUP BY 1 ORDER BY 1;
```
A plausible daily average is thousands of metres. Single digits mean the rows
were not repaired; millions mean a factor was applied twice, which the audit
row is there to prevent.
+4 -2
View File
@@ -17,7 +17,8 @@ that captures how many failures the bucket ledger has accumulated since
the last success.
The persistent-failure alert dispatcher in
`src/lib/integrations/status.ts:453` uses `Math.max(...buckets)` — the
`src/lib/integrations/status.ts` (the v1.4.43 W14 block) uses
`Math.max(...Object.values(buckets))` — the
**max** across the three buckets. A 3-deep persistent streak pages even
when the transient bucket is empty, and a flapping integration that
ping-pongs between transient and reauth_required never trips a
@@ -44,7 +45,8 @@ we want to wake someone up for.
If you see an audit row with `attemptNumber >= threshold` but no alert
was dispatched, check the per-bucket counts on
`IntegrationStatus.failureBuckets` for that user/integration pair. The
`IntegrationStatus.consecutiveFailuresByKind` (DB column
`consecutive_failures_by_kind`) for that user/integration pair. The
sum may be high while every individual bucket sits below the threshold.
This is working as designed; manually investigate only if a single
bucket is at or above the threshold and `alertedAt` is unset (broken
+403 -31
View File
@@ -16,29 +16,86 @@ container (queue `data-backup-offhost`). Object key layout:
```
magic = "HLBK" (4 bytes, ASCII)
version = 0x01 (1 byte)
version = 0x04 (1 byte)
keyIdLen, keyId (1 byte + 12 ASCII hex: the first 12 hex digits of SHA-256(key))
iv = 12 random bytes (AES-GCM nonce)
authTag = 16 bytes (AES-GCM tag)
ciphertext = N bytes (AES-256-GCM, key = BACKUP_ENCRYPTION_KEY)
plaintext = JSON dump (UTF-8)
ciphertext = N bytes (AES-256-GCM over gzip(JSON dump), key = BACKUP_ENCRYPTION_KEY,
associated data = "healthlog/offhost-backup/v4|<object key>")
authTag = 16 bytes (AES-GCM tag, trailing)
```
Version `0x04` (from v1.39.3) adds two things. The key id says which off-host
key an object needs, so a reader holding a retired key as well finds the right
one. The associated data is the object's own key in the bucket,
`YYYY-MM-DD/user-<id>.json.enc`: an object copied to another account's name or
another date does not decrypt, where before it opened as if it belonged there.
The restore script passes the key it downloaded, so nothing changes for an
operator.
Four versions exist in the wild and all four restore. `0x01` encrypted the
JSON directly and `0x02` gzipped it first; both carry the tag in FRONT of the
ciphertext, which is what made them impossible to write a piece at a time —
GCM only produces the tag once the last block is in, so a leading tag means the
whole object has to exist before its first byte can be sent. `0x03` moves the tag to the end and changes nothing else: it still
covers every ciphertext byte, and the reader still verifies it before returning
a single byte of plaintext. Objects already in your bucket stay readable, and
the restore script needs no flag to tell them apart.
## Required env vars
| Var | Required | Notes |
| ----------------------- | -------- | -------------------------------------------------------------------- |
| `BACKUP_ENCRYPTION_KEY` | yes | 64 hex chars or 32-byte base64. **Different from `ENCRYPTION_KEY`.** |
| `BACKUP_S3_ENDPOINT` | yes | e.g. `https://<account>.r2.cloudflarestorage.com` |
| `BACKUP_S3_BUCKET` | yes | |
| `BACKUP_S3_ACCESS_KEY` | yes | |
| `BACKUP_S3_SECRET_KEY` | yes | |
| `BACKUP_S3_REGION` | no | defaults to `auto` (Cloudflare R2) |
| `BACKUP_RETENTION_DAYS` | no | defaults to `30` |
| Var | Required | Notes |
| --------------------------------- | -------- | ----------------------------------------------------------------------------------- |
| `BACKUP_ENCRYPTION_KEY` | yes | 64 hex chars or 32-byte base64. **Different from `ENCRYPTION_KEY`.** |
| `BACKUP_S3_ENDPOINT` | yes | e.g. `https://<account>.r2.cloudflarestorage.com` |
| `BACKUP_S3_BUCKET` | yes | |
| `BACKUP_S3_ACCESS_KEY` | yes | |
| `BACKUP_S3_SECRET_KEY` | yes | |
| `BACKUP_S3_REGION` | no | defaults to `auto` (Cloudflare R2) |
| `BACKUP_RETENTION_DAYS` | no | not read by the app; the number for your bucket's lifecycle rule |
| `BACKUP_ENCRYPTION_PREVIOUS_KEYS` | no | retired off-host keys, comma-separated, read only (see "Rotating the off-host key") |
## Bucket lifecycle (recommended)
## Bucket permissions
The worker prunes objects older than `BACKUP_RETENTION_DAYS`, but the
storage provider's lifecycle rule is the canonical safety net:
The worker needs `PutObject`, `GetObject`, `ListBucket`, `DeleteObject` and
`AbortMultipartUpload`. On Cloudflare R2 the **Object Read & Write** token
covers all of them.
`DeleteObject` is needed because the app deletes objects in two cases, and
only those:
- **An account is deleted, or its data is wiped.** Deleting an account,
deleting a managed profile and "Delete all data" each write a deletion
request in the same transaction as the deletion. The `offhost-backup-purge` job lists the bucket, deletes every
`YYYY-MM-DD/user-<id>.json.enc` of that account and removes the request once
nothing of the account is left. It runs right after the deletion and again
every night at 03:40. A copy the nightly upload was writing while the account
was deleted is removed by the upload itself.
- **The connection test** deletes its own `_healthcheck/<ts>.bin`.
The admin wipe of every account deletes nothing in the bucket. It is you
clearing your own host, the bucket is yours, and its copies are the way back
from a wipe pressed by mistake. If you are handing the host on, empty the
bucket yourself.
Earlier versions of this page said the worker never deletes an object. That
was the design until v1.39.3, and it meant a deleted account's copies stayed
in the bucket for as long as the lifecycle rule kept them, or forever without
one. If the bucket refuses the delete (a credential without `DeleteObject`),
the request stays, the job retries it every night, and **Admin → Backups →
Off-host** shows how many deletions are outstanding and the bucket's answer.
`AbortMultipartUpload` only reaches an upload the same worker started and is
what clears the parts of a run that failed halfway. Without it, a failed
upload leaves parts that are billed and do not show in a bucket listing.
## Bucket lifecycle (required for retention)
The app does not expire objects by age, and nothing in the app reads
`BACKUP_RETENTION_DAYS`. Expiry is the storage provider's lifecycle rule, set
to match the number you wrote there. Without one, every nightly copy of every
account is kept forever. **Admin → Backups → Off-host** reads the bucket's
lifecycle configuration and says so when there is none, or when the credential
may not read it (grant `GetLifecycleConfiguration` to let it check):
```
Filter: "" (all objects)
@@ -54,12 +111,15 @@ performs a 1-byte PUT + GET round-trip and returns:
```json
{
"endpoint": "https://...r2.cloudflarestorage.com",
"bucket": "healthlog-backups",
"region": "auto",
"putLatencyMs": 142,
"getLatencyMs": 38,
"ok": true
"data": {
"endpoint": "https://...r2.cloudflarestorage.com",
"bucket": "healthlog-backups",
"region": "auto",
"putLatencyMs": 142,
"getLatencyMs": 38,
"ok": true
},
"error": null
}
```
@@ -92,14 +152,317 @@ The script downloads the object, decrypts it, and writes the JSON dump
to disk. Importing the JSON back into a HealthLog instance is left to
the operator (use `prisma db seed` or a custom script).
Restoring is not streamed and does not need to be. It holds the whole document,
because the next thing anyone does with a backup is parse it as one JSON
object, and handing back plaintext the auth tag has not yet covered would trade
the authentication for memory. It runs on your machine rather than in the
container, so give it room: a record of several hundred thousand measurements
decompresses to a few hundred megabytes, and
`NODE_OPTIONS=--max-old-space-size=2048` in front of the command is enough for
a 445 000-measurement account.
### Restoring from the backups console
An admin can restore a stored snapshot from the browser instead of the shell.
`/admin/backups` lists one row per account and per backup type: **Backup now**
enqueues the `data-backup` pass for every account on the instance, **Download**
decrypts one snapshot and hands back the JSON, and **Restore** opens a dialog
that first shows what the file carries and then requires the word `RESTORE` to
be typed before it will run. The restore targets the account the snapshot was
taken for, never the admin running it, and it refuses a file whose declared
owner does not match the stored row. Instance-wide settings ride along only
when you tick _Also restore instance settings_ in the dialog; leave it clear to
restore the account alone.
A stored copy this instance can no longer open — the key that wrote it dropped
from `ENCRYPTION_KEYS` one rotation too early, or bytes that are not the ones
written — is refused by all three buttons with `422` and
`meta.errorCode = backup.payload.undecryptable`, before anything is read back.
### What a backup deliberately does not carry
Every credential-shaped row is left out, and this is not an oversight to fix:
API tokens, trusted devices, step-up elevations, known devices, clinician share
links, and the account grants behind shared record access. Restoring data is
rolling a record back to a known state. Restoring an authorization is different
in kind, because a grant the owner revoked on Tuesday would come back alive out
of Monday's file with nobody deciding it and neither person told.
What this means in practice depends on where you restore to.
**Onto the same instance.** Nothing changes. The restore replaces the account's
data tables and does not touch grants, tokens or devices, so shared access
carries on exactly as it was. Somebody who had read access before the restore
still has it afterwards, now looking at the restored data.
**Onto a fresh instance.** None of it comes with the file. Nobody has access to
anybody's record, every API token has to be reissued, every device re-trusted,
and both people have to invite and accept again before sharing works. That is
the fail-safe direction — access lost, never access resumed — and re-consenting
is the right amount of ceremony for handing someone your health record a second
time. Plan for it rather than discovering it.
The full per-model reasoning lives in `src/lib/export/backup-plan.ts`, where
every excluded model carries a written verdict and a structural test refuses to
let a new model land without one.
## Container memory (the nightly off-host job)
This is the part that bites, and it bit the nightly job a release after it bit
the weekly one. The job runs inside the app process, so V8's heap limit is the
app's heap limit. Node sizes it from the container's memory cap: 1 GB gives a
524 MB old-space limit, the compose default of 1536m (since 1.40.1) gives 792 MB. A long-lived Next.js server is already holding a large share
of that before the job starts.
The uploader used to build the whole backup JSON as one string, gzipped
that whole string, ran a whole-buffer cipher pass over the result and handed
the finished buffer to a single `PutObject` — four full copies of the record
alive at once. On an account of 445 000 measurements the JSON alone is 242 MB,
and the first configured run took the container down seventeen seconds in with
`FATAL ERROR: Reached heap limit`. Because the job shares the app process, one
account's size restarted the instance for everybody on it.
It streams now. The JSON is produced a page at a time, gzip and the cipher
consume it as it arrives, and the object goes up as a multipart upload that
holds two 8 MB parts. What the process holds is fixed by that pipeline's shape
rather than by the size of the record going through it: measured on the same
445 000-measurement account under `--max-old-space-size=450`, the old path
died and the new one finished holding tens of megabytes, writing a 9.1 MB
object that restores to the identical record.
One ceiling remains, and it is structural rather than a memory bound: a
multipart upload carries 10 000 parts, so 80 GB is the largest object one
account can produce. Past it the account's backup fails with a clear refusal,
is counted in the run's `offhost_backup_oversized` meta, and the pass carries
on with everybody else.
### Reading a failed run
A nightly run that could not upload for **anybody** now fails the pg-boss job
instead of reporting success. This is the case wrong credentials, a missing
bucket and an unreachable endpoint all land in, and the target's own sentence
rides out as the failure cause — `The request signature we calculated does not
match the signature you provided`, `The specified bucket does not exist`,
`connect ECONNREFUSED`. Check `offhost_backup_uploaded` against
`offhost_backup_total_users`: before this change a run where every single
upload failed still read `ok: true`, so a bucket could stay empty while the
jobs page looked healthy.
A run where SOME account got a copy still succeeds, with the rest counted in
`offhost_backup_failed`. Failing the whole queue over one account's object
would re-upload everybody's on every retry.
### A run the process died under
Both backup jobs carry a pg-boss heartbeat of five minutes. While a run is
alive the worker refreshes it; a run whose process died (a restart, or a
container killed for memory) stops refreshing, and pg-boss fails the job with
`job heartbeat timeout` within minutes instead of leaving it `active` until its
two- or four-hour expiry. The retries the queue already allows then pick it up.
Each pass also notes when it started and when it got past every account
(`backup_pass_attempts`). An account whose last attempt started and never
finished is the one the process died under, and the next run takes it last, so
one record too large for the container cannot keep every account after it from
a copy. **Admin console → Backups** shows when the run in progress started and
names such an account under both the weekly and the off-host card. Seeing the
same account there twice means it needs more memory than the container has.
### Which account has no copy
The counts above say how many accounts were uploaded, never which. An account
whose object has failed every night for a month reads as `99 uploaded, 1
failed` each time, which looks like weather.
**Admin console → Backups → Off-host copies** answers it per account: when this
host last put that account's encrypted copy in the bucket, how big it was, and
how that compares with the nightly schedule. **Fresh** is inside one run,
**due** means one run produced nothing for that account, **stale** means two
did not, **never** means a run walked the account and no object has ever
landed for it, and **no record yet** means no run has recorded the account at
all. On a host without `BACKUP_S3_*` the card says off-host backup is not
configured and stops there.
The ledger starts empty on the release that adds it, so on a host that has
been uploading nightly for months every account reads **no record yet** until
the first run after the upgrade. That is the ledger having no history, not the
bucket being empty — which is why it is a separate word from **never**, and
why the row says so rather than claiming nothing has ever reached the bucket.
Each verdict carries six hours of slack on top of the schedule's own 24, and
that slack is load-bearing on two nights. The cron runs at 02:30 Europe/Berlin,
so on the DST fall-back Sunday two consecutive runs are 25 hours apart; and the
timestamp is when _that account's_ object landed, so on a cohort walked one
account at a time an account reached later tonight than last night drifts by
hours. Without the slack a healthy host would paint its whole cohort **due**
once a year.
The verdicts come from a ledger the worker writes when the object lands
(`offhost_backup_state`), not from a listing of the bucket. Keep the worker's
grant as documented — PutObject, GetObject, AbortMultipartUpload — and the card
still tells the truth. A row that goes stale while the run reports success is
that account's object being refused, and the reason is in the run's
`offhost_backup_failures` meta.
## The weekly in-database backup (`data-backup`)
Separate from the off-host job above, and easy to confuse with it. A second
pg-boss job writes one `WEEKLY_AUTO` copy per user into the database, the same
JSON document, gzipped and then encrypted under `ENCRYPTION_KEY` /
`ENCRYPTION_KEYS`, staying inside the instance. It is what
`/api/admin/backups/<id>/restore` reads, and an uploaded backup file is stored
the same way.
### How a copy is stored
From v1.39.2 a copy is kept as ordered pieces of about a megabyte in
`data_backup_chunks`, with the list of pieces on its `data_backups` row. The
writer produces the JSON a page at a time, gzips it as it goes and seals each
megabyte of gzip output on its own with AES-256-GCM. Reading it back (restore,
preview, download) takes the pieces one at a time. Nothing on either path holds
the whole copy, so the size of a copy has nothing to do with the app's memory.
Measured on an account of 2.6 million readings in a 1 GB container,
with the web server and the worker in one process: the backup took 87 seconds
and stored 97 MB in 96 pieces, the preview 20 seconds, the download of the
1.4 GB file 25 seconds, and the restore 264 seconds, which gave back every
reading exactly. The container peaked at 567 MB and did not restart. What the
backup, preview and download hold on top of the running app stays at a few tens
of megabytes and does not grow with the account. A 512 MB container is too
small for the app itself: its heap limit is 259 MB and a backup of any account,
even one with 130 000 readings, runs it out of heap.
Each piece carries, inside its encryption, which copy it belongs to, its
position, and whether it is the last. Before a restore deletes anything, every
piece is checked: a piece that is missing, moved, altered, taken from another
copy, or a copy that stops short of its last piece is refused with
`backup.payload.undecryptable`, and the account is left as it was.
The write is one transaction. Until the new copy is complete the previous one
stays in place and readable; a run that fails halfway leaves it untouched. A
second backup of the same account started while one is running (a manual run
during the weekly one, say) waits for the first to finish and then replaces
its copy; neither leaves a partial copy behind.
While a restore of an account's copy is queued or running, the weekly and
manual backup leave that account's copy alone and back up everyone else. The
run's `users_skipped_restoring` meta counts such accounts; the next run
replaces the copy as usual. If a copy is replaced anyway while it is being
read (a download or preview in progress when the weekly run finishes), the
reader answers `409` with `backup_changed` and "The backup was replaced by a
newer one while it was being read", not the undecryptable error, and a restore
rolls back with nothing changed. Start it again to use the new copy. A
download already sending when this happens stops partway; download again.
Copies written before v1.39.2 are a single value in `data_backups.data` and
still restore, preview and download as they did. The next weekly run replaces
the weekly copy in the new form, and a key rotation (below) converts every
remaining one, including uploaded copies. Until then those older copies are
read as one value, as before, which needs the memory they needed when they were
written.
Migration 0352 cannot be undone by going back to v1.39.1. That release reads
only the single value, so it finds a copy in pieces empty, and if it writes a
weekly copy into a row that has pieces, the row holds both forms. v1.39.2 then
refuses to read that row, because nothing says which of the two is current
("This backup holds both a single stored value and pieces ..."); the next
weekly backup replaces it. If you must go back, restore the database backup
you took before upgrading.
### The size limit
The one limit left is on storage: a copy of one account may take at most
`BACKUP_MAX_STORED_MB` megabytes (default 2048). It exists so a runaway copy
fails with a message instead of filling the database volume, which holds the
old and the new copy side by side while a backup runs. An account past it fails
for that account alone, is counted in the run's `users_failed` and
`records_oversized` meta, and keeps its previous copy; the pass carries on with
everybody else. The message names the setting. Raise it in `.env`, recreate the
app container, and make sure the database volume has room for two copies of
that size.
Before v1.39.2 the limit was a fifth of the app's heap, 105 MB in a 1 GB
container, because the copy had to pass through the app as one value. An
account with 1.75 million readings was past it, and the only way round was more
memory. That is no longer the case: `records_oversized` means the storage limit,
never memory.
The writer deliberately reads no heap gauge. A version that did shipped in
v1.38.6 and compared the whole process's live usage, garbage included, against
80 % of the limit. A Next.js server that has been up for a week sits at 400 MB
of largely collectable heap, so the weekly pass aborted every account on the
first chunk, including one whose whole stored copy is 1.2 MB, and reported
success while doing it. If you are on v1.38.6, a `data-backup` run that finishes
in seconds having backed up nothing is that defect and not your record.
### Key rotation
Rotation reaches a stored backup's envelope and nothing inside it. The
content of a disaster-recovery backup is the database's ciphertext, carried
as it is stored, and a restore writes it back verbatim: a note, a document or
a coach message inside a copy taken before a rotation still needs the key the
rotation retired. The same holds for every copy in the off-host bucket and for
every file an operator has downloaded. So the rule is: **keep a retired
`ENCRYPTION_KEYS` entry until no backup you may still restore needs it.**
**Admin → Encryption → Keys the backups still need** lists, per key id, the
stored copies that need it with the oldest date, and when the last off-host
copy needing it expires under the bucket's lifecycle rule. Copies written
before v1.39.3 did not record their keys and are listed as such.
Every restore, the restore preview, the admin upload and the monthly drill
check this before anything is changed: a file whose content needs a key this
server does not have (or an id whose key material differs) is refused with the
key id named, and the account is left as it was.
Re-encrypting the content of stored backups during rotation was considered and
not done: it would mean decrypting, parsing, re-encrypting and re-writing every
copy in full, and it still could not reach the off-host copies or downloaded
files, so the rule above would be needed regardless.
`scripts/rotate-encryption-key.ts` and the rotation in the admin console
re-seal every piece under the active key, in small batches, without reading
the backup inside. The link between a piece, its copy and its position is
inside the encryption, so it comes through rotation unchanged.
A copy still in the older single-value form (any of them, including the
`~hlgcm1.` form v1.38.6 to v1.39.1 wrote) is not re-sealed in place, which would need the
whole copy in memory several times over. Rotation converts it into pieces
under the active key instead, one copy at a time, reading the stored value a
few megabytes at a time; the copy keeps its date. The conversion of a copy is
one transaction, so a copy that fails its check is left exactly as it was and
counted as an error. Rotation up to v1.39.1 counted every `~hlgcm1.` copy
as an error; run it again after updating before retiring the old key.
### What a restore replaces
A restore replaces the account's data tables; it does not merge into them.
Every row the file carries is written back under its original id, and every row
the account gained after the snapshot was taken — readings, doses, mood
entries, documents — is deleted with the rest of the class before the file is
read back. Restoring Monday's copy on Wednesday therefore costs the account
everything it recorded on Tuesday. If the current state is worth keeping, take
a fresh snapshot from the backups console before restoring the old one.
## Rotating the off-host key
`BACKUP_ENCRYPTION_KEY` is the key new objects are written under. To rotate
it, set the new key there and move the old one into
`BACKUP_ENCRYPTION_PREVIOUS_KEYS` (comma-separated if there are several), then
restart. New objects are written under the new key; older objects stay
readable because every version-4 object names its key and older objects are
tried against each key in turn. Remove the old key once the lifecycle rule has
retired every object written under it, that is `BACKUP_RETENTION_DAYS` after
the restart.
## Monthly restore drill (automatic)
Since v1.16.4 a pg-boss job (`data-restore-drill`, cron `11 4 1 * *` —
04:11 on the 1st of each month) exercises the read path end-to-end:
fetch the most recent backup object from the bucket, decrypt it under
the current `BACKUP_ENCRYPTION_KEY`, JSON-parse it, and sanity-check
the payload shape. It performs **no database restore** — it validates
the artefact, not the import path.
fetch every backup object of the most recent date from the bucket (one per
account), decrypt each under the current `BACKUP_ENCRYPTION_KEY`, JSON-parse
it, and sanity-check the payload shape. It performs **no database restore** —
it validates the artefacts, not the import path. Each account is checked and
reported on its own: one object that fails is named, and the others are still
read.
Outcomes:
@@ -109,12 +472,21 @@ Outcomes:
uploader has stalled (or the lifecycle rule is too aggressive). The
drill pages via the worker error reporter (stderr + GlitchTip).
- **Failure** — empty bucket, fetch error, decryption failure (wrong or
rotated key), malformed JSON: pages the same way. A decryption
rotated key), malformed JSON: pages the same way, once per failing object,
with the object key and how many accounts were checked. A decryption
failure right after a `BACKUP_ENCRYPTION_KEY` change means the new
key cannot read the existing objects — re-encrypt or accept that
pre-rotation backups are only readable with the retired key.
key cannot read the existing objects: put the old key into
`BACKUP_ENCRYPTION_PREVIOUS_KEYS` (see "Rotating the off-host key").
- **Content under a missing application key** — the object opens, but its
content was written under an `ENCRYPTION_KEYS` entry this server no longer
has, or under an id whose key material changed. The drill decrypts the
shortest value of each section under every key id it finds, and pages naming
the key when none of them opens. A restore of that object
would write back rows nobody can open; put the key back before restoring.
- **Not configured** — deployments without the `BACKUP_S3_*` vars skip
silently (wide-event warning only).
The drill needs no IAM grant beyond the uploader's existing
`GetObject` + `ListBucket`.
The drill lists the bucket to find the newest object, so it needs
`ListBucket` on top of the uploader's `PutObject`, `GetObject` and
`AbortMultipartUpload`. Cloudflare R2's **Object Read & Write** token covers
all four.
@@ -0,0 +1,60 @@
# Blood pressure readings missing their diastolic half
## What happened
The iPhone app (every App Store build up to 1.0.3 and TestFlight 1.1.0)
saves a manually entered blood pressure as two requests to
`POST /api/measurements`: one `BLOOD_PRESSURE_SYS`, one
`BLOOD_PRESSURE_DIA`, both carrying the same `Idempotency-Key`. Until the
replay cache learned to compare request bodies, the server treated the second
request as a retry of the first. It answered with the first request's cached
`201` (header `X-Idempotent-Replay: true`) and never wrote the diastolic
value. The app showed success, so nobody noticed.
The fix makes the cache replay only a request with the same body. A different
body under the same key now runs normally. Nothing recovers the values that
were never sent to the database: they exist only on the person's phone, if at
all.
## Finding the affected readings
Read-only. Run it against the HealthLog database (with the bundled compose
file: `docker compose exec db psql -U healthlog healthlog`). It lists every live systolic reading that has no
live diastolic reading for the same account at the same instant.
<!-- bp-missing-diastolic:start -->
```sql
SELECT u.username,
m.id,
m.measured_at,
m.value AS systolic,
m.source
FROM measurements m
JOIN users u ON u.id = m.user_id
WHERE m.type = 'BLOOD_PRESSURE_SYS'
AND m.deleted_at IS NULL
AND NOT EXISTS (
SELECT 1
FROM measurements d
WHERE d.user_id = m.user_id
AND d.measured_at = m.measured_at
AND d.type = 'BLOOD_PRESSURE_DIA'
AND d.deleted_at IS NULL
)
ORDER BY u.username, m.measured_at;
```
<!-- bp-missing-diastolic:end -->
Readings from the phone app carry `source = 'MANUAL'`. Rows from a synced
source (Withings, Apple Health) that show up here are a different gap, not
this one: those sources write both halves themselves.
## What to tell users
There is nothing the server can repair: the diastolic value never reached
it. A person whose reading appears in the list can re-enter it: delete the
incomplete reading, then add the blood pressure again with both values and
the original date and time. From this release on, both halves are saved on
the first try, from any app version.
+130 -13
View File
@@ -13,22 +13,26 @@ Migrations land **before** the new app container takes traffic. The
canonical command sequence on a single-instance host:
```sh
# 1. Pull the new image.
docker pull ghcr.io/mbombeck/healthlog:vX.Y.Z
# 1. Pull the new image. If you pin a version with HEALTHLOG_IMAGE_REF,
# set it to the new one first.
docker compose pull app
# 2. Run migrations against the live DB using the new image.
docker run --rm --env-file .env.production \
ghcr.io/mbombeck/healthlog:vX.Y.Z \
pnpm prisma migrate deploy
# 2. Run the migrations with the new image before it takes traffic. The
# one-off container starts inside the stack, so it reaches the database
# as `db` and gets the same environment as the app. Its entrypoint
# applies the migrations and exits; a failed migration stops here.
docker compose run --rm app sh -c 'exit 0'
# 3. Recreate the app container so it picks up the new image.
docker compose up -d app
```
The entrypoint also runs `prisma migrate deploy` on container boot, so
step 2 is redundant in normal Coolify flow. It's listed explicitly for
the manual case so an operator can verify the migration result before
flipping traffic.
Use `docker compose run` rather than a plain `docker run` for step 2. A
plain `docker run` starts outside the stack's network, where `db` does not
resolve, and the entrypoint gives up after thirty seconds with "Database
not reachable". The entrypoint also runs the migrations on every boot, so
step 2 is optional; it is there for when you want to see the migration
result before the new container takes traffic.
### v1.11.0 notes
@@ -40,9 +44,10 @@ them in order on boot like any other.
WHOOP introduces two optional instance env vars, `WHOOP_REDIRECT_URI`
and `WHOOP_WEBHOOK_SECRET` (HMAC secret for WHOOP webhook signature
verification). Per-user WHOOP client id/secret live in Settings, not
in the environment. See `docs/integrations/whoop.md`. Add the two vars
to the compose `environment:` whitelist if you set them — vars not on
the whitelist never reach the container.
in the environment. See `docs/integrations/whoop.md`. The shipped
`docker-compose.yml` already whitelists both under `environment:`; only
a forked or older compose file needs them added by hand, since vars not
on the whitelist never reach the container.
### What goes wrong if you reverse it
@@ -73,6 +78,20 @@ roll back:
dev --create-only --name vX_Y_Z_rollback_<col>`), edit the SQL,
commit, and re-deploy. Never `migrate resolve --rolled-back` against
production unless you've taken a fresh `pg_dump` first.
4. Rolling back from v1.40.2 or later to v1.40.1 or earlier: an account
that saved the Coach lookback "Last year" reads its whole Coach
preference blob as defaults on the older version, metric exclusions
included, until the setting is saved again. Ask affected accounts to
pick another lookback before the rollback, or re-save their exclusions
after it.
## Catalog templates
A new required environment variable, or a change to the compose shape, needs a
matching pull request to the TrueNAS apps catalog in the same release cycle
(and an update to `docs/self-hosting/unraid/healthlog.xml` and
`docs/self-hosting/portainer/templates.json`). See
`docs/self-hosting/truenas.md` for what the catalog template carries.
## Verify the served version
@@ -91,6 +110,76 @@ Pass `--only=prod` / `--only=demo` to check a single target, or
`--attempts=N --interval=ms` to widen the retry window while a slow
pull settles.
## Walk the synthetic journey
The version check proves the instance serves the right build. It does not
prove a person can use it. `scripts/synthetic-journey.mjs` walks the
shortest journey that touches the whole stack — sign in, write a reading,
read it back, delete it again — against a running instance:
```sh
# Plain Node 22, no dependencies: runs from a workstation, a runner, or
# the deploy host. Warms the instance first, then asserts each leg.
BASE_URL=https://review.healthlog.dev \
SYNTHETIC_USERNAME=<probe account> \
SYNTHETIC_PASSWORD=<its password> \
EXPECTED_VERSION=v1.38.13 \
node scripts/synthetic-journey.mjs
```
It prints one line per leg with the elapsed time and stops at the first
failure with the status and a redacted body excerpt. The warm-up hit on
each route is timed but discarded — the first request after a deploy pays
the cold-start cost and says nothing about the instance's steady state.
The same journey is available as the **Synthetic journey** workflow
(`workflow_dispatch`, inputs `base_url` and `expected_version`), which
reads the credentials from the `SYNTHETIC_USERNAME` / `SYNTHETIC_PASSWORD`
repository secrets. Nothing calls it from the deploy path; run it by hand
after a deploy until a target instance is settled.
Two preconditions on the probe account: it must be password-only, because
the password flow stops at the MFA ticket for an account with a second
factor, and the target must not be the demo instance, where every mutation
is blocked and the write leg would be red for a reason unrelated to the
deploy.
**A red result.** The leg that failed names the layer:
| Red leg | What it means |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `version` | The instance serves a different build than the tag you deployed. Check the image digest and the `pull_policy` before looking anywhere else. |
| `sign in` | Sessions are broken, or the probe account gained a second factor. A 429 here is the login rate limit, not the deploy. |
| `write` | The write path is down: database, encryption keys, or a migration that did not run. |
| `read back` | A value was written and cannot be read back — the shape this project keeps rediscovering. Roll back. |
| `delete` | The write path works and the reversible delete does not; the probe reading is still on the account and needs removing by hand. |
Run `node scripts/synthetic-journey.mjs --self-test` to confirm the check
itself still works: it walks the journey against an in-process instance
once per leg with that leg broken, and fails if any of them comes back
green.
## Error reporting
HealthLog ships no default error-reporting target and never will: an
operator's crash reports must not leave their host because nobody told them
not to. Reporting starts only when someone types a DSN into **Admin →
Integrations → GlitchTip**, and that card states plainly whether reports are
going anywhere and which host they go to.
For a maintainer-operated instance, set the DSN there after the first deploy —
it lives in the database, not in the environment, so it survives an image
upgrade and does not need a compose change.
The badge on that card tracks delivery, not intent. A DSN that is set and
parses is not the same fact as reports arriving: a wrong public key, a wrong
project id and a host that stopped answering all parse. So the card is green
only while a report has actually left this host inside the last fortnight,
amber while a target is set and nothing has come back from it, and it names the
reason underneath when the last attempt was refused. Press **Test** to prove
the target on demand — that send is recorded like any other, so the badge
answers immediately.
## Verify the image signature
Every release image (the multi-arch manifest **index**, covering both
@@ -131,6 +220,34 @@ without touching the file:
- `HEALTHLOG_IMAGE_REF=:v1.16.5` — pin to a release tag (still mutable).
- `HEALTHLOG_IMAGE_REF=@sha256:<digest>` — pin to the immutable digest.
#### Bumping a digest pin by hand
A digest-pinned instance never follows a release on its own — an image
promote does not touch the pin, so moving it is part of shipping. The
mechanic, end to end:
1. Resolve the new release's digest from the registry (the manifest-list
digest, which covers both architectures):
```sh
docker buildx imagetools inspect ghcr.io/mbombeck/healthlog:v1.37.20 \
| grep -m1 Digest
```
2. Set `HEALTHLOG_IMAGE_REF=@sha256:<that digest>` where the compose
environment lives — the `.env` next to the compose file, or the
deployment platform's env vars for the app service.
3. Deploy as usual.
4. Verify `/api/version` on the target — and verify it **three times a
few seconds apart**, not once: during the container swap a single
probe can be answered by the outgoing container (or a cache) and read
as success while the old release keeps running. Three stable answers
reporting the shipped `version` + `buildSha` are the signal; a deploy
that finishes suspiciously fast (under ~30 s) is a warning that
nothing was actually pulled.
> **A pin is sticky, and a stale pin is silent.** Once set, every later deploy
> ships that reference until someone changes it. The deploy still reports
> success, the tag still builds, the image still publishes, and the running
+111 -16
View File
@@ -41,41 +41,136 @@ under `v1` (the synthetic id assigned to the existing `ENCRYPTION_KEY`).
Restart the app. New writes are now encrypted under `v2`; existing
`v1`-keyed and legacy bare rows still decrypt because the `v1` entry is
retained.
3. **Run the rotation script** to re-encrypt every existing encrypted column
under the new active key:
3. **Re-encrypt the stored data under the new key.** Open **Admin →
Encryption** and press **Rotate now**. The button needs an admin account
with a second factor, confirmed recently; it queues one background run
(`POST /api/admin/encryption/rotate`) on the app's own worker, so it
works on the published image with nothing else installed. The same page
shows the per-column counts and the result of the last run.
Without a second factor on any admin account, run the rotation script
instead. It imports the application code and the generated database
client, so it runs from a source checkout of the same release, not
inside the production container (the image has no package manager and
does not contain `scripts/rotate-encryption-key.ts`). It needs the same
`ENCRYPTION_KEYS` and `ENCRYPTION_ACTIVE_KEY_ID` as the app and a
`DATABASE_URL` that reaches the database:
```
git checkout vX.Y.Z # the release the instance runs
pnpm install && pnpm db:generate
pnpm dlx tsx scripts/rotate-encryption-key.ts v2
```
The script is idempotent — running it again is a no-op for rows already
prefixed with `v2.`. It rotates User, WithingsConnection, AppSettings,
NotificationChannel, and PushSubscription rows. The summary line at the
end shows `scanned`, `rotated`, and `errors` per table+field; treat
`errors > 0` as a hard failure and re-run after fixing the cause.
4. **Drop the old key (optional, recommended).** Once the script has run
cleanly:
The bundled `db` service publishes no port. On a stock compose stack,
either publish `5432` for the duration, or run the checkout in a
throwaway `node:22` container attached to the compose network.
Both paths are idempotent: running again is a no-op for rows already
prefixed with `v2.`. Both rotate every column in the canonical registry
(`src/lib/crypto/encrypted-columns.ts`), which covers the `*Encrypted`
columns plus the ones whose names say nothing about their contents:
`IntegrationStatus.lastError`, `CoachMessage.encryptedContent`,
`NotificationChannel.config`, the OAuth `accessToken` / `refreshToken`
columns, the web-push `p256dh` / `auth` secrets, the idempotent-replay
`IdempotencyKey.responseBody`, and `DataBackup.data` — the whole-account
backup blob.
When you used the script, read three things off its output before going
further:
- the per-column line, `scanned` / `rotated` / `errors` / `dropped`.
`scanned` counts the rows that hold ciphertext in that column, not every
row of the table. Treat `errors > 0` as a hard failure and re-run after
fixing the cause. A
`dropped` count is only ever a cache row the run could not read and
deleted rather than leave unreadable.
- `Columns walked: N/M registered`. The two numbers must match.
- a `NOT WALKED` block, if one appears. It lists registered columns this
run skipped, and the run exits non-zero. Rotation is incomplete; do not
go on to step 4.
Two guard tests keep the registry honest in CI: one scans the schema for
`*Encrypted` columns, the other derives the ciphertext-bearing columns from
the Prisma write payloads, which is what catches a column that holds
ciphertext under an ordinary name.
4. **Confirm nothing is left on the old key, THEN drop it.** This is the step
that destroys data if it is taken on a bad signal, so check the corpus
rather than the absence of complaints. Open **Admin → Encryption** and
confirm the status view reports zero rows outside the active key, or
re-run the script: a clean second pass reports `rotated=0`, `errors=0` and
a full `Columns walked` line. Both read the same registry the rotation
walks.
A run that walked every column without an error also removes the boot
key check's record of each previous key id that no longer holds a single
value (`encryption_key_canaries`); the script prints which ids it removed
and, for an id that still holds values, the columns that do. With the record
gone, the id can later carry a different key without the start-up check
refusing it.
A zero only means "nothing left" when the run also says it walked every
registered column. A zero from a run that skipped columns means "never
looked", and dropping the old key on it makes those rows permanently
undecryptable — `decrypt()` is fail-closed and there is no recovery path.
Only once the corpus reads clean:
```
ENCRYPTION_KEYS='{"v2":"<new key>"}'
ENCRYPTION_ACTIVE_KEY_ID="v2"
# ENCRYPTION_KEY can now be removed
```
Restart. The legacy single-key fallback is now disconnected; only `v2`
exists.
> **The rows in the database are covered. The content of a backup is not.**
> Rotation re-encrypts every registered column, including `DataBackup.data`
> and the pieces in `DataBackupChunk`, so every stored copy opens under the
> new key. What it cannot change is what a disaster-recovery backup carries
> inside: the database's ciphertext as it was stored when the copy was taken,
> which a restore writes back verbatim. A copy taken before the rotation still
> needs the old key for its notes, documents and coach history, and so does
> every copy in the off-host bucket and every backup file you downloaded.
>
> So before step 4, also check **Admin → Encryption → Keys the backups still
> need**. It lists, per key id, the stored copies that need it with the oldest
> date, and when the last off-host copy needing it expires under the bucket's
> lifecycle rule. Keep the old key in `ENCRYPTION_KEYS` until it is no longer
> listed there (the weekly copy replaces itself within a week; delete old
> uploaded copies you no longer want, and wait out the off-host retention), or
> accept that those copies cannot be restored. Copies written before v1.39.3
> did not record their keys and are listed as such: treat them as needing
> every key that existed when they were written.
>
> Dropping the key early no longer fails silently: a restore, a restore
> preview or an upload of a copy that needs a missing key is refused with the
> key id named, and nothing is changed. Putting the key back makes the copy
> restorable again.
>
> If you rotated on a release before v1.38.6 and dropped the previous key,
> the stored backups themselves are encrypted under the key you removed: put
> that key back into `ENCRYPTION_KEYS` and re-run the rotation on this release
> before removing it again.
## Adding a third key (v2 → v3)
Same procedure, just shift the labels — keep `v2` in the map until the
script reports zero `v2.`-prefixed rows remaining.
Same procedure, just shift the labels — keep `v2` in the map until a full
run (every registered column walked) reports zero `v2.`-prefixed rows
remaining.
```
ENCRYPTION_KEYS='{"v2":"<old>","v3":"<new>"}'
ENCRYPTION_ACTIVE_KEY_ID="v3"
pnpm dlx tsx scripts/rotate-encryption-key.ts v3
# restart, then Admin → Encryption → Rotate now
# (or: pnpm dlx tsx scripts/rotate-encryption-key.ts v3 from a checkout)
ENCRYPTION_KEYS='{"v3":"<new>"}'
```
## Rollback
> **Important.** Once the rotation script has run, ciphertexts in the
> **Important.** Once a rotation has run, ciphertexts in the
> database start with `v2.` (or whatever the active id is). The pre-PR
> v1.3.x image cannot read that prefix — it expects bare base64 — and
> calling `decrypt()` on those rows will throw.
@@ -85,7 +180,7 @@ If you need to revert to the pre-rotation image:
- Either keep the new image. The new code reads both formats, so most
rollback scenarios don't need to undo rotation.
- Or, if you must run the old code, restore a database backup taken
_before_ the rotation script ran. There is no script to convert
_before_ the rotation ran. There is no script to convert
`v2.`-prefixed rows back to legacy format — by design, rotation is a
forward-only operation.
@@ -97,10 +192,10 @@ at least 24 hours.
- `Encryption key id 'v1' is not configured` — the database still contains
`v1.`-prefixed rows but `v1` was removed from `ENCRYPTION_KEYS`. Re-add
the key, run the rotation script, then remove again.
the key, run the rotation again, then remove it.
- `Found a legacy-format ciphertext but no v1 key is configured` — same
cause for legacy bare-base64 rows. Restore `ENCRYPTION_KEY` (or add a
`v1` entry to `ENCRYPTION_KEYS`) and run the rotation script before
`v1` entry to `ENCRYPTION_KEYS`) and run the rotation again before
removing it.
- `Refusing to rotate: argv key id ... does not match the currently active
id ...` — pass the same id you set in `ENCRYPTION_ACTIVE_KEY_ID`. The
+19 -12
View File
@@ -46,8 +46,10 @@ states:
| `[missing-optional]` | Variable is optional. The script reports it but does not fail. |
The grep-friendly format lets a CI pipeline do `grep -q
'\[MISSING-REQUIRED\]'` to gate a deploy. The CI integration itself
is deferred to v1.4.43 — this release ships the CLI tool only.
'\[MISSING-REQUIRED\]'` to gate a deploy. CI already does: the
`env-check.yml` workflow runs `pnpm check-env --file
.env.production.example` on every PR and fails on missing required
vars.
## All-or-none groups
@@ -65,11 +67,15 @@ Example output for a partial APNs config:
[OK] APNS_TEAM_ID
[OK] APNS_BUNDLE_ID
[missing-optional] APNS_KEY — Satisfied by any of: APNS_KEY, APNS_KEY_FILE
[MISSING-REQUIRED] <all-or-none> — Group is all-or-none but only 3/4 variables are set. Either set all or unset all.
```
A reviewer immediately sees that `APNS_KEY` (or its `APNS_KEY_FILE`
alternative) is missing while the other three APNs vars are set — the
exact configuration that silently disables iOS push.
The APNs group is `allOrNone: true`, so the partial config also emits
the synthetic `<all-or-none>` row at REQUIRED severity and the run
exits 1. A reviewer immediately sees that `APNS_KEY` (or its
`APNS_KEY_FILE` alternative) is missing while the other three APNs
vars are set — the exact configuration that silently disables iOS
push.
## Editing the manifest
@@ -88,12 +94,13 @@ so changes go through a PR. To add a new variable:
if the manifest change introduces a new classification branch
(anyOf, allOrNone, …).
## Future: CI gate
## CI gate
Deferred to v1.4.43:
The GitHub Actions workflow `.github/workflows/env-check.yml` runs
`pnpm check-env --file .env.production.example` on every PR, blocking
changes that introduce new required vars without updating the example
file.
- GitHub Actions workflow that runs `pnpm check-env --file
.env.production.example` on every PR, blocking changes that
introduce new required vars without updating the example file.
- Coolify pre-deploy hook that runs `pnpm check-env` inside the
target container and aborts the deploy on exit code 1.
Still an idea only: a Coolify pre-deploy hook that runs
`pnpm check-env` inside the target container and aborts the deploy on
exit code 1.
+18 -10
View File
@@ -2,9 +2,13 @@
A self-hosted operator can reset a single user's password from inside the
running container. This is an **operator-only** maintenance path — there is no
user-facing or API route for it, and it bypasses the normal account-recovery
flow. Use it only for an account you administer (for example, after a forgotten
password on a single-user instance).
self-service reset route for users, and it bypasses the normal
account-recovery flow. Admins do have an in-app alternative:
`POST /api/admin/users/{id}/reset-password` (cookie-admin only) sets a new
password and destroys the user's sessions, tokens, and trusted devices. The
CLI remains the path when no admin can log in. Use it only for an account you
administer (for example, after a forgotten password on a single-user
instance).
> **Operator-only.** The script writes directly to the `users` table and is
> intended to be run by the host operator with database access. Treat the new
@@ -14,10 +18,12 @@ password on a single-user instance).
## Run it
The reset CLI ships in the image and runs under plain `node` against the built
runtime (the standalone image strips `tsx`, so this is a `.mjs` that uses the
in-image `pg` and `@node-rs/argon2` directly and reuses the app's exact Argon2id
parameters):
The reset CLI ships in the image from v1.39.3 on. It runs under plain `node`
against the built runtime: a `.mjs` file that uses the in-image `pg` and
`@node-rs/argon2` directly and reuses the app's exact Argon2id parameters.
Images up to and including v1.39.2 did not contain the script, so on those
the command below fails with "Cannot find module"; use the source-checkout
form at the end of this page instead.
```sh
docker compose exec app node scripts/reset-password.mjs <username-or-email>
@@ -28,7 +34,7 @@ confirmation that names only the user — never the password:
```
New password (input hidden):
reset-password: password updated for "alice"
reset-password: password updated for "alice"; revoked 2 sessions, 0 API tokens, 1 refresh tokens, 0 trusted devices, and 0 step-up elevations
```
You can also pass the password as a second argument for non-interactive use,
@@ -53,8 +59,10 @@ docker compose exec app node scripts/reset-password.mjs alice 'a-strong-passphra
## Source checkout
From a source checkout (not the production image) the same script runs under
Node directly:
From a source checkout of the same release (after `pnpm install`) the same
script runs under Node directly. It needs a `DATABASE_URL` that reaches the
database; the bundled `db` service publishes no port, so on a stock compose
stack run it inside the compose network or publish the port temporarily:
```sh
DATABASE_URL='postgres://…' node scripts/reset-password.mjs <username-or-email>
+10 -11
View File
@@ -1,11 +1,10 @@
# TLS SPKI pinning — coupling, alarm, and re-pin runbook
The native client SPKI-pins the server's TLS chain at the **CA level**. It
ships a small pin set — currently the issuing intermediate plus the root —
and accepts a connection only when the served chain passes baseline X.509
evaluation AND at least one certificate anywhere in the chain matches a pin
(any-match). The leaf is deliberately **not** pinned, so routine leaf
renewals are a client no-op. The outage risk is a **chain change**: the
The native client SPKI-pins the server's TLS chain at the **CA level**: it
ships a small pin set and rejects a connection whose validated chain
contains no pinned key. The leaf is deliberately **not** pinned, so routine
leaf renewals are a client no-op. The pin set itself and its enforcement
rules live in the client repository, not here. The outage risk is a **chain change**: the
served chain stops terminating in the pinned CA keys — the server moves to a
different CA, or the CA rotates its intermediate / root keys. This page
explains the coupling, the server-side alarm that watches the served leaf,
@@ -15,11 +14,11 @@ and the operator / release-owner steps when it fires.
A SPKI pin is `base64(sha256(DER subjectPublicKeyInfo))` — a hash of a
certificate's public key, not of the whole certificate. The native client
carries a set of these pins (build-time config, ≥ 2 well-formed pins
enforced for release builds) and rejects any TLS connection whose validated
chain contains no pinned key. Hosts outside the client's pinned-host list
fall back to plain system-trust validation, which is the documented model
for self-hosted instances that ship their own chain.
carries a set of these pins in its build-time config and rejects any TLS
connection whose validated chain contains no pinned key; the exact pin-set
rules are the client repository's contract. Self-hosted instances that ship
their own chain sit outside the pinned-host list and validate against
system trust.
The app host's certificate auto-renews roughly every 90 days and each
renewal mints a new leaf keypair. Because the client pins the CA keys rather
-260
View File
@@ -1,260 +0,0 @@
# v1.4.x follow-up issues
Items identified by the v1.4.1 audit pass that warrant deeper work
than a hardening release should land. Each one carries enough context
that a future contributor can pick it up without re-running the audit.
## Security — deferred
### S-FOLLOW-1 — Idempotency-Key concurrent duplicate side-effects (HIGH)
Audit reference: `~/infra/reports/v14-security-audit.md` H1.
The `withIdempotency()` wrapper currently does
`findCached → handler → persistCached`. Two requests with the same
`Idempotency-Key` arriving in parallel both miss the SELECT, both
execute the handler (duplicate measurements / intake events), and
one INSERT loses on the unique constraint silently. The repo-doc
contract ("retries with the same Idempotency-Key … replay the
original response — no second side-effect") is therefore violated
whenever a flaky mobile client double-sends.
**Fix shape**: acquire the slot before the handler runs.
`INSERT … ON CONFLICT DO NOTHING RETURNING id` reserving the
`(userId, key, method, path)` row with a sentinel
`responseStatus = 0`, then UPDATE on completion; concurrent losers
SELECT-loop with backoff for the row to be filled. Or wrap the
whole request in a Postgres advisory lock keyed by hash(userId, key)
via `pg_advisory_xact_lock`.
Why deferred: needs a careful integration test against the new
testcontainers suite (two concurrent inserts → exactly one handler
invocation) and a public-API contract check that the
sentinel-status row never bleeds into a 2xx replay. Fits a v1.4.2
PR scope on its own.
---
### S-FOLLOW-2 — Encryption key fallback NODE_ENV gate (MEDIUM)
Audit reference: `~/infra/reports/v14-security-audit.md` M1.
`src/lib/crypto.ts:61-74` only requires the 64-hex production key
when `process.env.NODE_ENV === "production"`. A fresh Docker run
that forgets to set `NODE_ENV=production` (raw `node …` invocations,
some operator setups) silently accepts a 32-character key and pads
it deterministically with a SHA-256 of itself, halving the entropy
and making the resulting key recoverable from any leaked partial.
**Fix shape**: invert the gate to `NODE_ENV !== "development" &&
NODE_ENV !== "test"` — fail-closed by default — or require an
explicit `ALLOW_WEAK_DEV_KEYS=1` opt-in.
Why deferred: needs a migration note for self-hosters whose `.env`
files lack `NODE_ENV` (default Coolify deploys do set it; bespoke
setups may not). Worth a release note + .env.example call-out.
---
### S-FOLLOW-3 — Refresh-token reuse-detection serialisation (MEDIUM)
Audit reference: `~/infra/reports/v14-security-audit.md` M2.
`src/lib/auth/refresh-token.ts` reuse-detection is a `findUnique`
followed by a non-transactional `findMany + updateMany`. Concurrent
first-time refreshes can briefly have both clients holding
unrevoked access tokens before the loser's are revoked, and a
parallel reuse attempt doubles the audit-log noise.
**Fix shape**: wrap the rotation in a single `prisma.$transaction`
with `Serializable` isolation, OR reorder to "claim first, mint
second": `prisma.refreshToken.update({ where: { id, usedAt: null } })`
fails atomically if the row was already consumed; only after the
update succeeds, call `issueAccessAndRefresh`.
Why deferred: needs an integration test that fires N parallel
refreshes for the same token and asserts exactly one new pair is
issued. The testcontainers suite is the right home; v1.4.2 PR.
---
### S-FOLLOW-4 — moodLog webhook HMAC lookup column (MEDIUM)
Audit reference: `~/infra/reports/v14-security-audit.md` M3.
`src/app/api/integrations/moodlog/webhook/route.ts` performs an
O(n) AES-GCM decrypt sweep across all enabled users for every
webhook hit. Side-channels: timing oracle for ordering, DoS
amplification (30/min IP rate-limit × n decrypts).
**Fix shape**: add a `moodLogWebhookSecretLookupHash` column on
`User` (HMAC-SHA-256 keyed by `API_TOKEN_HMAC_KEY`, populated
alongside the encrypted secret on every write). Webhook does a
single indexed `findUnique` on the lookup hash, bypassing the
candidate iteration. The encryption stays as defence-in-depth.
Why deferred: schema migration required. Backfill needs a one-off
script that decrypts every existing row and writes the lookup
hash. Owners need to approve the migration window. v1.4.2 or
v1.5.
---
### S-FOLLOW-5 — moodLog `readMoodLogSecret` legacy fallback (MEDIUM)
Audit reference: `~/infra/reports/v14-security-audit.md` M4.
If `decrypt()` throws inside `src/lib/moodlog-secret.ts:27-37`, the
function returns the stored value as-is. Intent: legacy plaintext
rows keep working. Side effect: an attacker with read access to
the DB obtains the ciphertext blob and can submit it as the literal
webhook secret.
**Fix shape**: detect "looks like a v1.4 envelope"
(`/^[A-Za-z0-9_-]{1,32}\..+$/`) and refuse the legacy fallback for
envelope-shaped values. Log a metric so the rotation-on-write
contract can be verified to drain.
Why deferred: needs a small data-audit run to confirm no production
row has a non-envelope value before the strict check goes live.
---
### S-FOLLOW-6 — Restore script writes decrypted JSON with default permissions (MEDIUM)
Audit reference: `~/infra/reports/v14-security-audit.md` M5.
`scripts/restore-backup.ts:73-122` writes the decrypted JSON via
`writeFileSync(out, plaintext, "utf8")` with default mode (0644
typical). The file contains decrypted PHI for the restored user.
**Fix shape**:
`writeFileSync(out, plaintext, { encoding: "utf8", mode: 0o600 })`.
Optional: warn if `out` is in a world-readable directory.
Why deferred: tiny one-line fix; bundling with the next ops-script
update keeps the PR coherent.
---
## Performance — deferred
### P-FOLLOW-1 — Recharts top-level import on `/insights` (P0)
Audit reference: `~/infra/reports/v14-performance-audit.md` P0.
`src/app/insights/page.tsx:42-50` static-imports
`{ ScatterChart, Scatter, XAxis, … } from "recharts"` even though
`HealthChart` and `MoodChart` 8 lines above are already wrapped in
`dynamic(…, { ssr: false })`. The static import pulls the whole
recharts bundle into the route's first JS payload, defeating the
dynamic split.
**Fix shape**: extract the BP-mood scatter into
`src/components/charts/bp-mood-scatter.tsx` and import it via
`dynamic(…, { ssr: false })` like the others.
Why deferred: trivial mechanical change but needs a Lighthouse
before/after to quantify the bundle-size win for the v1.4.2
release notes.
---
### P-FOLLOW-2 — `/api/insights/targets` unbounded glucose history scan (P0)
Audit reference: `~/infra/reports/v14-performance-audit.md` P0.
`src/app/api/insights/targets/route.ts:600-604` pulls every glucose
measurement the user ever logged (no `gte: thirtyDaysAgo`) and
filters in JS. Diabetic users with multi-year history will
materialise tens of thousands of rows on every targets fetch.
**Fix shape**: split into "latest per context"
(`distinct: ["glucoseContext"], orderBy: { measuredAt: "desc" }`)
and a `measuredAt: { gte: thirtyDaysAgo }` window query, mirroring
the pattern at lines 102-121 for `latestEverByType`.
Why deferred: needs a per-context test asserting the new query
returns the same payload shape. Pairs nicely with the MoodEntry
index migration (P-FOLLOW-3).
---
### P-FOLLOW-3 — `MoodEntry @@index` is on `(userId, date)` not `(userId, moodLoggedAt)` (P0)
Audit reference: `~/infra/reports/v14-performance-audit.md` P0.
`prisma/schema.prisma:438` declares `@@index([userId, date])`, but
active queries sort/filter by `moodLoggedAt`:
- `src/app/api/insights/targets/route.ts:495`
- `src/app/api/insights/comprehensive/route.ts:52`
- `src/app/api/export/route.ts:87`
The unique constraint `@@unique([userId, date, moodLoggedAt])` is
not selectable by Postgres for windowed `moodLoggedAt`-range reads.
**Fix shape**: add `@@index([userId, moodLoggedAt])` (do NOT drop
the existing index — the unique still serves the moodlog webhook
upsert path). New migration `0026_moodentry_moodloggedat_index`.
Why deferred: schema migration. Owner approval for the migration
window.
---
### P-FOLLOW-4 to -7 — P1 / P2 perf items
- N+1 count() per medication on admin reminder-check
(`src/app/api/admin/notifications/reminder-check/route.ts:84`).
Replace with `groupBy` on `medicationIntakeEvent`.
- `/api/analytics` 8-parallel full-history scan
(`src/app/api/analytics/route.ts:20-40`). Single `findMany` with
`type: { in: types }` and JS-side group.
- `/api/import` sequential `prisma.measurement.create` per row
(`src/app/api/import/route.ts:77-96`). Replace with
`createMany({ skipDuplicates: true })`.
- `pairByTimestamp` not used in `/api/analytics` BP correlation
(`src/app/api/analytics/route.ts:80-86`). Replace the quadratic
loop with the helper from `@/lib/analytics/correlations`.
---
## Test-quality polish (5 minor items)
Audit reference: `~/infra/reports/v14-test-theatre-audit.md`.
- `src/app/api/gamification/__tests__/ios-format.test.ts` L111-112:
upgrade `toBeDefined()` to shape predicates.
- `src/lib/analytics/__tests__/classifications.test.ts` L169-170:
add `toMatch(/60/)` body-content assertion to compliance-alert tests.
- `src/lib/__tests__/idempotency.test.ts` L145: upgrade bare
`toHaveBeenCalled()` to `toHaveBeenCalledWith({ where: …key… })`.
- `src/app/api/telegram/webhook/__tests__/route.test.ts` L457: same
shape — upgrade or drop.
---
## i18n hardcoded strings
Audit reference: `~/infra/reports/v14-i18n-drift-audit.md`.
35+ hardcoded strings in `src/components/settings/ai-section.tsx`
need to be moved into `messages/{en,de}.json` keys. The settings
section was extracted in #143 with strings inline as a known
follow-up; this is the cleanup PR.
Why deferred: low blast-radius (only the AI provider settings page
shows English to a German user; the dashboard, dialogs, and
critical UX paths all flow through `t(…)`). v1.4.x or v1.5.
---
## Notes
These are the items the v1.4.1 audit identified that the hardening
release deliberately did NOT take. The audit also found 0 hallucinated
medical claims, 0 i18n key-parity gaps, and the test theatre rate
across the entire codebase was low (5 minor patterns). The codebase
is in healthy shape; this list is the punch-list for the next
proactive iteration, not a backlog of bugs we know about and ignore.
+318
View File
@@ -0,0 +1,318 @@
# Sharing a health record with another account
Two accounts on the same instance can be connected so that one of them
can open the other's health record. A parent and an adult child, two
partners, somebody keeping an eye on a relative's blood pressure — the
case this exists for is a household, not an organisation.
Since v1.37.0 there is a second arrangement beside it: a **managed
profile**, a health record for somebody who has no account at all. That
half is described further down, under "Records with no login".
This page describes what these arrangements do, what they deliberately do
not do, and which of the instance's existing trust properties they leave
exactly as they were.
## The shape of it
One account **shares**; the other is **given access**. In the code and in
the settings copy these are the owner and the person they invited.
- The owner opens **Settings → Shared access** and invites somebody by
the username or e-mail address that person signs in with. They need an
account on this instance already; there is no invite-by-e-mail flow.
- **The invitation confers nothing.** Until the other person accepts it,
it is an offer sitting in their own settings. Being handed read access
to somebody's health record is not something the product imposes
silently, and the acceptance — with its timestamp and the accepting IP —
is what the row records.
- Once accepted, the record shows up in that person's user menu under
"Open a record". Opening it reloads the app into the owner's record.
- A banner across the top of every page names whose record is open and
what the access admits, with a button back to the person's own. It is
loud on purpose: somebody who forgets they are switched will log their
own reading into another person's record, and there is no undo for an
entry that was never theirs.
- Either side can end it at any time. The owner withdraws access; the
other person hands it back. Both are one click with no second factor
and no typed confirmation — reducing access must never be harder than
granting it was.
## What the other person can and cannot do
An invitation carries two answers: how much of the record it opens, and
what may be done inside it.
### How much of the record
Either the entire record, which is what sharing has always meant and what
every grant written before v1.37.0 carries, or a set of named sections
chosen when the invitation is written:
| Section | What it covers |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| Readings | Weight, blood pressure, pulse, glucose, sleep, workouts and custom metrics |
| Medications | The medication list, its schedules, doses taken, side effects and stock |
| Lab results | Lab results and the analytes behind them |
| Health background | Allergies, family history, the facts in the health profile, visits and the practices behind them, and the vaccination record |
| Illness | Illness episodes and the day logs kept under them |
| Mood and mind | Mood entries and the mental-health questionnaire history |
| Cycle | Cycle tracking |
| Documents | Everything in the document vault |
A section that was not shared is refused exactly the way a record nobody
shared is, so the shape of what was held back is not readable from
outside. Sections are route families and nothing finer: there is no row
filtering, no field filtering and no redaction inside a section that WAS
shared. The invitation screen says this in as many words, because a note
or a document name inside one section can be about any other.
Aggregate surfaces (the dashboard overview, the health score, the daily
digest, every insight) read across sections, so a grant naming sections
never opens one. A figure derived from part of a record reads as a figure
about the person, and it would not be one. Whole-record grants do not all
open them equally either: the daily digest and the dashboard's snapshot
answer at read, while the health score, the dashboard's summary and the
insights need manage.
A stored scope never grows. A section added by a later release is not in
a set somebody ticked before it existed.
### What may be done inside it
Three levels, fixed when the invitation is written. Raising one means
revoking and inviting again, because widening a grant in place would carry
a consent the other person never gave.
| Level | Adds |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Read | Read what the grant opens, and change nothing. |
| Write | Add entries: a reading, a lab result, an analyte, an illness entry, a side effect, a medication, marking a dose taken or skipped, a visit, a practice, and a vaccination dose. Editing, deleting and restoring stay with you. |
| Manage | Change and remove entries, including ones the owner wrote; record the health background; read the insights generated from the record. Always the entire record. |
Some entries are creates only **manage** reaches, and the split runs by
entry rather than by section: an allergy, a family-history entry, a mood
entry, a screener, a cycle day, a water entry and a preventive-care
reminder are all created at manage, in sections a write grant can
otherwise add to. Nothing in the document vault is writable at any level.
One entry needs two sections rather than a higher level. Planning the
booster a vaccination suggests files it as a preventive-care reminder,
which lives under Readings, so a grant that opens Health background alone
logs the dose and is refused the booster. Logging the dose is unaffected
either way, and the app does not offer the booster to a grant that cannot
plan it.
Offering **manage** asks the owner for a fresh second factor if they have
one enrolled, which makes it a browser-only act either way: a Bearer
caller is refused before anything else happens and told to use a browser.
Accepting it has no such restriction. Manage never carries a section
scope, because "they can do anything, but only to part of you" promises a
boundary an edit cannot keep.
Everything a manager does is written to the trail under their own name,
with a verb naming the act rather than a generic "made a change".
**Nothing about the account around the record.** This is the line the
whole feature is built on, and it is drawn on the server:
| Not reachable | Why it would matter |
| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| Password, passkeys, second factor, recovery codes | Silent takeover, surviving any revocation |
| Sessions, trusted devices, sign-out-everywhere | Ending or enumerating the owner's logins |
| API tokens, the MCP connector | A durable credential that outlives the access |
| Connected services (Withings, Fitbit, WHOOP, Google Health, Polar, Oura, Strava, Nightscout) | Re-pointing a sync, or feeding somebody else's wearable into this record |
| Notification channels and push devices | The owner's health alerts redirected to another phone or chat |
| Full exports, the encrypted archive, clinician share links | A one-click copy of everything, or a new door that outlives the access |
| Asking an AI provider anything | AI processing of the owner's data, under the owner's own consent |
| Modules, thresholds, units, the record's language and timezone | Configuration of the account, not content of the record |
| Sharing itself | Inviting somebody else, widening the access, or passing it on |
| Locale, theme, dashboard layout | Presentation belongs to the person, not to the record |
One export is the exception, and it is deliberate: the doctor report
(`POST /api/export/health-record`) answers at manage on a whole-record
grant. It renders a prepared artefact from a selection the caller declares
rather than handing the record over whole, which is the difference the row
above is drawing. The full exports and the passphrase-encrypted archive
stay with the owner.
This table is about a grant between two accounts. A managed profile is
the one place where some of it is deliberately different, because a record
with no login has nobody else to keep its own configuration: see "Records
with no login" below for exactly which part of it a guardian may reach.
The last two rows are worth a sentence each. Sharing is not
transferable: somebody given access cannot invite a third person, cannot
raise their own level, and cannot hand it on. And display preferences
stay with the person at the keyboard, so reading somebody else's record
does not change your own theme, language or dashboard.
The AI row is the one that looks arbitrary and is not. Server-managed AI
features send the record's data to a provider under a consent the record's
OWNER gave, for their own use. Somebody else triggering that would create
a consent-shaped act the owner never made. So a manage grant can READ
insights that were already generated, and nothing a delegate does at any
level causes an outbound provider call or queues a generation job. The
owner's own path is unchanged and is the control that proves the
difference.
These are not checks that a page forgot to render. Every route in the
product refuses by default while a browser is acting on another account;
a route becomes reachable only by declaring it, and the set of declared
routes is frozen by a test.
## Revocation, and what it cannot undo
Ending access takes effect on the other person's **next request**, not at
their next login. The grant is checked against the database on every
single request, so there is no cached verdict to wait out. If their
browser is sitting inside the record when the owner ends it, the same
database transaction puts that browser back into its own account — they
land at home rather than on a wall of refusals.
What revocation cannot do is take back what was already seen. A person
who had read access could have read, remembered, screenshotted or written
down anything in the record. The product can close the door; it cannot
reach through it. Nothing in the interface implies otherwise, and neither
does this page.
Ending access never deletes the record of it. The row stays with the
dates and with who ended it, because "who had access, from when to when,
and who ended it" is a question a deleted row cannot answer. Re-inviting
the same person creates a new row beside the old one.
## Records with no login
A **managed profile** is a health record for somebody who does not sign
in: a child, or an adult who is cared for. It is a real account row with
no password, no passkey and no e-mail address, and it is never presented
as something to log in as.
- It is created from **Settings → Shared access**, under a fresh second
factor. An account with no second factor enrolled is refused rather than
waved through, because the act creates a permanent management
relationship over a person who cannot object to it.
- Creation takes a display name, optionally a real date of birth, and the
language and timezone the record's own days and reminders are measured
in. A year on its own is never turned into the first of January. The
language belongs to the record, not to the guardian reading it, so the
guardian's own screens stay in their own language.
- The creator becomes the first **guardian** in the same transaction, over
an ordinary accepted MANAGE grant with the profile as grantor. If either
half fails, neither happens: there is no window in which the profile
exists with nobody looking after it.
- A second guardian is invited and accepts exactly like any other
invitation. An accepted guardian grant does not expire; the invitation
token still can.
- **A managed profile can never be left guardian-less.** Revoking,
handing back, deleting a guardian's own account and deleting the
profile all take the same lock on the profile and re-check the count
inside it, so two people cannot both leave at once. The last guardian is
refused, with a message naming the two ways out: add another guardian,
or delete the profile under a fresh second factor. Deleting the profile
deletes everything recorded for it.
- A guardian may keep that record's settings: modules, units, thresholds,
its language and timezone, and its notification preferences. Connected
services are visible as a status only. Connect, callback, sync,
credential, disconnect, resume and test are not guardian surfaces in
this release, and their deep links land on the shared-record unavailable
page rather than on a raw refusal.
- **Its reminders go to its guardians.** A record with no login has no
channels of its own, so medication reminders, measurement reminders,
safety-floor alerts and low-stock alerts fan out to every active
guardian, in that guardian's own language and over the channels that
guardian already configured. Nothing else fans out; every other event
stays on the path it was already on. The payloads carry no take or skip
action, on any channel, so a notification about somebody else's record
cannot be acted on from a lock screen. One guardian suppressing
server-side reminders on their own device does not suppress anybody
else's.
- Delivery attempts record both the record the message is about and the
person it was sent to, so the admin notification diagnostic can answer
"who was this for" and "whose record was it about" separately.
There is no emancipation flow: no route, no control and no copy suggests
a managed profile can be turned into an ordinary account. The data model
leaves room for it (the credentials are nullable and the managed marker
can be cleared) and clearing that marker stops the notification fan-out,
but nothing in v1.37.0 exercises any of that.
## Seeing what happened
**Settings → Shared access** answers three questions for the owner, at
any time: who can open this record, since when, and when they last did.
Below that, a list of the days somebody else opened it and how many times
— one line per person per day, rather than a line per request.
That list is bounded by the instance's audit retention, and the page says
so with the actual number rather than a hardcoded one. The default is 365
days (`AUDIT_LOG_RETENTION_DAYS`); an operator who shortens it shortens
this view too, and the sentence under the heading changes to match. The
query is bounded to that window, so the sentence is the real limit of the
list rather than a caption over an unbounded one.
Two things the list does not claim, both worth reading before treating it
as an answer:
- **An empty list is not proof that nobody opened the record.** It means
nobody did so within the window, and that any earlier row has been
purged.
- **The list is capped.** It returns at most the hundred most recent rows
inside the window; when it hits that ceiling it says so under the
heading. A busy household can reach the cap in far less time than the
retention window, and the oldest line on screen is then the oldest line
shown, not the oldest that exists.
## What this does not change about the instance
Stated plainly, because a sharing feature is exactly the moment somebody
re-reads the trust model:
- **The operator could always read the database.** Anyone with server or
database access, and anyone with an admin account on this instance, can
reach health data directly. That was true before sharing existed and is
unchanged by it. On a household instance the operator is usually one of
the people using it; on an instance hosting other people, it is worth
saying out loud.
- **Encryption at rest is instance-keyed, not per-user.** The encrypted
columns are protected by the key in `ENCRYPTION_KEYS`, which belongs to
the instance. Sharing does not weaken that, and it never did protect one
account's data from the operator of the same instance.
- **AI processing stays under the record owner's consent**, because the AI
surfaces are not part of what sharing covers.
## For operators
Nothing to configure. Sharing is available on every instance, needs no
environment variable, and does nothing until one account invites another.
The same is true of managed profiles.
Four operational notes:
- **Invitations disclose whether a username exists.** An invitation to a
name nobody uses is refused with "no account with that name". That is
deliberate: the alternative is a silent pending row that will never be
accepted because the owner mistyped. The caller is already
authenticated and the endpoint allows ten invitations an hour per
account, which bounds how fast the surface could be walked.
- **Deleting an account** removes the grants it is party to. The audit
rows naming that account as the one who opened somebody's record stay,
and render as "a deleted account" — nulling them would turn "your
daughter opened your record" into "you opened your record", which is
worse than an unresolvable id. Deleting the last guardian's account is
refused while the managed profile would survive it, so an account
deletion cannot strand a record.
- **A managed profile is a user row and appears as one.** It is listed in
the admin user list like any other account, with no e-mail address
beside it and an internal username nobody is ever asked to type. No
login path will accept it: there is no password hash to verify against
and no address to look it up by.
- **The second-factor requirement is not the same on both features, and
the difference is deliberate.** Creating a managed profile, deleting
one and inviting a second guardian require a second factor
unconditionally: an account with none enrolled is refused and told to
set one up, because those acts create or end a permanent relationship
over somebody who cannot object. Offering manage access on an ordinary
invitation asks for a fresh factor only from an account that has one, so
an instance where nobody has enrolled a factor can still use every level
of ordinary sharing. All of them are browser-only either way.
+101
View File
@@ -0,0 +1,101 @@
# Document picker — Paperless-ngx and Papra
People who keep their paperwork in Paperless-ngx or Papra can search it from
HealthLog and import the documents they pick: under "Link a document" on a
visit, a vaccination or a condition, and from the Documents page. They search
by document name, narrow by tag and date, tick what they want, and HealthLog
fetches those files and stores its own encrypted copy, exactly as if they had
been uploaded.
The picker is off until the operator names the instances HealthLog may
contact.
## Turning it on
List the origins in the server environment:
```env
DOCUMENT_SOURCE_ORIGINS="https://paperless.example.com,http://papra.lan:1221"
```
The variable is on the `docker-compose.yml` whitelist, so setting it in `.env`
is enough; restart the app container afterwards. Unset or empty, the settings
card and every import button stay hidden and the routes answer 404.
Each entry is one `scheme://host[:port]`, the grammar
`NOTIFICATION_PRIVATE_ORIGINS` uses (see [notifications](notifications.md)):
- only `http` and `https`; scheme, host and port must match what a person
enters (`https://paperless.example.com:8443` and
`https://paperless.example.com` are two different entries);
- no path, query, credentials, wildcard or CIDR; a person may still enter a
base address with a path (`https://example.com/paperless`) as long as its
origin is listed;
- the unspecified address, link-local and the cloud-metadata range can never
be listed, and a listed name that resolves there is refused when HealthLog
connects;
- a malformed entry is logged once at startup, reduced to scheme and host, and
grants nothing; the valid entries beside it keep working.
Unlike the notification list, this list is the whole decision: an origin
that is not listed is refused even when it is a public address. Removing an
entry cuts off the connections that point at it on their next request; people
can still delete their stored connection.
## What each person sets up
Settings → Integrations → Document archives:
- **Paperless-ngx:** the base address and an API token (Paperless-ngx: My
Profile → API token). Paperless-ngx 2.16 or later (API version 9).
- **Papra:** the base address, the organization id (from the Papra address
bar, `org_` followed by 24 letters and digits) and an API key with
`documents:read` and `tags:read`. The connection test reads the tags too,
so a key without `tags:read` is refused at save.
HealthLog tests the connection before saving it. A saved token is only ever
sent to the address it was saved for: changing the address to another origin
asks for the token again. The token is stored
encrypted (AES-256-GCM, rotated with the other keys by
`scripts/rotate-encryption-key.ts`) and is never shown again, not even in
part.
## What leaves the server, and when
Only requests the person starts: a search, the tag list for the filter, a
connection test, and one download per picked document. There is no background
sync and no polling. Every request goes to the listed origin only, with
redirects refused, a 10-second limit for searches and 60 seconds for a file,
and a size cap on every answer (1 MiB for a search page, the vault's per-file
limit for a document).
## Limits and rules
- Name search on Paperless-ngx uses its own title filter. On a Paperless-ngx
that stores its data in SQLite, that filter ignores upper and lower case
only for plain ASCII letters: searching `röntgen` does not find `Röntgen`.
That is Paperless-ngx's behaviour, not HealthLog's; PostgreSQL-backed
Paperless does not have it.
- A document deleted in HealthLog is recognised by its content during the
30-day undo window, so the same file from another archive is not stored
again; after the purge only its ids are remembered.
- Imports count against the person's normal upload allowance (60 an hour) and
storage quota.
- A document that is already in HealthLog is not stored twice, and one the
person deleted in HealthLog is not brought back by picking it again. Each
import is keyed by system, instance (the archive's origin) and document id,
so the same id on two Paperless-ngx instances is two documents; a key
imported before v1.39.3 carries no instance and matches any instance. These
are the same rules the document token and `scripts/import-documents.mjs`
follow.
- A picked document follows the person's own automatic AI reading setting.
- Only the owner of a record can connect an archive or import from it. People
with shared access to a record, whatever their level, do not see the picker.
- Connections are not part of backups. After a restore on another server,
each person reconnects (one form); the imported documents themselves are in
the backup with the rest of the vault.
- Delete all data and account deletion remove the connection and its token.
- A stored connection stays visible under Settings, read-only, when this
variable is unset or the person switched Documents off, so it can still be
removed.
+93 -28
View File
@@ -3,24 +3,66 @@
The admin login overview shows a coarse `City, CC` location and a carrier
next to every sign-in. Two tiers can produce that:
- **Online.** A third-party lookup, `https://ipwho.is` by default. Free,
keyless, and on by default — which also means every login IP address of
every account on the instance leaves the host.
- **Offline.** MaxMind's GeoLite2-City and GeoLite2-ASN databases read
from a local directory. The ASN database is the authoritative source
for the carrier and the AS number. Note that the resolver is
online-first: having the databases in place is not by itself enough to
stop the outbound lookup, see "Turning the online lookup off entirely"
below.
for the carrier and the AS number. The resolver reads these first: an
address the local databases can place never leaves the host.
- **Online.** A third-party lookup, `https://ipwho.is` by default. Free,
keyless, and the only tier on a host without the databases — which
means every login IP address of every account on that instance leaves
the host. With the databases mounted it sees only the addresses they
could not place, and you can switch it off entirely (below).
The offline tier is optional and absent by default. The published image
only carries the databases when the image build had a MaxMind licence key
(`scripts/fetch-geolite2.sh`, run from the release workflow), which is a
build-time decision you do not control when you pull `:latest`. Bringing
your own copy is the way to get the offline tier on a self-host, and it
is the subject of this page.
build-time decision you do not control when you pull `:latest`. Two ways
get the offline tier onto a stock `:latest` self-host, and both are on this
page: let the app **fetch the databases itself** at runtime (simplest, one
env var), or **bring your own** copy and mount it.
## What you need
## Runtime fetch (one env var)
Set a MaxMind licence key and the app downloads the databases itself — no
rebuild, no mount, no `geoipupdate` on the host.
1. Create a free MaxMind account at
<https://www.maxmind.com/en/geolite2/signup>, then a licence key under
**My Account → Manage License Keys**. GeoLite2 is free; the account and
key exist because MaxMind requires them for the download.
2. Put the key in your `.env`:
```env
MAXMIND_LICENSE_KEY="your-licence-key"
```
`MAXMIND_LICENSE_KEY` is on the compose `environment:` whitelist, so a
value in `.env` reaches the container. Leave `GEOLITE2_DIR` unset to use
the default `/opt/geolite2`, which the image already owns as the app
user for exactly this write.
3. `docker compose up -d`. On the next worker boot the app fetches
`GeoLite2-City.mmdb` and `GeoLite2-ASN.mmdb` into `GEOLITE2_DIR` and
starts reading them — no restart needed beyond the one that picks up the
new env var. It refreshes once a month afterwards (MaxMind reissues on
the first Tuesday), so a keyed host stays current on its own.
The fetch is fail-soft: if the key is wrong or MaxMind is unreachable, the
previous state stands (the online provider keeps answering) and the worker
log carries the reason. It never writes a partial database. Confirm it
landed under **Admin → System status** (`Geo data: Offline (GeoLite2)`) or
from the host: `docker compose exec app ls -l /opt/geolite2`.
If you would rather not have the app reach MaxMind on its own schedule —
for example you keep a curated database copy — skip the key and use
**bring your own** below instead. The two do not conflict: a read-only
bind mount wins, because the runtime fetch cannot write over it and just
fails soft.
## Bring your own (mount a copy)
### What you need
- A free MaxMind account. Sign up at
<https://www.maxmind.com/en/geolite2/signup>, then create a licence key
@@ -30,7 +72,7 @@ is the subject of this page.
two `.mmdb` files onto the host. Most distributions package
`geoipupdate`; there is also an official container image.
## Setup
### Setup
1. Pick a directory on the host and fetch both databases into it. With
`geoipupdate`, `/etc/GeoIP.conf` looks like this:
@@ -53,10 +95,15 @@ is the subject of this page.
```yaml
volumes:
- /srv/healthlog/geolite2:/var/lib/geolite2:ro
- ./geolite2:/opt/geolite2:ro
```
3. Point the runtime at the container path:
Swap the host side (`./geolite2`) for your directory, e.g.
`/srv/healthlog/geolite2`.
3. `/opt/geolite2` is the default value of `GEOLITE2_DIR`, so mounting
at that container path needs no env var at all. Only if you mount at
a different container path do you set it:
```env
GEOLITE2_DIR="/var/lib/geolite2"
@@ -73,13 +120,16 @@ is the subject of this page.
## Turning the online lookup off entirely
Once the offline tier resolves, the third-party lookup is redundant. To
stop all IP egress:
With the databases mounted, the third-party lookup already only sees
addresses they could not place. To remove that remainder too:
```env
IP_GEO_LOOKUP_DISABLED="1"
```
`true` and `yes` work as well. Any other value, including an empty one, leaves
the lookup on.
The resolver then uses only the local databases and returns nothing when
they miss, rather than asking anyone. An instance handling other people's
health data is a reasonable place to make that trade.
@@ -88,28 +138,41 @@ health data is a reasonable place to make that trade.
MaxMind reissues GeoLite2 on its own schedule, and a stale city database
is quietly wrong rather than loudly broken — it keeps answering, with
last month's allocations. Run `geoipupdate` on a schedule (a weekly cron
or systemd timer is enough) against the same directory.
last month's allocations.
The reader loads each database once per worker process and holds it, so a
refreshed file on the host is picked up at the next container restart,
not immediately. A weekly `geoipupdate` followed by
The **runtime fetch** handles this for you: it re-downloads both databases
once a month and resets the reader in place, so a keyed host stays current
with no cron of your own and no restart.
The **bring-your-own** path is yours to keep fresh. Run `geoipupdate` on a
schedule (a weekly cron or systemd timer is enough) against the same
directory. The reader loads each database once per worker process and holds
it, so a refreshed file on the host is picked up at the next container
restart, not immediately. A weekly `geoipupdate` followed by
`docker compose restart app` keeps the two in step.
## Licence and attribution
The databases are downloaded under your own MaxMind account, so their
terms are between you and MaxMind — read what your account agrees to at
<https://www.maxmind.com/en/geolite2/eula>. HealthLog's own attribution
("this product includes GeoLite2 data created by MaxMind") is already on
the `/about` page and covers an instance that uses them.
<https://www.maxmind.com/en/geolite/eula>. That agreement, the GeoLite
End User License Agreement, incorporates CC BY-SA 4.0 by reference and
controls wherever the two disagree; both require you to attribute the
data to MaxMind if you make it available to anyone else.
HealthLog's own attribution ("This product includes GeoLite2 data
created by MaxMind, available from https://www.maxmind.com") is already
on the `/about` page and covers an instance that uses them. Keep that
page reachable — it is what carries the attribution for your deployment,
and it is served without a session for exactly that reason.
## Troubleshooting
**System status still says the online provider.** The readiness check
requires `GeoLite2-City.mmdb` to exist in `GEOLITE2_DIR` and no `.empty`
marker file beside it. Check the path from inside the container:
`docker compose exec app ls -l /var/lib/geolite2`. An empty listing means
`docker compose exec app ls -l /opt/geolite2` (or your `GEOLITE2_DIR`
value). An empty listing means
the bind mount did not land; a `.empty` file means the image was built
without a licence key and you are still reading the baked-in directory
rather than your own.
@@ -120,6 +183,8 @@ the value is in `.env` but not on the `environment:` whitelist — compare
against `docker-compose.yml`.
**The carrier column is empty.** The carrier also comes from the online
provider's ISP field, so it is normally filled even without the ASN
database. If both tiers are off (`IP_GEO_LOOKUP_DISABLED="1"` and no
`GeoLite2-ASN.mmdb`), there is no source for it and it stays empty.
provider's ISP field, but the online lookup only runs for an address the
City database could not place. On a host with `GeoLite2-City.mmdb` and no
`GeoLite2-ASN.mmdb`, a location that resolves locally has no carrier to
go with it — mount the ASN database too. With neither database, the
online provider fills both, unless `IP_GEO_LOOKUP_DISABLED="1"` is set.
+102 -7
View File
@@ -13,13 +13,26 @@ already installed, longer if a TLS-fronted public hostname is in scope
unchanged.
- **2 GB RAM, 10 GB free disk.** The Postgres data volume grows with
measurement history; the Apple Health import worker can briefly
hold a 1.5 GB upload in `/tmp` while it parses.
hold a 1.5 GB upload in `/tmp` while it parses. The app container is
capped at `APP_MEMORY_LIMIT`, `1536m` by default (Node then sizes its
heap at about 792 MB). On a 2 GB host that leaves too little for
Postgres and the system, so set `APP_MEMORY_LIMIT=1g` in `.env`
(a heap of about 524 MB); a long-used account then runs closer to
that heap, and the weekly backup with it.
- **Outbound HTTPS** to `ghcr.io` (image pulls) plus whichever
integration endpoints you plan to enable (Withings, OpenAI, etc.).
The opt-in environmental-context module additionally reaches
`api.open-meteo.com` for weather and daylight; it stays off until you
`archive-api.open-meteo.com` and `geocoding-api.open-meteo.com` for
weather and daylight; it stays off until you
enable it and set a home location, and every outbound call goes
through the SSRF-guarded egress wrapper.
Three requests happen by default without anything connected: the
HaveIBeenPwned range query when a password is set (only the first five
characters of the password's SHA-1 are sent), a daily check of the
GitHub releases API for the update badge, and the online IP
geolocation lookup for login events. `PASSWORD_BREACH_CHECK_DISABLED`,
`UPDATE_CHECK_DISABLED` and `IP_GEO_LOOKUP_DISABLED` turn each off; see
`.env.production.example`.
- **Optional but recommended:** a reverse proxy that terminates TLS
and forwards to `http://localhost:3000` (Caddy, Traefik, Nginx
Proxy Manager, Coolify, or bare Nginx — see `reverse-proxy.md`).
@@ -32,9 +45,11 @@ cd HealthLog
cp .env.example .env
```
`.env.example` is the canonical reference for every env var the app
reads. Anything you do not uncomment falls back to a sane default or
disables the optional subsystem.
`.env.example` is a short starter with the variables most self-hosts
touch. The complete reference, with every variable the app reads and what
it does, is `.env.production.example`; CI checks that file against
`scripts/env-manifest.json`. Anything you do not set falls back to a sane
default or leaves the optional subsystem off.
## 2. Generate the three required secrets
@@ -170,6 +185,7 @@ NEXT_PUBLIC_DASHBOARD_SNAPSHOT=false pnpm build
| Next step | File |
| ------------------------------------------------------------------- | ------------------------------------- |
| TLS + reverse-proxy configuration | `docs/self-hosting/reverse-proxy.md` |
| Tailnet-only HTTPS via `tailscale serve` (no reverse proxy) | `docs/self-hosting/tailscale.md` |
| Push notifications — Web Push, Telegram, ntfy, webhook, email, APNs | `docs/self-hosting/notifications.md` |
| Web/worker process split for horizontal scale | `docs/self-hosting/scaling.md` |
| Off-host encrypted backups to S3/R2/B2 | `docs/ops/backup-restore.md` |
@@ -191,10 +207,18 @@ NEXT_PUBLIC_DASHBOARD_SNAPSHOT=false pnpm build
`app_settings.singleton.registrationEnabled`. The admin panel can
flip it back if a previous owner closed it.
- **Service unreachable on `localhost:3000`.** Check `docker compose
ps` — the `app` healthcheck polls `/api/version` every 30 seconds
and will mark the container unhealthy if Postgres is still
ps` — the `app` healthcheck polls `/api/health` every 30 seconds
(it returns 503 while the database or worker is down) and will mark
the container unhealthy if Postgres is still
starting. Tail `docker compose logs db` to confirm Postgres came up
cleanly.
- **The login page says "Signing in cannot complete on this page".** The
server sets its session cookie with the `Secure` flag (the production
default) and the page was opened over plain `http://`, where the browser
would drop it. Set `SESSION_COOKIE_SECURE=false` for a server reached only
over HTTP on a private network, or open the `https://` address (behind a TLS
proxy, make sure it forwards `X-Forwarded-Proto: https`). The sign-in is
refused before any password, code or ticket is used.
- **OAuth callbacks loop back to localhost.** Confirm `APP_URL` and
`NEXT_PUBLIC_APP_URL` both point at the public hostname, not at
`localhost`, and restart `app` after the change.
@@ -214,6 +238,77 @@ ps` — the `app` healthcheck polls `/api/version` every 30 seconds
`pull_policy: always` on the `app` service, and verify the running
build with `GET /api/version` (it returns `version` + `buildSha`).
## Back up your encryption key
`ENCRYPTION_KEY` (or the `ENCRYPTION_KEYS` map) is not stored in the database.
Without it, the encrypted parts of the database and every in-database backup
cannot be read. Keep a copy outside the server, then confirm it under Admin,
Encryption: the step shows the key id and a fingerprint (the first 12 hex
characters of SHA-256 over the key) and can check a pasted copy without
storing it. Admins see a dashboard reminder until the active key is confirmed.
| Platform | Where the key is set |
| --------- | --------------------------------------------------------------- |
| Compose | `.env` next to `docker-compose.yml` |
| TrueNAS | Apps, HealthLog, Edit, Environment |
| Coolify | the application's Environment Variables |
| Unraid | the container template (Docker tab, Edit) or the Compose `.env` |
| Portainer | the stack's Environment variables |
Set `HEALTHLOG_PLATFORM` (`compose`, `truenas`, `coolify`, `unraid`,
`portainer`) to open the step on your platform's instructions.
To compute the fingerprint of your copy:
```bash
echo -n "<your key>" | xxd -r -p | sha256sum | cut -c1-12
```
**HealthLog refuses to serve: encryption key does not match this database.**
At start the app checks that its key opens the stored data. If it does not,
every API request answers `503` with `meta.errorCode`
`encryption.key_mismatch`, `/api/health` answers `503` with
`reason: "encryption_key_mismatch"`, and background jobs are not started.
Restore the original key, point `DATABASE_URL` at the matching database, or
start with an empty database; then restart.
The check remembers the key it first saw for each key id in the table
`encryption_key_canaries`. Before it records a key, it reads the oldest
encrypted values in the database and records the key only if they open, or
if the database holds no encrypted value under that key id at all. When the
stored data proves neither (a single unreadable value, the oldest values
failing while newer ones open, or a probe that ran out of time), the app
keeps serving, records nothing, logs a warning that starts with
`[boot] Encryption key check inconclusive`, and checks again at the next
start.
If you are certain the configured key is the one your data was written
with, and the check still refuses because it recorded a different key
earlier, reset the check for that key id and restart. The refusal in the log
prints the exact statement; for the default key id it is:
```bash
docker compose exec -T db psql -U healthlog healthlog \
-c "DELETE FROM encryption_key_canaries WHERE key_id = 'v1';"
docker compose restart app
```
The next start probes the stored data again and records the key only if
that data opens with it. Do this only when you are sure: if the key is in
fact wrong, the app serves errors on every encrypted value instead of the
one clear refusal. After a key rotation the rotation script removes the
record of a retired key id itself, once it reports that no values remain
under that id.
At a first start there is no record yet, so there is nothing to reset. If
the check refuses there and you are certain the key is right, the last
resort is `ENCRYPTION_KEY_CHECK=warn` (default `enforce`): the check still
runs and logs its full result, `/api/health` names it as
`warning: "encryption_key_mismatch"` without failing, requests are served,
and no key is recorded while the check does not pass. This disables a
safety check. With a wrong key every encrypted value fails and new rows are
written under that key, so remove the setting once the key is confirmed.
## Backup and restore
Your database is the only stateful piece — back it up, and back up the
+7 -5
View File
@@ -30,7 +30,7 @@ Three things must be true before `/mcp` will answer:
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`APP_URL` is set** | The endpoint fails closed without a pinned canonical origin. `APP_URL` (or `NEXT_PUBLIC_APP_URL`) is the origin every OAuth document and audience check is anchored to — `Host` is never trusted. Without it the surface stays invisible (`404`). |
| **The global API is on** | The operator's instance-wide API switch must be enabled (it is by default). With it off, every token path — including `/mcp` — returns `404`. |
| **The `mcp` module is on** | A per-account opt-in. It is the only module that ships dark; you turn it on in Settings. Until then `/mcp` answers `404` for that account. |
| **The `mcp` module is on** | A per-account opt-in that ships off by default; you turn it on in Settings. Until then `/mcp` answers `404` for that account. |
`APP_URL` is the same origin you already use for passkeys and invite
links — for example `https://health.example`. It must be reachable by the
@@ -113,10 +113,12 @@ access token (60 minutes, with a refresh token) behind the scenes.
2. In ChatGPT's **default** (non-Developer) mode, the only tools it will
call are **`search`** and **`fetch`** — these are HealthLog's two-tool
retrieval façade over the same server-authoritative reads. So in
default ChatGPT you ask in natural language ("what's my recent LDL?")
and it searches your record and fetches the matching item with a
citation deep-link back into the app. Developer mode exposes the full
tool catalogue.
default ChatGPT you ask in natural language ("what's my recent LDL?",
"when was my left knee operation?", "what does the discharge letter
say?") and it searches your record and fetches the matching item with a
citation deep-link back into the app. Search covers metrics,
medications, lab values, visits and procedures, conditions, documents
and vaccinations. Developer mode exposes the full tool catalogue.
### Claude Desktop (stdio)
+155 -14
View File
@@ -91,10 +91,8 @@ VAPID_PRIVATE_KEY="...(private key)"
VAPID_SUBJECT="mailto:you@example.com"
```
The database values win when both are present. The loader also accepts a
few aliases (`WEB_PUSH_VAPID_PUBLIC_KEY`, `WEB_PUSH_PUBLIC_KEY`, and the
private/subject equivalents) so a config copied from another deployment
keeps working.
The database values win when both are present. These three names are the
only ones the loader reads.
### 3. Subscribe a device
@@ -182,16 +180,18 @@ HealthLog publishes to that topic.
server if you self-host ntfy) and **Topic**, then save.
If your ntfy server requires auth, an access token can be attached; the
server URL is validated as a public host and dialled through the egress
guard (`src/lib/notifications/senders/ntfy.ts`). Urgent events are sent at
ntfy's top priority (`5` / max) so they bypass batching and surface on the
lock screen.
server URL is validated at save time and dialled through the egress guard
(`src/lib/notifications/senders/ntfy.ts`). A self-hosted ntfy on your own
network needs the operator grant described under [Notification targets on
a private network](#notification-targets-on-a-private-network). Urgent
events are sent at ntfy's top priority (`5` / max) so they bypass batching
and surface on the lock screen.
## Webhook
The generic webhook POSTs every enabled event as JSON to a URL you own —
wire it into your own automation (Home Assistant, n8n, a Discord/Slack
relay, whatever routes the payload). You supply a public URL and,
relay, whatever routes the payload). You supply the URL and,
optionally, one custom header (e.g. an auth token).
1. In HealthLog open `/settings/notifications`, fill the Webhook card's
@@ -199,11 +199,152 @@ optionally, one custom header (e.g. an auth token).
**header value**.
2. Save. A Test button fires a one-off POST so you can confirm routing.
The URL is validated as a public host and dialled through
`safeFetch({ requirePublicHost: true })` — the SSRF guard blocks private
and loopback ranges because the target is user-supplied
(`src/lib/notifications/senders/webhook.ts`). The webhook carries the
event's urgency flag so you can route urgent events differently.
The URL is validated at save time and dialled through `safeFetch` with
the connect-time resolver pin — the SSRF guard refuses a target that
resolves to a private or loopback address because the target is
user-supplied (`src/lib/notifications/senders/webhook.ts`). A Gotify or
Home Assistant on your own network needs the operator grant described in
the next section. The webhook carries the event's urgency flag so you can
route urgent events differently.
### What the webhook sends
Every event is one `POST` with `Content-Type: application/json` and the
one header you configured. It goes to the URL exactly as you saved it:
nothing is added to the path or the query. The body depends on the
**Payload format** you choose on the card. The examples below are what the
Test button sends.
**Generic JSON** is the default, and what every webhook saved before the
choice existed keeps sending:
```json
{
"title": "HealthLog Test",
"message": "HealthLog: Connection successful! Webhook notifications are active.",
"eventType": "SYSTEM_ALERT",
"priority": "default"
}
```
- `title` and `message` are plain text. HTML tags are stripped, and routine
reminders lose their decorative emoji.
- `eventType` is the event name, for routing rules. With discreet cycle
notifications on, a cycle event arrives as `reminder`, and its title and
message are masked as they are on every other channel.
- `priority` is a word: `urgent` for an event flagged urgent, `high` for
medication reminders, `default` for everything else.
**Gotify** sends the body Gotify's `POST /message` endpoint expects:
```json
{
"title": "HealthLog Test",
"message": "HealthLog: Connection successful! Webhook notifications are active.",
"priority": 5,
"extras": {
"client::display": { "contentType": "text/plain" },
"healthlog::event": { "type": "SYSTEM_ALERT" }
}
}
```
- `priority` is an integer: `5` for most events, `8` for medication
reminders, `10` for urgent events. The Gotify Android app plays a sound
from 4 and shows a heads-up banner from 8, so routine events are audible
and reminders pop up on screen.
- `extras` tells Gotify clients to show the message as plain text and
carries the event name, which is `reminder` for a discreet cycle event.
The generic body does not work with Gotify. Gotify reads `priority` as a
number, so the word `default` makes it answer `400 Bad Request`.
### Sending to Gotify
1. In Gotify, create an application and copy its token.
2. On the Webhook card, set **URL** to your Gotify address ending in
`/message`, for example `https://gotify.example.com/message`.
3. Set **Header name** to `X-Gotify-Key` and **Header value** to the
application token. Gotify also accepts the token as `?token=` on the URL,
but in a header it stays out of proxy access logs.
4. Set **Payload format** to **Gotify**, save, and press Test.
If the test fails, the card shows the status Gotify answered and, when it is
short, Gotify's own error text. A `401` means the token is wrong. A `400`
means Gotify could not read the body; check that the format is set to
Gotify. A Gotify on your own network also needs the operator grant below.
The detail reaches the card inside the server's `502` response. A reverse
proxy that replaces error pages for 5xx responses, such as Traefik's
`errors` middleware or nginx with `proxy_intercept_errors on`, swaps that
response for its own page, and the card can then only say "Test failed".
Exclude the `/api/` paths from the error-page rule to keep the detail. This
applies to the ntfy and email tests too.
## Notification targets on a private network
Every webhook and ntfy target is resolved at send time and refused when
the answer is a private, loopback, link-local or CGNAT address. That is
the DNS-rebinding defence, and it applies to a public-looking name with a
LAN A record (a Gotify behind Nginx Proxy Manager with a DNS-01
certificate) exactly as it applies to `http://192.168.1.20`. The test
button and the scheduled delivery take the same decision, so a test that
fails with "Private network target" means nothing would have arrived
either.
The operator opens a target by listing its exact origin in the server
environment:
```env
NOTIFICATION_PRIVATE_ORIGINS="https://gotify.example.com,http://ntfy.lan:8080"
```
Each entry is one `scheme://host[:port]`, the same grammar as
`NIGHTSCOUT_PRIVATE_ORIGINS`:
- only `http` and `https`; scheme, host and effective port must all match
what the user saves (`https://gotify.example.com:8443` and
`https://gotify.example.com` are two different grants);
- no path, query, credentials, wildcard (`*.lan`) or CIDR (`10.0.0.0/8`) —
a range grant would let a DNS rebinding to any address in the range pass
the pin, so an operator with several relays lists several origins;
- listing a host does not list its sub-hosts or sibling ports;
- the unspecified address (`0.0.0.0`, `::`), link-local and the
cloud-metadata range (`169.254.0.0/16`, `fe80::/10`) cannot be granted: a
literal entry is logged once and ignored, and a listed name that resolves
there is refused at dial time;
- RFC1918, IPv6 unique-local, CGNAT (a Tailscale address or MagicDNS name)
and, on a host-network deployment, loopback (`http://127.0.0.1:8080`,
`http://localhost:8080`, `::1`) are what the list is for — an exact
loopback origin with its port is as deliberate a decision as a LAN one;
- a malformed entry is logged once at first use and grants nothing; the
valid entries beside it keep working.
A listed origin is still dialled through the pinned resolver with
redirects forbidden, so a relay that answers with a redirect to another
host is refused. The variable has to be on the compose `environment:`
whitelist to reach the container; the published `docker-compose.yml`
lists it. Restart the app after changing it.
What is refused where, so you know which lever to pull:
| Target | Without the grant | With the exact origin listed |
| ----------------------------------------------------------- | ----------------- | ---------------------------------------------- |
| Public name resolving to a public address | works | works, public pin |
| Public name with a private A record (LAN reverse proxy) | refused at send | works |
| `gotify.lan`, `gotify.home.arpa`, a Docker service name | refused at send | works |
| `gotify.local` (mDNS) | refused at save | allowed, if the container resolves mDNS |
| Literal `192.168.x.x`, `10.x.x.x`, `100.64.x.x`, `fd00::/8` | refused at save | works |
| `localhost`, `127.0.0.1`, `::1` (host networking) | refused at save | works |
| `0.0.0.0`, `169.254.169.254`, `fe80::…` | refused at save | still refused (`private_origin_not_grantable`) |
A private target that is not listed is refused when the card is saved
(`422`, `meta.errorCode` = `private_origin_not_approved`, the message
names the variable; a link-local, metadata or unspecified target answers
`private_origin_not_grantable` instead, because no grant can open it) or, for a DNS name the save cannot classify, when the
test button or a reminder dials it. The resolved address is never shown
to the user. Telegram, email and Web Push are not affected: their hosts
are not user-supplied.
## Email (SMTP)
@@ -30,6 +30,18 @@
"label": "API token HMAC key",
"description": "Generate with: openssl rand -hex 32"
},
{
"name": "HEALTHLOG_PLATFORM",
"label": "Platform hint",
"description": "Opens the admin's encryption key backup step on the Portainer instructions.",
"default": "portainer"
},
{
"name": "ENCRYPTION_KEY_CHECK",
"label": "Encryption key check",
"description": "enforce refuses to serve when the key does not open the stored data. warn only logs it: a last resort for a refusal you are certain is false; it disables a safety check.",
"default": "enforce"
},
{
"name": "SESSION_COOKIE_SECURE",
"label": "Session cookie Secure flag",
+47 -16
View File
@@ -3,12 +3,17 @@
The bundled `docker-compose.yml` exposes HealthLog on plain HTTP at
`localhost:3000`. Production deployments front the container with a
reverse proxy that terminates TLS, sets the forwarded headers the
rate-limiter trusts, and preserves the WebSocket upgrade path the
streaming Coach surface depends on.
rate-limiter trusts, and passes the Coach's Server-Sent Events stream
through unbuffered with a generous read timeout.
This guide gives copy-paste blocks for five common fronts. Pick one;
the env-var pairing is identical across them.
If the instance only needs to be reachable from your own devices, none
of them is required: `tailscale serve` terminates trusted HTTPS on the
tailnet with no extra container. See
[`docs/self-hosting/tailscale.md`](tailscale.md).
## Pre-flight — env vars the proxy interacts with
| Variable | Required for | Notes |
@@ -21,6 +26,13 @@ Set the URL pair to the public origin (`https://your-instance.example.com`)
and restart the `app` container. The image reads both at startup; no
rebuild needed.
All three variables are on the shipped `docker-compose.yml`
`environment:` whitelist, so a value in `.env` reaches the container
without editing the compose file. (Before v1.37.33 the whitelist was
missing `TRUST_PROXY_HOPS`; on those versions add
`TRUST_PROXY_HOPS: "${TRUST_PROXY_HOPS:-}"` to the `app` service's
`environment:` block yourself.)
### `TRUST_PROXY_HOPS` — what to set it to
`src/lib/api-response.ts` (`getClientIp`) reads the `X-Forwarded-For`
@@ -28,17 +40,29 @@ chain from the **right**, counting back `TRUST_PROXY_HOPS` entries.
This guards against a client rotating `X-Forwarded-For` per request
to defeat IP-based rate limits.
| Topology | `TRUST_PROXY_HOPS` |
| --------------------------------------------------------- | -------------------------- |
| App is internet-facing with no proxy | `0` (XFF ignored entirely) |
| Single proxy in front (Caddy / Traefik / Nginx / Coolify) | `1` (default) |
| Cloudflare → your proxy → app | `2` |
| Cloudflare → Coolify-Tunnel → Coolify → app | `3` |
| Topology | `TRUST_PROXY_HOPS` |
| --------------------------------------------------------- | ------------------------------------- |
| App is internet-facing with no proxy | `0` (no forwarding header is trusted) |
| Single proxy in front (Caddy / Traefik / Nginx / Coolify) | `1` (default) |
| Cloudflare → your proxy → app | `2` |
| Cloudflare → Coolify-Tunnel → Coolify → app | `3` |
A misconfigured count logs a one-shot warning to stderr and collapses
every anonymous caller into one shared rate-limit bucket. Match the
value to the actual hop count or set it to `0` and let `x-real-ip`
drive the IP resolution.
value to the actual hop count.
`X-Real-IP` gets the same trust as `X-Forwarded-For`. It is read only
when `TRUST_PROXY_HOPS` is exactly `1` and the request carries no
`X-Forwarded-For`, which covers a single proxy that sets only
`X-Real-IP`. With `0` neither header is believed, because without a proxy
in front both come from the caller. With `2` or more, the hop count
describes an `X-Forwarded-For` chain, so have your proxies send one.
If requests arrive with a forwarding header the setting does not let
HealthLog read, the log shows one warning naming the header and the
setting. Every anonymous caller then shares one rate-limit bucket, so one
person mistyping a password can hold sign-in back for everyone. The usual
cause is `0` behind a proxy that sends only `X-Real-IP`: set `1`.
## Caddy
@@ -56,8 +80,8 @@ your-instance.example.com {
}
```
Caddy handles the WebSocket upgrade automatically. `flush_interval -1`
disables response buffering so the streaming insight events surface
`flush_interval -1`
disables response buffering so the SSE events surface
without batching delays. With Caddy as the only hop, leave
`TRUST_PROXY_HOPS=1`.
@@ -78,8 +102,9 @@ services:
- "traefik.http.routers.healthlog.middlewares=healthlog-headers"
```
Traefik forwards `X-Forwarded-For` by default and respects the WebSocket
upgrade. Pair with `TRUST_PROXY_HOPS=1`. If Traefik sits behind
Traefik forwards `X-Forwarded-For` by default and does not buffer
responses, so the SSE stream passes through as-is. Pair with
`TRUST_PROXY_HOPS=1`. If Traefik sits behind
Cloudflare, set it to `2` so the rate-limiter reads the real client IP
that Cloudflare placed in the chain.
@@ -91,8 +116,9 @@ In the NPM UI:
2. **Domain Names:** `your-instance.example.com`.
3. **Scheme:** `http`; **Forward Hostname / IP:** the Docker host or
internal hostname; **Forward Port:** `3000`.
4. Enable **Websockets Support** (required for streaming Coach
responses).
4. **Websockets Support** may stay on or off; the Coach stream is
SSE over plain HTTP, not WebSockets. What matters is the buffering
and timeout config in step 6.
5. **SSL tab:** request a Let's Encrypt certificate, force SSL.
6. **Advanced tab — Custom Nginx Configuration:**
@@ -240,6 +266,11 @@ login works over HTTP. The trade-off is explicit: the session
cookie crosses the wire unencrypted, so the network it traverses
needs to be one you control.
For the Tailscale case specifically there is a better option than
lifting the flag: `tailscale serve` gives the same surface real HTTPS
with a tailnet-trusted certificate, and `SESSION_COOKIE_SECURE` stays
unset. See [`docs/self-hosting/tailscale.md`](tailscale.md).
**Do not set this on a deployment that ever serves plain HTTP to the
open internet.** Anyone with passive network access can capture the
session cookie and impersonate the user. The right answer for any
+102 -19
View File
@@ -46,22 +46,95 @@ staging file. The import then fails with a staging-file-missing error
("the import staging file is not visible to the worker"). Two things to
know:
- A pure `web` container has no pg-boss handle, so an import kicked off
there currently returns `503 Background worker is not running`. Run
imports from a container that also runs the worker until send-only
boss support lands.
- A pure `web` container opens a send-only pg-boss connection at boot
(`src/instrumentation.ts`, `startGlobalBossProducer`), so an import
kicked off there is accepted and queued for the worker like any other
job. It answers `503 Background worker is not running` only when that
producer connection could not be opened (the boot log then shows
`Failed to start pg-boss producer`).
- If you run web and worker as separate containers, they **must share
the import staging directory** — mount the same named volume at the
temp path on both — or run imports in single-container (`all`) mode.
Without a shared staging volume, imports in split mode cannot
complete.
## Apple Health import memory
The import parses `export.xml` as a stream: the archive is never
buffered whole, records flush to the database in fixed-size batches,
and what stays resident scales with the data's calendar span, not its
record count. Multi-year exports with millions of records parse within
the default Node.js heap.
Before parsing starts, the worker compares the archive's declared
uncompressed size against the runtime heap limit. If the limit is too
low to carry the export — realistically only when
`--max-old-space-size` was pinned far below the default — the import
fails immediately with a `failureReason` starting with
`insufficient_memory`, naming the required and available amounts.
Raise the limit on the container that runs the worker and re-upload:
```yaml
# docker-compose.yml
services:
app:
environment:
NODE_OPTIONS: --max-old-space-size=1024
```
An import interrupted by a container restart or an out-of-memory kill
does not stay stuck: the worker reconciles non-terminal import jobs at
boot and every 15 minutes, flipping orphaned rows to `failed`
(`interrupted_by_restart`) so the UI offers a retry instead of an
endless spinner.
## Document and lab-scan reads run on the worker (v1.40)
Since v1.40, every AI read of a document or a lab report runs as a
background job on the worker, not inside the HTTP request:
- reading a document for search (the content index),
- a document summary, stored or shown once,
- filing suggestions (title, type, date),
- extracting facts from a stored document for review,
- a lab scan (photo or PDF of a lab report).
The request only queues the read and answers `202`; the client then
polls the run until it ends. That is what keeps a
slow model from being cut off by a proxy timeout in front of the
server. When the enqueue itself fails (no pg-boss connection at all),
the request answers `503` straight away, and nothing is charged.
**"Waiting for the background worker"** is the line the app shows when
a read has sat in the queue for more than 30 seconds without a worker
picking it up. On a single `all` container that is rare and short
(the worker is busy with another job). If it does not go away, no
worker process is consuming the queue: the worker container is
stopped, crashing on boot, or pointed at another database. A run that
no worker picks up within 15 minutes fails as
`aiRuns.workerUnavailable` and its AI budget reservation is handed
back. That sweep is itself a worker job, so with no worker running at
all the run simply stays queued until one starts.
**In a web/worker split, the worker must run the same version as the
web containers.** The web container queues the read; only a worker
that knows the `document-ai-run` queue can execute it. A worker left
on a pre-v1.40 image never takes these jobs, so every document read
and lab scan waits and then fails as above, while everything else
looks healthy. Deploy both from the same image tag
(`HEALTHLOG_IMAGE_REF` is shared by `app` and the `app-worker` block)
and restart the worker together with the web containers.
## Healthchecks
- `app` (web) healthcheck: `wget /api/version` every 30s.
- `app-worker` does not expose a port; its liveness is reported into
the `worker_status` table on every reminder pass and surfaced through
`/api/admin/status`.
- `app` (web) healthcheck: `wget /api/health` every 30s.
- `app-worker` does not expose a port; its liveness is tracked
in-memory inside the process (`src/lib/jobs/worker-status.ts`) and
read back by `/api/admin/status`. In a web/worker split this means
the web container cannot see the separate worker container's
liveness: `/api/admin/status` only reports the worker embedded in
the container that serves the request. Watch the worker container's
own logs and restart policy instead.
The web container does NOT depend on the worker, and vice versa, so
neither container's startup can deadlock the other. The shared
@@ -82,13 +155,21 @@ dependency is Postgres; both wait on `db: condition: service_healthy`.
## Postgres connection-pool sizing
Every container that boots the HealthLog image opens its own
`pg.Pool` against the configured `DATABASE_URL`. The pool ceiling is
**20 connections per container by default** (raised from the library
default of 10 in v1.4.40 to keep the dashboard's analytics fan-out
from starving every other query during a cold mount).
Every container that boots the HealthLog image owns a connection
budget against the configured `DATABASE_URL`. The budget is
**20 connections per container by default** and is split between the
Prisma pool and pg-boss (2 connections). The bundled compose exposes
the knob as `DB_CONNECTION_LIMIT`, baked into `DATABASE_URL` as
`connection_limit`; `DATABASE_POOL_MAX` remains a working explicit
override. Resolution order: `DB_CONNECTION_LIMIT`, then
`DATABASE_POOL_MAX`, then the `connection_limit` URL parameter, then
the default of 20. In the bundled single-container setup
(`HEALTHLOG_PROCESS_TYPE=all`) the web requests and the background
worker run in one process and share that one Prisma pool, so a budget
sized for the web traffic alone leaves the worker's jobs queueing for
the same connections.
Plan total Postgres slots as **container_count × `DATABASE_POOL_MAX`**.
Plan total Postgres slots as **container_count × budget**.
A stock Postgres 16 container ships with `max_connections = 100`, so
the safe envelope is:
@@ -109,9 +190,10 @@ transaction-pooling mode.
### Overriding the per-container pool ceiling
Set `DATABASE_POOL_MAX` to a positive integer on every container that
needs a non-default ceiling — both web and worker pick up the same
env var:
With the bundled compose, set `DB_CONNECTION_LIMIT` in `.env`; it
flows into `DATABASE_URL`'s `connection_limit`. On a hand-rolled
setup, `DATABASE_POOL_MAX` as a plain env var works the same way on
every container, web and worker alike:
```yaml
# docker-compose.yml — example for a 6-container deployment
@@ -146,6 +228,7 @@ tenant, starving every other dashboard query for the duration. The
fan-out — keeps 16 slots free for the rest of the dashboard while
still sitting well under Postgres's 100-slot stock ceiling.
The implementation lives in `src/lib/db.ts → getPoolMax()`; the
The implementation lives in `src/lib/db.ts → getConnectionBudget()`
(split into `getPrismaPoolMax()` and `getPgBossPoolMax()`); the
20-slot default was chosen after measuring on a 4-CPU production
container — see the inline rationale in `getPoolMax()`.
container — see the inline rationale in `src/lib/db.ts`.
+28 -17
View File
@@ -81,11 +81,19 @@ Client registration essentials only — the IdP's own docs cover the rest.
## Security model
- **Identity is pinned, not guessed.** The first OIDC sign-in either
provisions a fresh account or links to an existing account matched by
**verified** email (`email_verified: true` — an IdP that does not
assert verification is rejected). Either way the account is stamped
with the provider's `(issuer, sub)` pair, and every later login
matches on that pair alone. An email change at the IdP updates the
provisions a fresh account or links to an existing account with the
same email, and only when the IdP asserts `email_verified: true` (an
IdP that does not assert verification is rejected). An existing
account is never linked on the email alone: HealthLog never verified
that address, so anyone could have registered it or typed it into a
profile. The browser is sent to the sign-in page instead, and the link
is made when the person signs in to that account once with its own
password (and second factor) or passkey, within ten minutes. Under
`OIDC_ONLY` that password sign-in is allowed for exactly that account.
The iOS app gets `oidc_link_required` and the person confirms once on
the web. Either way the account is stamped with the provider's
`(issuer, sub)` pair, and every later login matches on that pair
alone. An email change at the IdP updates the
displayed email; it can never re-point the login at a different
account. An email that matches an account already pinned to a
_different_ identity is rejected and audited.
@@ -115,9 +123,11 @@ Client registration essentials only — the IdP's own docs cover the rest.
(the routes return 403; hiding the buttons is not the boundary).
Consequences to accept before turning it on:
- **The native iOS app cannot sign in.** It authenticates via
password/passkey only; there is no native SSO flow yet. Do not enable
`OIDC_ONLY` on a deployment with active iOS users.
- **The native iOS app needs a build that ships the SSO flow.** The app
signs in via the native OIDC handoff (`GET /api/auth/oidc/login?client=native`
with PKCE and the fixed `healthlog://` callback) or via password/passkey.
`OIDC_ONLY` works with app builds that carry the handoff; older
password/passkey-only builds are locked out.
- **Existing sessions survive.** The flag gates new sign-ins, not live
sessions — nobody is thrown out at flip time, including
password-authenticated sessions.
@@ -139,12 +149,13 @@ Consequences to accept before turning it on:
## Troubleshooting
| Symptom | Cause / fix |
| --------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Login page shows "Single sign-on failed", log says `discovery issuer mismatch` | `OIDC_ISSUER_URL` must equal the `issuer` inside the discovery document. A single trailing slash either way is tolerated; anything else (scheme, host, port, path, `//`) is a hard reject. |
| `discovery request failed: 3xx` | Discovery redirects are not followed (egress policy pins `redirect: "manual"`). Point `OIDC_ISSUER_URL` at the final URL — e.g. include the realm/application path, match `http` vs `https`, add/remove `www`. |
| IdP shows its own "invalid redirect URI" page | The mismatch happens **at the IdP**, before HealthLog is involved. Compare the registered URI against `${NEXT_PUBLIC_APP_URL}/api/auth/oidc/callback` byte for byte — scheme and port included. |
| Sign-in loops back with "failed" and the log shows an `exp`/`nbf` claim error | Clock skew beyond the 60 s tolerance. Fix NTP on the IdP or app box. |
| "Your identity provider did not mark your email address as verified" | The IdP omits `email_verified` or sends `false`. Mark the address verified at the IdP (Keycloak: user → Email verified; Authentik: verify the email stage) — HealthLog will not link or provision without it. |
| "That email address belongs to an account that is already linked to a different SSO identity" | Deliberate: identities never re-bind silently. See "Linking is once" above. |
| SSO button missing | One of the three provider vars is empty or not whitelisted in compose. `pnpm check-env` shows which. |
| Symptom | Cause / fix |
| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Login page shows "Single sign-on failed", log says `discovery issuer mismatch` | `OIDC_ISSUER_URL` must equal the `issuer` inside the discovery document. A single trailing slash either way is tolerated; anything else (scheme, host, port, path, `//`) is a hard reject. |
| `discovery request failed: 3xx` | Discovery redirects are not followed (egress policy pins `redirect: "manual"`). Point `OIDC_ISSUER_URL` at the final URL — e.g. include the realm/application path, match `http` vs `https`, add/remove `www`. |
| IdP shows its own "invalid redirect URI" page | The mismatch happens **at the IdP**, before HealthLog is involved. Compare the registered URI against `${NEXT_PUBLIC_APP_URL}/api/auth/oidc/callback` byte for byte — scheme and port included. |
| Sign-in loops back with "failed" and the log shows an `exp`/`nbf` claim error | Clock skew beyond the 60 s tolerance. Fix NTP on the IdP or app box. |
| "Your identity provider did not mark your email address as verified" | The IdP omits `email_verified` or sends `false`. Mark the address verified at the IdP (Keycloak: user → Email verified; Authentik: verify the email stage) — HealthLog will not link or provision without it. |
| "An account with this email address already exists here. Sign in to it once …" | The IdP email matches a local account that is not linked yet. Sign in to that account with its password or passkey within ten minutes and the link is made. If nobody knows that account's password, an operator decides which account the identity belongs to. |
| "That email address belongs to an account that is already linked to a different SSO identity" | Deliberate: identities never re-bind silently. See "Linking is once" above. |
| SSO button missing | One of the three provider vars is empty or not whitelisted in compose. `pnpm check-env` shows which. |
+102
View File
@@ -0,0 +1,102 @@
# HealthLog over Tailscale
For a single Docker box that only you and your household need to reach,
`tailscale serve` can stand in for the reverse proxy entirely. Tailscale
terminates HTTPS with a certificate every device on your tailnet already
trusts, there is no extra container to run and nothing to renew, and the
free plan covers all of it. The trade is scope: the instance is reachable
only from devices signed into your tailnet, which for a personal health
record is usually the point.
Two modes exist, and the difference matters more here than for most apps:
- **`tailscale serve`** publishes HealthLog inside your tailnet only.
Every device that should reach it runs the Tailscale client and signs
into the same tailnet, including the iPhone if you use the iOS app.
The instance is invisible from the public internet. This is the right
default for a personal health record.
- **`tailscale funnel`** publishes the same HTTPS endpoint to the public
internet. No client is needed on the phone, but anyone on the internet
can reach the sign-in page, so the instance becomes a public deployment
and needs to be treated like one. Funnel is the deliberate opt-in, not
the default.
## Set up `tailscale serve`
1. Install Tailscale on the Docker host and sign in. On macOS, the
standalone app from tailscale.com is more full-featured than the App
Store build; either works for this page.
2. With the compose stack running on `localhost:3000`, run:
```bash
tailscale serve --bg localhost:3000
```
3. If HTTPS certificates are not yet enabled for your tailnet, the CLI
says so and prints the admin-console link that enables them. Follow
that link once; it is a one-time, per-tailnet step.
4. The CLI prints the HTTPS URL it now serves, of the form
`https://<machine>.<tailnet>.ts.net`. `--bg` persists the
configuration across restarts, so this is a run-once command, not
something to add to a boot script.
## Point HealthLog at the tailnet URL
Set the URL pair in `.env` to the exact HTTPS URL the CLI printed:
```env
NEXT_PUBLIC_APP_URL="https://your-machine.your-tailnet.ts.net"
APP_URL="https://your-machine.your-tailnet.ts.net"
```
Both variables are on the bundled compose `environment:` whitelist, so
values in `.env` reach the container. Restart to pick them up:
```bash
docker compose up -d
```
## Cookies and TLS
`tailscale serve` terminates real HTTPS, so the session cookie's
`Secure` flag works exactly as it does behind any TLS-terminating proxy.
Leave `SESSION_COOKIE_SECURE` unset. The plain-HTTP escape hatch in the
[reverse-proxy guide](reverse-proxy.md) exists for serving the raw
`http://host:3000` surface across a trusted network without a TLS front;
once `serve` fronts the app you do not need it.
`serve` is a single proxy hop in front of the app, which is the topology
the default `TRUST_PROXY_HOPS=1` assumes. If the wide-event log shows a
null client IP after the switch, or every caller lands in one shared
rate-limit bucket, the "Verifying the proxy chain" section of the
reverse-proxy guide shows how to read the mismatch warning and adjust.
## The iOS app and Apple Health
With `serve`, the iPhone reaches the instance the same way every other
device does: install Tailscale from the App Store on the phone, sign
into the same tailnet, then point the HealthLog iOS app at the
`https://<machine>.<tailnet>.ts.net` URL. Apple Health sync works over
this path; from the app's perspective the tailnet URL is an ordinary
HTTPS origin with a trusted certificate.
## Public exposure with `tailscale funnel`
If the instance must be reachable without the Tailscale client, for
example for someone outside your household's tailnet, `tailscale funnel`
publishes the endpoint to the public internet. The command shape mirrors
`serve`; follow the CLI's own output, which walks through any
admin-console enablement funnel needs on your tailnet.
Before opening it, accept what it means: the sign-in page is now
internet-facing. Close public registration once every household member
has an account (the toggle lives in `/admin`, see
[`getting-started.md`](getting-started.md)), and keep the image current
via `pull_policy: always` as documented there. Everything the other
guides say about publicly reachable hosts applies unchanged.
## Costs
The free Tailscale plan is enough for everything on this page.
+122
View File
@@ -0,0 +1,122 @@
# HealthLog on TrueNAS SCALE
HealthLog runs on TrueNAS SCALE as a Docker app: one `app` container from
`ghcr.io/mbombeck/healthlog` and one PostgreSQL 16 database. The app container
is stateless; everything you care about lives in the database dataset and in
one value you must keep yourself: the encryption key.
## What the app needs
| Setting | Value |
| ------------ | ---------------------------------------------------------------------------------------- |
| Image | `ghcr.io/mbombeck/healthlog`, tag `X.Y.Z` (amd64 and arm64) |
| Port | `3000` (HTTP) |
| User | runs as uid `1001`; no extra capabilities, `no-new-privileges` is fine |
| Health check | `GET /api/health`, `200` when ready |
| Start period | at least 60 s, with more retries than the image's 3 × 30 s: migrations run at every boot |
| Database | PostgreSQL 16 (17 and later are not a drop-in), no extensions |
| Volumes | none for the app; the database gets its own dataset |
## Environment
| Variable | Required | Notes |
| ----------------------- | -------- | ------------------------------------------------------------------------------------------- |
| `DATABASE_URL` | yes | `postgresql://<user>:<password>@<host>:5432/<db>` |
| `ENCRYPTION_KEY` | yes | 64 hex characters: `openssl rand -hex 32`. Keep a copy outside the NAS (see below). |
| `API_TOKEN_HMAC_KEY` | yes | 64 hex characters, generated the same way. Changing it signs everyone out. |
| `NEXT_PUBLIC_APP_URL` | yes | the address people open, for example `http://truenas.local:30180` |
| `APP_URL` | yes | the same address |
| `SESSION_COOKIE_SECURE` | no | `false` for a LAN install served over plain `http://`; leave unset behind an HTTPS proxy |
| `HEALTHLOG_PLATFORM` | no | `truenas`: the admin's key backup step opens on the TrueNAS instructions |
| `GEOLITE2_DIR` | no | a mounted directory of GeoLite2 `.mmdb` files, so sign-in locations are resolved on the NAS |
`HEALTHLOG_PROCESS_TYPE` stays unset (`all`): one container serves the web app
and runs the background jobs.
## Plain HTTP on the LAN
Most NAS installs are reached over `http://`. Set `SESSION_COOKIE_SECURE=false`
for that. If it is left at its default, the browser drops the sign-in cookie
and the login page says so before you type a password: "This server only sets
its sign-in cookie over https://".
## Back up your encryption key
HealthLog encrypts tokens, notes, documents and in-database backups with
`ENCRYPTION_KEY`. The key is not stored in the database. If the app is deleted
and reinstalled with a new key over the old database dataset, the data is
still there but cannot be read.
1. Copy `ENCRYPTION_KEY` from the app's settings (Apps, HealthLog, Edit,
Environment) into your password manager.
2. Sign in as the admin and open Admin, Encryption. The step shows the key id
and a fingerprint, the first 12 hex characters of SHA-256 over the key.
Compare it with your copy:
```bash
echo -n "<your key>" | xxd -r -p | sha256sum | cut -c1-12
```
or paste the copy into "Check my copy" (it is compared and dropped, never
stored or logged).
3. Confirm the backup. Until you do, admins see a reminder on the dashboard.
After a key rotation the step comes back for the new key.
## When the key does not match the database
At every start HealthLog checks that its key opens the data already in the
database. If it does not, it refuses to serve instead of failing on every
encrypted value: pages show "HealthLog cannot open its data", API requests
answer `503` with `meta.errorCode` `encryption.key_mismatch`, `/api/health`
answers `503` with `reason: "encryption_key_mismatch"`, and no background jobs
run. TrueNAS shows the app as unhealthy rather than crashed, so the reason
stays visible.
Fix it one of three ways, then restart the app:
1. Put the original `ENCRYPTION_KEY` back.
2. Point `DATABASE_URL` at the database that belongs to this key.
3. Start fresh with an empty database. The old data and its backups need the
old key.
Before it records a key as the right one, the check reads the oldest
encrypted values in the database and records the key only if they open (or if
the database holds no encrypted value under that key id yet). When the data
proves neither, the app keeps serving, records nothing, writes a warning
starting with `[boot] Encryption key check inconclusive` to the log, and
checks again at the next start.
### Resetting the check
If you are certain the configured key is the one the data was written with,
and the app still refuses because the check recorded a different key earlier,
remove that record and restart. Open a shell on the database container (Apps,
HealthLog, the database container's Shell) and run, with the key id the log
names (`v1` unless you use `ENCRYPTION_KEYS`):
```bash
psql -U healthlog healthlog \
-c "DELETE FROM encryption_key_canaries WHERE key_id = 'v1';"
```
Then restart the app. It probes the stored data again and records the key
only if that data opens with it. If the key is in fact wrong, the app then
fails on every encrypted value instead of refusing clearly, so only do this
when you are sure. After a key rotation you never need this for the old key
id: the rotation script removes its record once no values remain under it.
On a first start there is no record to remove. If the check refuses there and
you are certain the key is right, add `ENCRYPTION_KEY_CHECK` = `warn` under
Apps, HealthLog, Edit, Environment as a last resort. The check still runs and
logs, `/api/health` reports `warning: "encryption_key_mismatch"` without
failing, the app serves, and no key is recorded until the check passes. This
switches off a safety check: with a wrong key every encrypted value fails and
new data is written under that key. Remove the setting once the key is
confirmed.
## Updates
Pick the new tag, take a snapshot of the database dataset first, and update.
Migrations run on start; the first start of a new install applies all of them,
which is why the start period above is generous.
+10 -1
View File
@@ -7,7 +7,8 @@ Unraid UI, but because CA templates describe a single container you install
PostgreSQL separately and wire the two together.
HealthLog stores all persistent state in PostgreSQL — the app container itself is
stateless (the offline geo-IP databases are baked into the image). A backup of
stateless (the offline geo-IP databases are either baked in at build time or
mounted read-only; replaceable either way, not state). A backup of
the database is a backup of everything.
## What you need
@@ -120,6 +121,14 @@ Set `SESSION_COOKIE_SECURE=true` (or leave it unset) only when a TLS reverse
proxy serves HealthLog over HTTPS. In that case also point `NEXT_PUBLIC_APP_URL`
and `APP_URL` at the public `https://` URL.
## Back up your encryption key
Copy `ENCRYPTION_KEY` from the template into your password manager, then
confirm it under Admin, Encryption (set `HEALTHLOG_PLATFORM=unraid` so the step
opens on the Unraid instructions). A reinstall with a new key over the old
database makes the data unreadable; HealthLog then refuses to serve and says
so. See [Getting started](getting-started.md#back-up-your-encryption-key).
## Updates
Pin a release tag (`ghcr.io/mbombeck/healthlog:vX.Y.Z`) and bump deliberately,
+2
View File
@@ -53,6 +53,8 @@
<Config Name="API_TOKEN_HMAC_KEY" Target="API_TOKEN_HMAC_KEY" Default="" Mode="" Description="HMAC key for API token hashing. Generate with: openssl rand -hex 32 (64-char hex)." Type="Variable" Display="always" Required="true" Mask="true"/>
<Config Name="SESSION_COOKIE_SECURE" Target="SESSION_COOKIE_SECURE" Default="false" Mode="" Description="Set to false for LAN / plain-HTTP installs (http://tower:3000) or login fails. Set to true only behind an HTTPS reverse proxy." Type="Variable" Display="always" Required="true" Mask="false">false</Config>
<Config Name="HEALTHLOG_PLATFORM" Target="HEALTHLOG_PLATFORM" Default="unraid" Mode="" Description="Where this server is configured. Opens the admin's encryption key backup step on the Unraid instructions." Type="Variable" Display="advanced" Required="false" Mask="false">unraid</Config>
<Config Name="ENCRYPTION_KEY_CHECK" Target="ENCRYPTION_KEY_CHECK" Default="enforce" Mode="" Description="Start-up encryption key check. enforce refuses to serve when the key does not open the stored data. warn only logs it: a last resort for a refusal you are certain is false, and it disables a safety check." Type="Variable" Display="advanced" Required="false" Mask="false">enforce</Config>
<Config Name="NEXT_PUBLIC_APP_URL" Target="NEXT_PUBLIC_APP_URL" Default="http://tower:3000" Mode="" Description="Public URL users reach HealthLog at. Use the LAN URL (e.g. http://tower:3000) or your HTTPS domain behind a reverse proxy." Type="Variable" Display="always" Required="true" Mask="false"/>
+16 -19
View File
@@ -320,24 +320,18 @@ tile itself, to avoid accidental hide.
### 3.3 Settings — `/settings/[section]`
The 1.4 release splits the legacy 3150-LOC settings monolith into one
route per top-level section:
The 1.4 release split the legacy 3150-LOC settings monolith into one
route per top-level section. The pattern holds: every section is a
route under `/settings/[section]` with its component under
`src/components/settings/`. The section list has grown far past the
original eight (account, integrations, notifications, ai, api,
advanced, about now sit alongside security, access, sources, coach,
environment, export, mcp, and more); the registry in
`src/components/settings/settings-shell.tsx` is authoritative.
Cross-section search lives in the section sidebar header.
- `/settings/account` — profile, password, passkeys, account deletion.
- `/settings/integrations` — Withings, Nightscout, Telegram, ntfy, Web Push.
- `/settings/notifications` — channel matrix + quiet hours + reminders.
- `/settings/dashboard` — tile layout editor, default ranges, threshold
overrides.
- `/settings/ai` — AI provider selection + connection + test.
- `/settings/api` — API tokens for headless ingest + Bearer issuance.
- `/settings/advanced` — exports, imports, danger zone.
- `/settings/about` — version, build, license, links to docs/changelog.
Each section's component lives at `src/components/settings/<section>.tsx`
and stays under 400 LOC. Cross-section search lives in the section
sidebar header.
The legacy `/settings` route 301-redirects to `/settings/account`.
The legacy `/settings` route is a permanent (308) redirect to
`/settings/account`.
### 3.4 Admin — `/admin/[section]`
@@ -505,8 +499,11 @@ is the point.
## 7. Internationalization
All user-facing strings come from `messages/en.json` (default) and
`messages/de.json`. Use `useTranslations()` on the client and
All user-facing strings come from `messages/en.json` (default) plus
the `de`, `es`, `fr`, `it`, and `pl` bundles beside it. Guard tests
(`i18n-call-site-coverage`, `i18n-locale-integrity`) enforce that every
`t()` key resolves in EN and propagates across all six locales. Use
`useTranslations()` on the client and
`getServerTranslator()` (`src/lib/i18n/server-translator.ts`) on the
server. Numbers, dates, currencies, and units always go through
`useFormatters()` — never hand-roll `Intl.NumberFormat(...)` with a
+1
View File
@@ -14,6 +14,7 @@ The Playwright config (`../playwright.config.ts`) builds the app (`next build`)
- **`setup/`** — `test.ts` (the suite's `test` + `expect` entry point), `global-setup.ts` (auth + DB seeding), `test-helpers.ts` (shared login + navigation helpers).
- **`utils/`** — fixtures such as `mock-dashboard-snapshot.ts`.
- **`fixtures/`** — synthetic payloads a journey uploads, built in code rather than committed as blobs so the content stays reviewable (`apple-health-export.ts`).
- **`*.spec.ts`** — one spec per flow: auth/login/redirect, dashboard, charts, the medication-wizard cadences (`medications-wizard-*`), insights generation + scroll restoration, doctor report, settings, mobile-viewport consistency, locale switch, accessibility (`a11y.spec.ts`), and the `v1427-*` regression set.
## Conventions
+265 -48
View File
@@ -3,7 +3,10 @@ import type { Locator, Page, Route } from "@playwright/test";
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
import { openMenu } from "./open-menu";
import { POPULATED_SUMMARIES } from "./utils/mock-dashboard-snapshot";
import { revealDeferredSections } from "./utils/deferred-sections";
type AxeViolation = Awaited<
ReturnType<AxeBuilder["analyze"]>
@@ -11,10 +14,36 @@ type AxeViolation = Awaited<
type Theme = "light" | "dark";
/**
* One scan target: where to go, and what has to be on screen before axe is
* allowed to look.
*
* The `painted` locator is the whole contract of this file. A scan that runs
* against a page whose content has not arrived reports violations the app does
* not have — "page must have a level-one heading" against a page that has one,
* a moment later — and that reads as a product defect until somebody re-runs
* it. Two rules keep the sentinel honest, and both were learned from a case
* that broke them:
*
* 1. It must name something the PAGE renders once its data is there, never
* something the shell or a skeleton also carries. `#main-content` is the
* app frame and exists before the route paints anything; `[role="status"]`
* is on every busy placeholder; a filter rail renders next to the loading
* silhouettes it filters. Each of those is a coin flip, not a wait.
* 2. It must not be the thing the scan asserts. Waiting for `<h1>` and then
* letting axe check that an `<h1>` exists is a check that cannot fail —
* strictly worse than the flake, because a page that really lost its
* heading would wait out the timeout under a misleading name instead of
* failing the rule. Every case here gates on content that lives in a
* different component from the heading, so dropping the heading still
* fails the scan.
*/
type RouteCase = {
name: string;
path: string;
painted: (page: Page) => Locator;
/** Runs after navigation, before the painted gate (e.g. mount deferred sections). */
prepare?: (page: Page) => Promise<void>;
};
const THEMES: readonly Theme[] = ["light", "dark"];
@@ -35,15 +64,35 @@ const A11Y_WORKOUT_ID = "a11y-workout";
const A11Y_CONVERSATION_ID = "a11y-conversation";
const A11Y_DOCUMENT_ID = "a11y-document";
// Ten daily rows ending half a day before now. The chart range tabs are
// calendar-day windows anchored on now (v1.37.29), so absolute-dated rows
// age out of the default window — the weight sub-page would render its
// empty state and the `.recharts-wrapper` painted gate would never fire.
const fixedMeasurementRows = Array.from({ length: 10 }, (_, index) => ({
id: `a11y-measurement-${index}`,
type: "WEIGHT",
value: 78.5 + (index % 3) - 1,
measuredAt: `2026-07-${String(20 - index).padStart(2, "0")}T08:00:00.000Z`,
measuredAt: new Date(
Date.now() - 12 * 3_600_000 - index * 86_400_000,
).toISOString(),
source: "MANUAL",
notes: null,
}));
// Ten daily mood scores ending yesterday, anchored for the same reason the
// measurement rows above are: the mood chart windows by calendar day and
// withholds its line below three DISTINCT days, so a fixed date left the mood
// sub-page painting its sparse placeholder. The scan's painted gate was then
// satisfied by a different chart on the page, and the mood line — the reason
// the case exists — was never waited for and might never have been scanned.
const fixedMoodEntries = Array.from({ length: 10 }, (_, index) => ({
date: new Date(Date.now() - (index + 1) * 86_400_000)
.toISOString()
.slice(0, 10),
score: 3 + (index % 3) * 0.5,
samples: 1,
}));
const workoutListEntry = {
id: A11Y_WORKOUT_ID,
sportType: "running",
@@ -158,6 +207,7 @@ const inboundDocument = {
factCount: 0,
pendingCount: 0,
conditionLinks: [],
encounterLinks: [],
servingClass: "attachment",
hasContentIndex: true,
contentIndexSource: "vision",
@@ -278,6 +328,7 @@ async function visitAndScan(
): Promise<AxeViolation[]> {
return test.step(`${theme} ${routeCase.name}`, async () => {
await page.goto(routeCase.path, { waitUntil: "domcontentloaded" });
await routeCase.prepare?.(page);
return scanPaintedState(
page,
theme,
@@ -288,6 +339,9 @@ async function visitAndScan(
}
async function installA11yMocks(page: Page) {
// Every AI surface renders from the `ai` block of `/api/auth/me`; the
// scans cover the AI states too, so every capability reads available.
await serveAiBlock(page, aiBlockAvailable());
await page.route(/\/api\/analytics(\?|$)/, (route) =>
fulfilJson(route, {
summaries: POPULATED_SUMMARIES,
@@ -298,16 +352,34 @@ async function installA11yMocks(page: Page) {
await page.route("**/api/mood/analytics", (route) =>
fulfilJson(route, {
entries: [{ date: "2026-07-20", score: 4 }],
summary: { count: 1 },
entries: fixedMoodEntries,
summary: { count: fixedMoodEntries.length },
}),
);
// Matches the current `MoodInsightsResponse` (mood-insights-shared.tsx): the
// sections short-circuit on `summary.totalEntries === 0` and then read
// `heatmap.cells`, so `totalEntries` and a populated `heatmap` are both
// required or the page throws into its error boundary. Breakdown arrays are
// present-but-empty; the correlations block carries every metric key.
await page.route("**/api/mood/insights", (route) =>
fulfilJson(route, {
summary: { count: 1 },
tagBreakdown: [],
trends: [],
summary: { totalEntries: fixedMoodEntries.length, inTargetPct: null },
heatmap: { windowDays: 30, cells: fixedMoodEntries },
distribution: [],
weekday: [],
timeOfDay: { buckets: [], reliable: false, best: null, worst: null },
stability: null,
tags: [],
structuredTags: [],
narratives: [],
correlations: {
sleep: { result: null, points: [], n: 0 },
steps: { result: null, points: [], n: 0 },
pulse: { result: null, points: [], n: 0 },
weight: { result: null, points: [], n: 0 },
bloodPressureSystolic: { result: null, points: [], n: 0 },
},
}),
);
@@ -643,6 +715,60 @@ async function installA11yMocks(page: Page) {
},
],
retentionDays: 30,
// The off-host card, with one row in each state — the scan has to reach
// the status washes, and a card that paints only its header proves
// nothing about the rows an operator actually reads.
offhost: {
configured: true,
periodHours: 24,
rows: [
{
userId: "a11y-user",
username: "a11y-backup-user",
lastAttemptAt: "2026-07-20T03:00:00.000Z",
lastSuccessAt: "2026-07-20T03:00:00.000Z",
sizeBytes: 4096,
ageHours: 3,
freshness: "fresh",
},
{
userId: "a11y-user-2",
username: "a11y-backup-user-2",
lastAttemptAt: "2026-07-14T03:00:00.000Z",
lastSuccessAt: "2026-07-14T03:00:00.000Z",
sizeBytes: 2048,
ageHours: 150,
freshness: "stale",
},
{
userId: "a11y-user-3",
username: "a11y-backup-user-3",
lastAttemptAt: "2026-07-20T03:00:00.000Z",
lastSuccessAt: null,
sizeBytes: null,
ageHours: null,
freshness: "never",
},
{
userId: "a11y-user-4",
username: "a11y-backup-user-4",
lastAttemptAt: null,
lastSuccessAt: null,
sizeBytes: null,
ageHours: null,
freshness: "unknown",
},
],
// A deletion the bucket refused, and a bucket with no expiry rule:
// both lines paint only in these states, and both are what an
// operator has to read and act on.
pendingDeletions: {
count: 2,
oldestRequestedAt: "2026-07-18T03:00:00.000Z",
lastFailure: "AccessDenied",
},
lifecycle: { state: "missing", expirationDays: null },
},
}),
);
}
@@ -651,65 +777,110 @@ const INSIGHTS_ROUTES: readonly RouteCase[] = [
{
name: "/insights overview",
path: "/insights",
// Scan the whole overview, the sections that mount near the viewport too.
prepare: revealDeferredSections,
// The vitals grid, settled. The scores strip is not a stable gate: it
// unmounts for an account with no score yet, and since v1.39 it no longer
// keeps an empty cell for a cycle ring that has no dial to draw.
painted: (page) =>
page.locator('[data-slot="wellness-scores"]').filter({
has: page.locator(
'[data-slot="wellness-scores-grid"]:not([aria-busy="true"])',
),
}),
page.locator(
'[data-slot="vitals-dashboard-grid"]:not([aria-busy="true"])',
),
},
{
// `.recharts-wrapper` is a class the charting library writes, not a
// contract this repository keeps, and it is shared by every chart on the
// page — so the gate could be satisfied by a chart other than the one the
// route exists to render, and it moves whenever the library's markup does.
// `chart-plot` is the measurement chart's own slot and the data branch is
// the only branch that renders it: an empty window paints `ChartEmptyState`
// instead and this scan still waits, which is what it is for.
name: "/insights/weight metric subpage",
path: "/insights/weight",
painted: (page) => page.locator(".recharts-wrapper").first(),
painted: (page) => page.locator('[data-slot="chart-plot"]').first(),
},
{
// Mood is event-driven, so its sub-page renders the heatmap and the mood
// line chart from `/api/mood/insights` rather than a MeasurementType series.
// The mood chart carries the same `chart-plot` slot on the same terms, so
// the scan waits for the heavy content to land here too.
name: "/insights/mood metric subpage",
path: "/insights/mood",
painted: (page) => page.locator('[data-slot="chart-plot"]').first(),
},
{
// The two states this page's OWN render produces: the list, or the
// no-workouts empty state. Never `[role="status"]`, because the busy
// skeletons carry it too (`chart-skeleton` in the streamed route shell is
// one), so that selector matched the loading tree the server sends before
// the page client has mounted anything. On a loaded runner the scan then
// landed on a document whose only heading had not rendered yet and blamed
// the app for a missing `<h1>` it does have.
name: "/insights/workouts list",
path: "/insights/workouts",
painted: (page) =>
page
.locator(
'#main-content [data-slot="workout-list"], #main-content [role="status"]',
'#main-content [data-slot="workout-list"], #main-content [data-slot="empty-state"]',
)
.first(),
},
{
name: "/insights/workouts/:id detail",
path: `/insights/workouts/${A11Y_WORKOUT_ID}`,
painted: (page) => page.locator('[data-slot="workout-detail-header"]'),
painted: (page) =>
page.locator('[data-slot="workout-detail-header"]:visible'),
},
{
// `coach-page` is the sizing wrapper around a `<Suspense fallback={null}>`,
// so it is on screen while the conversation below it is still nothing at
// all. Gate on the conversation surface itself.
name: "/coach",
path: "/coach",
painted: (page) => page.locator('[data-slot="coach-page"]').first(),
painted: (page) =>
page.locator(
'[data-slot="coach-conversation"][data-variant="page"]:visible',
),
},
];
const RECORD_ROUTES: readonly RouteCase[] = [
{
// `filter-bar` is a sibling of the loading silhouettes, not their
// successor — the rail renders above the list in every branch, so it was
// on screen while the rows were still `measurement-list-loading`
// rectangles. The rows wrapper exists only in the resolved, non-empty
// branch, and both the desktop table and the mobile card list carry it.
name: "/measurements",
path: "/measurements",
painted: (page) => page.locator('[data-slot="filter-bar"]'),
painted: (page) => page.locator('[data-slot="measurement-rows"]:visible'),
},
{
// Same shape as /measurements, and the one this was measured on: under
// an 8× CPU throttle `filter-bar` and `mood-list-loading` resolved in the
// same 40 ms poll, the rows a poll later.
name: "/mood",
path: "/mood",
painted: (page) => page.locator('[data-slot="filter-bar"]'),
painted: (page) => page.locator('[data-slot="mood-rows"]:visible'),
},
{
// Was `getByRole("heading", { level: 1 })` — the axe rule's own query
// used as its own precondition. The card carries the mocked medication's
// id; `MedicationCardSkeleton` carries no id at all.
name: "/medications",
path: "/medications",
painted: (page) => page.getByRole("heading", { level: 1 }).first(),
painted: (page) => page.locator("[data-medication-id]").first(),
},
{
name: "/labs",
path: "/labs",
painted: (page) => page.getByText("A11y LDL").first(),
painted: (page) => page.locator('[data-slot="lab-list"]:visible'),
},
{
name: "/documents compact panel",
path: "/documents?view=compact",
painted: (page) => page.getByText("A11y blood panel").first(),
painted: (page) =>
page.locator(`[data-document-id="${A11Y_DOCUMENT_ID}"]`).first(),
},
];
@@ -717,40 +888,65 @@ const ADMIN_AND_BASELINE_ROUTES: readonly RouteCase[] = [
{
name: "/admin/app-logs",
path: "/admin/app-logs",
painted: (page) => page.getByText("a11y.paint").first(),
painted: (page) => page.locator('[data-slot="app-log-rows"] tr').first(),
},
{
name: "/admin/backups",
path: "/admin/backups",
painted: (page) =>
page.getByText("a11y-backup-user", { exact: true }).filter({
visible: true,
}),
painted: (page) => page.locator('[data-slot="backup-rows"]:visible'),
},
{
// This one is why the whole file was swept. `#main-content` is the
// authenticated shell's `<main>`: it is in the first HTML on every route,
// it wraps whatever the segment happens to be streaming, and on `/` that
// is `app/loading.tsx` — a silhouette with no heading in it. The scan was
// therefore free to run against a document that legitimately had no `<h1>`
// yet and report the app as missing one. Measured under an 8× CPU
// throttle: `#main-content` at 759 ms, the tile strip at 4896 ms.
//
// The gate is the revealed chart cell rather than the tile strip because
// an unrevealed cell is `invisible` AND `aria-hidden` — the chart cards
// are simply not in the accessibility tree, so axe walks past the whole
// chart row without reading it. Gating on the strip alone left it a
// coin flip whether the row was scanned at all: locally the cells were
// still hidden at strip time and revealed six seconds later, while the
// runner that reported the heading-order break had already revealed
// them. The row is the dashboard's largest surface; the scan has to see
// it every time or not claim to have checked the page.
name: "/ dashboard",
path: "/",
painted: (page) => page.locator("#main-content"),
painted: (page) =>
page
.locator('[data-slot="dashboard-chart-cell"][data-revealed="true"]')
.first(),
},
{
// The settings heading belongs to `<SettingsShell>`, i.e. the chrome —
// waiting on it says nothing about the section body below. The
// connections panel is that body. This route has no data-gated content of
// its own: every provider card renders immediately and fills in its
// status pill later, so the panel's presence is the honest ceiling here.
name: "/settings/integrations",
path: "/settings/integrations",
painted: (page) => page.getByRole("heading", { level: 1 }).first(),
painted: (page) => page.locator('[data-slot="connections-panel"]:visible'),
},
{
// The heading comes from `<AdminShell>` and is on screen while every card
// under it is still a spinner. The audit list is the last card on the
// overview and only exists once its query has answered.
name: "/admin overview",
path: "/admin",
painted: (page) => page.getByRole("heading", { level: 1 }).first(),
painted: (page) => page.locator('[data-slot="admin-audit-rows"]:visible'),
},
{
name: "/admin/system-status",
path: "/admin/system-status",
painted: (page) => page.getByRole("heading", { level: 1 }).first(),
painted: (page) => page.locator('[data-slot="system-status-grid"]:visible'),
},
{
name: "/admin/users",
path: "/admin/users",
painted: (page) => page.getByRole("heading", { level: 1 }).first(),
painted: (page) => page.locator('[data-slot="admin-user-rows"]:visible'),
},
];
@@ -763,7 +959,11 @@ test.describe("axe-core public surfaces", () => {
page,
theme,
"/auth/login",
page.getByRole("main"),
// Not `getByRole("main")`: the public shell renders that landmark
// around whatever the segment is streaming, so it is satisfied
// before the login card itself exists. The action block is the
// page's own.
page.locator('[data-slot="login-actions"]:visible'),
);
expectNoViolations(theme, "/auth/login", blocking);
});
@@ -823,13 +1023,17 @@ test.describe("axe-core authenticated route and state matrix", () => {
await test.step(`${theme} /labs open OCR picker dialog`, async () => {
await page.goto("/labs", { waitUntil: "domcontentloaded" });
await expect(page.getByText("A11y LDL").first()).toBeVisible({
await expect(
page.locator('[data-slot="lab-list"]:visible'),
).toBeVisible({
timeout: 15_000,
});
await page
.locator('#main-content [data-slot="dropdown-menu-trigger"]')
.first()
.click();
await openMenu(
page,
page
.locator('#main-content [data-slot="dropdown-menu-trigger"]')
.first(),
);
await page.getByRole("menuitem").first().click();
const sheet = page.locator('[data-slot="responsive-sheet-content"]');
await expect(sheet.locator('input[type="file"]')).toHaveCount(1);
@@ -843,33 +1047,41 @@ test.describe("axe-core authenticated route and state matrix", () => {
);
});
await test.step(`${theme} /coach open evidence disclosure and source chips`, async () => {
await test.step(`${theme} /coach open the areas an older answer looked at`, async () => {
await page.goto(`/coach?c=${A11Y_CONVERSATION_ID}`, {
waitUntil: "domcontentloaded",
});
const evidence = page.locator('[data-slot="coach-evidence"]').first();
await expect(evidence).toBeVisible({ timeout: 15_000 });
await evidence.locator("summary").click();
await expect(evidence).toHaveAttribute("open", "");
const steps = page.locator('[data-slot="coach-turn-steps"]').first();
await expect(steps).toBeVisible({ timeout: 15_000 });
const toggle = steps.locator('[data-slot="coach-turn-steps-toggle"]');
await toggle.click();
await expect(toggle).toHaveAttribute("aria-expanded", "true");
await expect(
evidence.locator('[data-slot="coach-source-chips"]'),
steps.locator('[data-slot="coach-turn-areas"]'),
).toBeVisible();
blocking.push(
...(await scanPaintedState(
page,
theme,
"/coach open evidence disclosure and source chips",
evidence,
"/coach open the areas an older answer looked at",
steps,
)),
);
});
await test.step(`${theme} /medications open representative wizard dialog`, async () => {
await page.goto("/medications", { waitUntil: "domcontentloaded" });
await page
.locator('#main-content [data-slot="dropdown-menu-trigger"]')
.first()
.click();
// axe scans the whole document, dialog and page behind it alike, so
// the list has to have arrived before the dialog opens on top of it.
await expect(page.locator("[data-medication-id]").first()).toBeVisible({
timeout: 15_000,
});
await openMenu(
page,
page
.locator('#main-content [data-slot="dropdown-menu-trigger"]')
.first(),
);
await page.getByRole("menuitem").last().click();
const dialog = page.locator('[data-slot="medication-wizard-dialog"]');
blocking.push(
@@ -886,6 +1098,11 @@ test.describe("axe-core authenticated route and state matrix", () => {
await page.goto(`/documents?view=compact&doc=${A11Y_DOCUMENT_ID}`, {
waitUntil: "domcontentloaded",
});
// Same reason as the medication dialog: the vault behind the sheet is
// in the scan, so it has to be past `documents-loading` first.
await expect(
page.locator(`[data-document-id="${A11Y_DOCUMENT_ID}"]`).first(),
).toBeVisible({ timeout: 15_000 });
const sheet = page.locator('[data-slot="responsive-sheet-content"]');
await expect(sheet).toBeVisible({ timeout: 15_000 });
await sheet.getByRole("button", { name: /summari/i }).click();
+533
View File
@@ -0,0 +1,533 @@
/**
* Account sharing, end to end: invite → accept → switch → banner → revoke.
*
* Two browser contexts, two real accounts, one real database. The owner
* invites, the delegate accepts and opens the record, and the owner takes it
* back — each step through the shipped UI rather than through the API, because
* the half of this feature that can go wrong is the half a person touches.
*
* ## The stale-paint check
*
* The assertion this spec exists for is a NEGATIVE one, and it is deliberately
* not "the new record's data arrives". A check that waits for the new data
* proves nothing about what was on screen while it was arriving, and the
* failure being guarded against is exactly that in-between frame: a dashboard
* hydrated from the previous record's IndexedDB snapshot, painted under a
* banner naming somebody else.
*
* So an init script installs a MutationObserver before any page script runs,
* on every navigation including the full reload the switch performs, and it
* latches the moment the delegate's own marker weight appears in the document.
* The spec then reads the latch. Nothing about it is sampled or timed.
*
* The observer's positive control runs first: with the same script installed,
* the delegate's own measurements page must trip the latch. Without that, "the
* marker never appeared" and "the observer never worked" are the same sentence.
*
* ### How much this assertion can be made to fail, measured rather than assumed
*
* Three controls stand behind it, and they were removed one at a time and
* together against a real build to see which of them this spec can actually
* detect. The honest answer is: none of them individually, and that is worth
* writing down rather than leaving as an implication.
*
* - Delete the switch-time cache wipe, the persister's restore guard and the
* record-scoped query hash — all three at once — and this spec stays
* GREEN. The reason is a rule that predates this feature: the restore
* refuses to clobber a query the live cache already holds, and the
* dashboard's own query is created during render, before any effect runs.
* So the IndexedDB snapshot never reaches the screen on this route at all.
* - Delete the full reload and the spec goes RED, but on the banner line
* rather than the marker line: without a reload the account payload never
* re-resolves and the banner never paints, so the run stops before the
* latch is read.
*
* What that means, plainly: this spec is a regression net over the whole
* journey, not a proof of any single control. The controls are proven where
* they can be broken and observed — `query-persister-shared-record.test.ts`
* for the two disk guards, `record-scope.test.ts` for the cache dimension —
* and each of those was verified red before being kept.
*
* ## What this spec cannot cover, stated rather than implied
*
* - **The service worker.** The Playwright context runs with
* `serviceWorkers: "block"` (see `playwright.config.ts`), so the worker's
* `healthlog-data-*` cache — the other layer that survives a reload — is not
* exercised here at all. The switch wipes it through the same helper the
* IndexedDB snapshot goes through, and that helper is covered in
* `src/lib/pwa/__tests__/query-persister-shared-record.test.ts`.
* - **The owner's data appearing.** No route declares the delegable mode yet,
* so every read inside a shared record is refused by design. That is the
* current, correct state of the tree; the pages a delegate can open show
* their refusal state and, crucially, still show nothing of the delegate's
* own. The positive half of that assertion belongs with the route migration.
*/
import type { BrowserContext, Page } from "@playwright/test";
import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
import { actWithReproof, useStaleSession } from "./setup/recent-proof";
import { expect, test } from "./setup/test";
import {
DELEGATE_STORAGE_STATE_PATH,
E2E_DELEGATE_MARKER_KG,
E2E_OWNER,
E2E_OWNER_FULL_NAME,
E2E_USER,
OWNER_STORAGE_STATE_PATH,
} from "./setup/test-helpers";
const DELEGATE_MARKER = String(E2E_DELEGATE_MARKER_KG);
/**
* Latch the first appearance of a string anywhere in the document, from before
* the first script of every page load.
*
* A MutationObserver rather than a poll: a poll samples, and the frame this is
* looking for can be one paint long. `characterData` is on because a hydration
* pass can fill an existing text node in place rather than inserting one.
*/
async function watchForText(page: Page, needle: string): Promise<void> {
await page.addInitScript((text: string) => {
const w = window as unknown as { __sawText?: boolean };
w.__sawText = false;
const seen = () => document.body?.innerText?.includes(text) ?? false;
const check = () => {
if (seen()) w.__sawText = true;
};
const start = () => {
check();
new MutationObserver(check).observe(document.documentElement, {
childList: true,
subtree: true,
characterData: true,
});
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", start);
} else {
start();
}
}, needle);
}
async function sawText(page: Page): Promise<boolean> {
return page.evaluate(
() => (window as unknown as { __sawText?: boolean }).__sawText === true,
);
}
/** Open the user menu and the switcher inside it. */
async function openSwitcher(page: Page): Promise<void> {
await page.getByRole("button", { name: "User menu" }).first().click();
await page.locator('[data-slot="account-switcher-trigger"]').click();
await expect(
page.locator('[data-slot="account-switcher-menu"]'),
).toBeVisible();
}
test.describe("account sharing", () => {
// One journey, in order: each step is the precondition of the next, so
// splitting them into independent tests would mean re-running the invitation
// three times against a rate-limited endpoint.
test.describe.configure({ mode: "serial" });
// The `page` fixture throughout is the DELEGATE. The owner gets an explicit
// context below, because a grant needs two signed-in sides at once and the
// login endpoint is IP-rate-limited.
//
// The delegate's jar is this journey's OWN, not the shared one every other
// authenticated spec reads, and that is load-bearing rather than tidy. The
// switch is stamped on the session row (see "the nav offers only what
// sharing covers" below, which relies on exactly that), so switching the
// shared jar would switch it for every spec holding the same cookie — and
// the suite runs fully parallel. The damage lands somewhere else entirely:
// a settings surface painting "Not part of shared access", an axe scan
// reading a banner its spec never asked for. Same account, different
// session, no reach outside this file.
test.use({ storageState: DELEGATE_STORAGE_STATE_PATH });
// Desktop only, and for a reason that is about the fixture rather than the
// layout: this journey mutates shared rows — one grant between two seeded
// accounts — so two projects running it at once race each other, and the
// second one's invitation is refused as a duplicate of the first's. Running
// it once keeps every step's precondition true. The mobile bar reads the
// same destination model as the sidebar, and that agreement is a unit
// contract (`nav-model-shared-record.test.ts`) rather than something two
// browser runs of the same script would establish.
test.beforeEach(({}, testInfo) => {
test.skip(
testInfo.project.name !== "chromium-desktop",
"shared-fixture journey — runs once",
);
});
let ownerContext: BrowserContext;
let ownerPage: Page;
let endOwnerSession: (() => Promise<void>) | null = null;
test.beforeAll(async ({ browser }) => {
ownerContext = await browser.newContext({
storageState: OWNER_STORAGE_STATE_PATH,
});
ownerPage = await ownerContext.newPage();
// An invitation asks for a recent proof. The owner acts from a session of
// this journey's own, made stale before the press, so the re-proof dialog
// is met on every run rather than only once the run is five minutes old.
endOwnerSession = await useStaleSession(ownerPage, E2E_OWNER.username);
});
test.afterAll(async () => {
await endOwnerSession?.();
await ownerContext.close();
});
/** A `YYYY-MM-DD` day the date input accepts, N days from now. */
function isoDayFromNow(days: number): string {
const d = new Date();
d.setDate(d.getDate() + days);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}
test("the owner invites, and the invitation confers nothing yet", async () => {
await ownerPage.goto("/settings/access");
// The submit button is disabled until the controlled input holds a value,
// so a `fill()` that lands before React has attached its listeners leaves
// the form looking filled and behaving empty. Retry the pair until the
// button agrees, rather than waiting a fixed time and hoping.
const identifier = ownerPage.locator(
'[data-slot="grant-invite-identifier"]',
);
const submit = ownerPage.locator('[data-slot="grant-invite-submit"]');
// Nothing under the scope question is preselected now, so the form blocks
// until the owner picks one. This invitation is unscoped, so choose the
// whole record before asserting the button can enable.
const wholeRecord = ownerPage.locator(
'[data-slot="grant-invite-scope-option"][data-scope="all"]',
);
await wholeRecord.click();
await expect(wholeRecord).toHaveAttribute("data-selected", "true");
await expect(async () => {
await identifier.fill(E2E_USER.username);
await expect(submit).toBeEnabled({ timeout: 1000 });
}).toPass({ timeout: 15_000 });
// The lapse date, through the real form and onto the real wire.
//
// `expiresAt` was accepted, stored and annotated on by the route from the
// day the grant model shipped, while the card sent a hardcoded `null`. The
// component test cannot see that: it renders the control and checks the
// date mapping, and BOTH still pass with the card wired back to `null`.
// Only reading the posted body proves the value a person typed is the
// value the server receives, which is the half that was missing.
// The VISIBLE overlay, not the hidden ISO mirror: `data-slot` rides
// `{...rest}` onto `DateField`'s hidden input, so the old selector resolved
// to an element that can never be visible and typed into nothing.
const lapse = ownerPage.getByTestId("grant-invite-expires-input");
await expect(lapse).toBeVisible();
const chosenDay = isoDayFromNow(30);
await lapse.fill(chosenDay);
// The overlay commits on blur; without it the ISO text sits in local state
// and the hidden mirror still holds the old value when the form submits.
await lapse.blur();
await expect(
ownerPage.locator('input[data-slot="grant-invite-expires"]'),
).toHaveValue(chosenDay);
// The level, through the real control and onto the real wire.
//
// Same class of gap as the lapse date above, and the reason it is checked
// here rather than in a component test is worth stating: the project's
// component convention is SSR-only, so no test under `src/` can run this
// form's submit path at all. Wire the radio back to a constant and every
// one of those stays green. Only the posted body can tell the level a
// person picked from the level the card sends.
const writeOption = ownerPage.locator(
'[data-slot="grant-invite-access-option"][data-access="WRITE"]',
);
await expect(writeOption).toBeVisible();
await writeOption.click();
await expect(writeOption).toHaveAttribute("data-selected", "true");
const invitePost = ownerPage.waitForRequest(
(req) =>
req.method() === "POST" && req.url().endsWith("/api/account/grants"),
);
await actWithReproof(ownerPage, E2E_OWNER.password, () => submit.click());
const posted = JSON.parse((await invitePost).postData() ?? "{}") as {
expiresAt?: string | null;
access?: string;
};
expect(
posted.expiresAt,
"the invitation must carry the day the owner chose",
).toBeTruthy();
// End of the chosen day, not the midnight that starts it.
expect(posted.expiresAt).toContain(chosenDay.slice(0, 8));
expect(
posted.access,
"the invitation must carry the level the owner chose",
).toBe("WRITE");
const row = ownerPage
.locator('[data-slot="grants-given-list"] [data-slot="grant-row"]')
.first();
await expect(row).toBeVisible();
// Pending, not active. The state is the server's answer, rendered.
await expect(row).toHaveAttribute("data-grant-state", "PENDING");
// And the level came back from the database on the list read, which is the
// far end of the same wire: form → POST → row → GET → attribute.
await expect(row).toHaveAttribute("data-grant-access", "WRITE");
});
test("the delegate is offered nothing until they accept", async ({
page,
}) => {
await page.goto("/settings/access");
const row = page
.locator('[data-slot="grants-received-list"] [data-slot="grant-row"]')
.first();
await expect(row).toBeVisible();
await expect(row).toHaveAttribute("data-grant-state", "PENDING");
// The delegate's half of the consent: what they are being offered, and
// what accepting it will mean, on the screen where they accept it.
await expect(row).toHaveAttribute("data-grant-access", "WRITE");
await expect(
row.locator('[data-slot="grant-write-consent"]'),
).toBeVisible();
// No switcher yet: `accountAccess.canSwitch` is false while the only
// grant is pending, and the menu binds that boolean.
await page.getByRole("button", { name: "User menu" }).first().click();
await expect(
page.locator('[data-slot="account-switcher-trigger"]'),
).toHaveCount(0);
await page.keyboard.press("Escape");
// The positive control for the shell-door assertion further down: the
// delegate, in their OWN record, is offered the Coach launcher like anyone
// else. Without this line the later "it is gone" check would also pass on
// a build where the launcher had stopped rendering for everybody.
// The launcher follows the `coach` capability, which needs a provider the
// suite cannot reach, so the capability reads available for this one
// look; the shared-record check below reads the real payload again.
await serveAiBlock(page, aiBlockAvailable());
await page.goto("/");
await expect(page.locator('[data-slot="coach-fab"]')).toBeVisible({
timeout: 10_000,
});
await page.unroute("**/api/auth/me");
// Back to where the rest of this journey happens. The check above leaves
// the browser on the dashboard, and Accept lives on the access page.
await page.goto("/settings/access");
await expect(row).toBeVisible();
await page.locator('[data-slot="grant-accept"]').click();
await expect(row).toHaveAttribute("data-grant-state", "ACTIVE");
});
test("the switcher appears once the grant is live", async ({ page }) => {
await page.goto("/settings/access");
await openSwitcher(page);
const entry = page.locator('[data-slot="account-switcher-entry"]');
await expect(entry).toHaveCount(1);
// v1.37.2 — the owner set a full name, so a delegate sees them by it
// rather than by the greeting name or the login handle. This is the
// record-owner's full name crossing to a read-only delegate, which is the
// deliberate disclosure the maintainer decided on. The username stays on
// the row as an attribute, which is the positive control for the label
// assertion — without it, a renamed slot would make this read green.
await expect(entry).toContainText(E2E_OWNER_FULL_NAME);
await expect(entry).toHaveAttribute(
"data-account-username",
E2E_OWNER.username,
);
// Two lines: the name and the kind of record. The access level used to
// take a third and was truncated more often than it was read; it is what
// the banner says once you are inside. The row still CARRIES the level as
// an attribute, which is the positive control for the absence below —
// without it, a renamed slot would make this read green.
await expect(entry).toHaveAttribute("data-access-level", /.+/);
await expect(entry).not.toContainText("Read only");
await expect(entry).not.toContainText("Can add entries");
await expect(entry).not.toContainText("change or remove what is in it");
// The way home is in the same menu as the way in.
await expect(
page.locator('[data-slot="account-switcher-own"]'),
).toBeVisible();
});
test("switching shows the banner and never the delegate's own data", async ({
page,
}) => {
await watchForText(page, DELEGATE_MARKER);
// Positive control. If the observer cannot see the marker on the page
// that definitely shows it, its silence later means nothing.
await page.goto("/measurements");
await expect(page.getByText(DELEGATE_MARKER).first()).toBeVisible();
expect(await sawText(page)).toBe(true);
// Let the offline persister flush the delegate's own dashboard to
// IndexedDB (1 s debounce). That snapshot is the stale-paint source this
// whole assertion is aimed at — without it the check would pass against a
// disk that was empty anyway. Poll the persister's own store for the
// written snapshot instead of sleeping past the debounce (C3): the
// condition IS the flush, so a slow CI box waits exactly as long as it
// needs to and a fast one moves on immediately.
await page.goto("/");
// Gate on rendered content first (the dashboard must actually mount and
// populate the query cache before there is anything to persist). The
// tile strip, not the Coach launcher: the launcher follows the `coach`
// capability, which needs a provider this suite does not have.
await expect(
page.locator('[data-slot="dashboard-tile-strip"]'),
).toBeVisible({
timeout: 10_000,
});
await expect
.poll(
() =>
page.evaluate(
() =>
new Promise<boolean>((resolve) => {
const req = indexedDB.open("healthlog-query-cache", 1);
req.onerror = () => resolve(false);
req.onsuccess = () => {
const db = req.result;
try {
const get = db
.transaction("kv", "readonly")
.objectStore("kv")
.get("react-query");
get.onsuccess = () => {
db.close();
resolve(get.result !== undefined);
};
get.onerror = () => {
db.close();
resolve(false);
};
} catch {
db.close();
resolve(false);
}
};
}),
),
{ timeout: 10_000 },
)
.toBe(true);
await openSwitcher(page);
await page.locator('[data-slot="account-switcher-entry"]').click();
// Wait for CONTENT, and for content the assertion is not about: the
// banner naming the owner. A skeleton does not satisfy it, and it says
// nothing about the marker either way. The owner set a full name, so the
// banner names them by it (v1.37.2) — the same label the switcher used.
const banner = page.locator('[data-slot="shared-record-banner"]');
await expect(banner).toBeVisible();
await expect(banner).toContainText(E2E_OWNER_FULL_NAME);
// The document showing the banner has never shown the delegate's own
// number. The latch was armed by that document's own init script, so this
// covers its whole life rather than the instant it is read. See the
// header for what this line can and cannot be made to fail on.
expect(await sawText(page)).toBe(false);
// And it stays false across a navigation inside the record.
await page.goto("/measurements");
await expect(
page.locator('[data-slot="shared-record-banner"]'),
).toBeVisible();
expect(await sawText(page)).toBe(false);
});
test("the nav offers only what sharing covers", async ({ page }) => {
// A fresh page fixture, and still inside the record: the switch lives on
// the session row rather than in the tab, so every tab of that browser is
// switched at once. That is the property this navigation quietly proves.
await page.goto("/");
await expect(
page.locator('[data-slot="shared-record-banner"]'),
).toBeVisible();
// The record itself is still there…
await expect(page.locator('a[href="/measurements"]').first()).toBeVisible();
// …and everything that configures the account around it is not.
await expect(page.locator('a[href="/settings/account"]')).toHaveCount(0);
await expect(page.locator('a[href="/coach"]')).toHaveCount(0);
await expect(page.locator('a[href="/insights"]')).toHaveCount(0);
// And neither is the door that stood beside the removed entries. The Coach
// launcher hangs off the shell rather than off a route, so dropping the
// nav entry left it floating over every page in the record — one tap from
// a drawer whose every action resolves `requireAuth()` and refuses.
await expect(page.locator('[data-slot="coach-fab"]')).toHaveCount(0);
});
test("a surface sharing does not cover says so", async ({ page }) => {
// Reached by bookmark: the nav entry is gone, the URL still resolves.
await page.goto("/settings/account");
await expect(
page.locator('[data-slot="shared-record-unavailable"]'),
).toBeVisible();
await expect(
page.locator('[data-slot="shared-record-unavailable-leave"]'),
).toBeVisible();
});
test("revoking from the owner's browser drops the delegate out", async ({
page,
}) => {
await page.goto("/");
await expect(
page.locator('[data-slot="shared-record-banner"]'),
).toBeVisible();
// The owner ends it from their own session, in their own context.
await ownerPage.goto("/settings/access");
await ownerPage.locator('[data-slot="grant-revoke"]').first().click();
await ownerPage
.getByRole("button", { name: "End access", exact: true })
.last()
.click();
await expect(
ownerPage
.locator('[data-slot="grants-given-list"] [data-slot="grant-row"]')
.first(),
).toHaveAttribute("data-grant-state", "REVOKED");
// The delegate's next navigation lands back in their own account rather
// than on a wall of refusals: the revoke cleared their acting session in
// the same transaction that stamped the row.
await page.goto("/measurements");
// Their own record, back. This goes first: the protected shell holds
// every child — nav, banner, page body — behind its hydration gate until
// `/api/auth/me` resolves, so "no banner" straight after a navigation is
// satisfied by the page still loading and would stay green if the revoke
// had left the acting session standing. The delegate's own marker only
// exists once the record really resolved to theirs.
await expect(page.getByText(DELEGATE_MARKER).first()).toBeVisible();
await expect(
page.locator('[data-slot="shared-record-banner"]'),
).toHaveCount(0);
});
test("the ended grant stays on the record as history", async () => {
await ownerPage.goto("/settings/access");
const row = ownerPage
.locator('[data-slot="grants-given-list"] [data-slot="grant-row"]')
.first();
// Revocation never deletes. "Who had access, from when to when, and who
// ended it" is the question the panel exists to answer.
await expect(row).toHaveAttribute("data-grant-state", "REVOKED");
await expect(row).toContainText("You ended it");
});
});
+126
View File
@@ -0,0 +1,126 @@
/**
* What happens to stored AI text and stored Coach rows, against the real
* server, on an account of its own (`E2E_AI_OPTIONAL`).
*
* J5 — consent withdrawn. The account has a local model (an address nothing
* listens on: presence is all the capability reads, nothing here calls
* it), a daily briefing a model wrote earlier, and an AI consent. The
* briefing is on the overview; the consent is withdrawn in Settings, AI
* through the real control; the briefing is gone, because the server
* deleted the notes written under that consent.
* J4 — Coach hidden. With Hide Coach on, Settings, Coach is out of reach, so
* Settings, AI lists what the Coach stored; one stored conversation is
* deleted from there and is gone from the database.
*
* Both journeys move the same account's state, so they run serially, in one
* project (see `playwright.config.ts`).
*/
import type { Page } from "@playwright/test";
import { AI_OPTIONAL_STORAGE_STATE_PATH } from "./setup/global-setup";
import {
coachConversationCount,
resetAiOptionalAccount,
seedHiddenCoachWithConversation,
seedStoredBriefing,
} from "./setup/ai-optional-fixture";
import { expect, test } from "./setup/test";
import { revealDeferredSectionsSettled } from "./utils/deferred-sections";
test.use({ storageState: AI_OPTIONAL_STORAGE_STATE_PATH });
test.describe.configure({ mode: "serial" });
test.beforeEach(async () => {
await resetAiOptionalAccount();
});
test.afterAll(async () => {
await resetAiOptionalAccount();
});
/**
* The overview with every section mounted. Sections past the first three
* render as an empty sentinel until they near the viewport, so a count of
* zero taken before they mount would pass whatever they paint.
*/
async function openOverview(page: Page): Promise<void> {
await page.goto("/insights");
await expect(page.locator('[data-slot="insights-hero-strip"]')).toBeVisible({
timeout: 20_000,
});
await page.waitForLoadState("networkidle");
await revealDeferredSectionsSettled(page);
}
test("J5: withdrawing AI consent deletes the notes written under it", async ({
page,
}) => {
test.setTimeout(90_000);
const marker = `Stored briefing ${Date.now()}`;
await seedStoredBriefing(marker);
// Positive control: the stored briefing is what the overview shows.
await openOverview(page);
await expect(page.locator('[data-slot="daily-briefing"]')).toHaveCount(1);
await expect(page.getByText(marker).first()).toBeVisible();
// Withdraw through the real control. The confirm names what goes and what
// stays before anything happens.
await page.goto("/settings/ai");
await page.locator('[data-slot="ai-consent-withdraw"]').click();
const withdrawn = page.waitForResponse(
(res) =>
res.url().includes("/api/consent/ai/latest") &&
res.request().method() === "DELETE",
);
await page.locator('[data-slot="ai-consent-withdraw-confirm"]').click();
expect((await withdrawn).status()).toBe(200);
await expect(page.locator('[data-slot="ai-consent-grant"]')).toBeVisible();
await openOverview(page);
await expect(page.getByText(marker)).toHaveCount(0);
});
test("J4: the Coach memory stays readable and deletable with the Coach hidden", async ({
page,
}) => {
test.setTimeout(90_000);
const title = `Stored conversation ${Date.now()}`;
await seedHiddenCoachWithConversation(title);
// Hide Coach takes the Coach page, its launcher and every per-card
// hand-off away...
await openOverview(page);
await expect(page.locator('[data-slot="coach-fab"]')).toHaveCount(0);
await expect(page.locator('[data-slot="ask-coach-action"]')).toHaveCount(0);
await expect(page.locator('[data-slot="ask-coach-icon"]')).toHaveCount(0);
// ...and Settings, AI lists what the Coach stored.
await page.goto("/settings/ai");
const card = page.locator(
'[data-testid="settings-coach-conversations-card"]',
);
await expect(card).toBeVisible({ timeout: 20_000 });
const row = card
.locator('[data-testid="settings-coach-conversation"]')
.filter({ hasText: title });
await expect(row).toHaveCount(1);
// Readable: the row opens its transcript in place.
await row.locator('[data-slot="settings-coach-conversation-open"]').click();
await expect(
row.locator('[data-slot="settings-coach-conversation-open"]'),
).toHaveAttribute("aria-expanded", "true");
// Deletable: the row goes at once, and the delete reaches the server once
// the undo window closes.
const deleted = page.waitForResponse(
(res) =>
/\/api\/insights\/chat\/[^/]+$/.test(new URL(res.url()).pathname) &&
res.request().method() === "DELETE",
{ timeout: 30_000 },
);
await row.locator('[data-slot="settings-coach-conversation-delete"]').click();
await expect(row).toHaveCount(0);
expect((await deleted).ok()).toBe(true);
expect(await coachConversationCount()).toBe(0);
});
+183
View File
@@ -0,0 +1,183 @@
/**
* Insights without AI (#975): switched off by the operator, or never set up.
*
* J1 — every AI capability `operator_disabled`, nothing configurable here.
* The overview renders its data sections; nothing AI-shaped paints, not
* even a hint; not one request goes to a route that calls a model or
* serves model text, and no request is answered 403.
* J3 — no provider, one could be set up here. Exactly one calm setup hint on
* the overview, no Coach launcher or per-card Coach hand-off, and
* `/coach` goes back to the overview. Dismissing the hint in Settings →
* AI keeps it gone on the overview.
*
* Both states are served through the `ai` block of `/api/auth/me`
* (`serveAiBlock`, which says why): the operator's switches are instance-wide
* and a parallel spec would lose its AI under a real flip.
*
* Every assertion is addressed to a stable `data-*` attribute, never copy.
*/
import type { Page, Request, Response } from "@playwright/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { aiBlockUnavailable, serveAiBlock } from "./setup/ai-capabilities";
import { expect, test } from "./setup/test";
import { revealDeferredSectionsSettled } from "./utils/deferred-sections";
test.use({ storageState: STORAGE_STATE_PATH });
/**
* Mount every overview section, then let their reads land. Sections past the
* first three render as an empty sentinel until they near the viewport, so a
* count of zero taken before this would pass whatever those sections paint.
*/
async function mountWholeOverview(page: Page): Promise<void> {
await revealDeferredSectionsSettled(page);
}
/** Routes that call a model or serve model-written text. */
const AI_ROUTE = new RegExp(
[
"/api/insights/generate",
"/api/insights/(weight|bmi|pulse|blood-pressure|mood|medication-compliance)-status",
"/api/insights/metric-status",
"/api/insights/biomarker-assessment",
"/api/insights/chat",
"/api/insights/coach/nudge-status",
"/api/medications/extract",
"/api/labs/ocr/",
"/api/feature-flags",
].join("|"),
);
function watchNetwork(page: Page): {
aiRequests: string[];
refused: string[];
} {
const aiRequests: string[] = [];
const refused: string[] = [];
page.on("request", (request: Request) => {
const url = new URL(request.url());
if (AI_ROUTE.test(url.pathname)) aiRequests.push(url.pathname);
});
page.on("response", (response: Response) => {
const url = new URL(response.url());
if (url.pathname.startsWith("/api/") && response.status() === 403) {
refused.push(url.pathname);
}
});
return { aiRequests, refused };
}
async function clearHintDismissal(page: Page): Promise<void> {
await page.evaluate(() => {
for (const key of Object.keys(window.localStorage)) {
if (key.startsWith("healthlog.ai-setup-hint.")) {
window.localStorage.removeItem(key);
}
}
});
}
test.describe("J1: AI switched off by the operator", () => {
test("the overview shows data, no AI, no AI requests and no refusals", async ({
page,
}) => {
test.setTimeout(60_000);
await serveAiBlock(
page,
aiBlockUnavailable("operator_disabled", {
configured: false,
managedBy: null,
canConfigure: false,
}),
);
const network = watchNetwork(page);
await page.goto("/insights");
await expect(page.locator('[data-slot="insights-hero-strip"]')).toBeVisible(
{ timeout: 20_000 },
);
// Let every section's reads land before judging what painted.
await page.waitForLoadState("networkidle");
await mountWholeOverview(page);
// A read refused for want of AI paints one of these on the overview:
// the section boundary, the error card, or the dense error row.
await expect(
page.locator('[data-slot="insights-overview-section-error"]'),
).toHaveCount(0);
await expect(page.locator('[data-slot="query-error-card"]')).toHaveCount(0);
await expect(page.locator('[data-slot="query-error-row"]')).toHaveCount(0);
await expect(page.locator('[data-slot="chart-error-state"]')).toHaveCount(
0,
);
await expect(page.locator('[data-slot="daily-briefing"]')).toHaveCount(0);
await expect(page.locator('[data-slot="ai-setup-hint"]')).toHaveCount(0);
await expect(page.locator('[data-slot="coach-fab"]')).toHaveCount(0);
// The ECG page is data and never waits on AI.
await page.goto("/insights/ecg");
await page.waitForLoadState("networkidle");
await expect(page.locator('[data-slot="query-error-card"]')).toHaveCount(0);
expect(network.aiRequests).toEqual([]);
expect(network.refused).toEqual([]);
});
});
test.describe("J3: no AI provider", () => {
test("one calm setup hint, no Coach, no per-card provider state", async ({
page,
}) => {
test.setTimeout(60_000);
await serveAiBlock(
page,
aiBlockUnavailable("no_provider", {
configured: false,
managedBy: null,
canConfigure: true,
}),
);
const network = watchNetwork(page);
await page.goto("/insights");
await clearHintDismissal(page);
await page.reload();
await expect(page.locator('[data-slot="ai-setup-hint"]')).toHaveCount(1, {
timeout: 20_000,
});
await page.waitForLoadState("networkidle");
await mountWholeOverview(page);
await expect(page.locator('[data-slot="coach-fab"]')).toHaveCount(0);
await expect(page.locator('[data-slot="daily-briefing"]')).toHaveCount(0);
// The per-card Coach hand-offs paint only while the Coach is available.
await expect(page.locator('[data-slot="ask-coach-action"]')).toHaveCount(0);
await expect(page.locator('[data-slot="ask-coach-icon"]')).toHaveCount(0);
await expect(page.locator('[data-slot="coach-launch-inline"]')).toHaveCount(
0,
);
// The Coach page itself answers an unavailable Coach by going back to
// the overview, rather than painting a composer that would be refused.
await page.goto("/coach");
await expect(page).toHaveURL(/\/insights$/, { timeout: 20_000 });
// Settings → AI carries the same hint; dismissing it there is remembered.
await page.goto("/settings/ai");
const hint = page.locator('[data-slot="ai-setup-hint"]');
await expect(hint).toHaveCount(1, { timeout: 20_000 });
await page.locator('[data-slot="ai-setup-hint-dismiss"]').click();
await expect(hint).toHaveCount(0);
await page.goto("/insights");
await expect(page.locator('[data-slot="insights-hero-strip"]')).toBeVisible(
{ timeout: 20_000 },
);
await page.waitForLoadState("networkidle");
await mountWholeOverview(page);
await expect(page.locator('[data-slot="ai-setup-hint"]')).toHaveCount(0);
expect(network.aiRequests).toEqual([]);
});
});
+112
View File
@@ -339,4 +339,116 @@ test.describe("Settings → AI provider dropdown UX (B2)", () => {
.locator('button[type="submit"]'),
).toBeEnabled();
});
// #1126 — the Reasoning select on the Local and OpenAI-compatible forms
// saves with the form, and at phone width it sits in the same column as
// the model field without pushing the page sideways.
test("reasoning setting saves from the Local and gateway forms at 390 px", async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 844 });
const patchBodies: Array<Record<string, unknown>> = [];
let providerState: Record<string, unknown> = {
provider: "LOCAL",
model: null,
baseUrl: "http://localhost:11434/v1",
responseTimeoutSeconds: null,
hasAnthropicKey: false,
anthropicKeyPreview: null,
hasLocalKey: false,
hasOpenaiKey: false,
openaiKeyPreview: null,
compatBaseUrl: "https://gateway.example.org/v1",
compatModel: "qwen3",
hasCompatKey: false,
localReasoningEffort: null,
compatReasoningEffort: null,
};
await page.route("**/api/insights/settings", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
data: {
codexStatus: "disconnected",
codexConnectedAt: null,
hasAdminKey: false,
codexOauthConfigured: true,
privacyMode: "aggregated",
lastInsightAt: null,
},
error: null,
}),
}),
);
await page.route("**/api/user/ai-provider", async (route) => {
if (route.request().method() === "PATCH") {
const body = route.request().postDataJSON() as Record<string, unknown>;
patchBodies.push(body);
providerState = { ...providerState, ...body };
}
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ data: providerState, error: null }),
});
});
await page.route("**/api/insights/provider-chain", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
data: {
activeProvider: "local",
cachedActiveProvider: null,
configuredChain: [
{ providerType: "local", enabled: true, available: true },
],
},
error: null,
}),
}),
);
const providerHydrated = page.waitForResponse("**/api/user/ai-provider");
await page.goto("/settings/ai?provider=local", {
waitUntil: "domcontentloaded",
});
await providerHydrated;
const localForm = page.getByTestId("ai-provider-config-local");
const localReasoning = page.locator("#ai-local-reasoning");
await expect(localReasoning).toHaveValue("");
// Same column, same width as the model select above it.
const [modelBox, reasoningBox] = await Promise.all([
page.locator("#ai-local-model").boundingBox(),
localReasoning.boundingBox(),
]);
expect(reasoningBox?.x).toBe(modelBox?.x);
expect(reasoningBox?.width).toBe(modelBox?.width);
expect(
await page.evaluate(
() =>
document.documentElement.scrollWidth <=
document.documentElement.clientWidth,
),
).toBe(true);
await localReasoning.selectOption("none");
await localForm.locator('button[type="submit"]').click();
await expect.poll(() => patchBodies.length).toBe(1);
expect(patchBodies[0].localReasoningEffort).toBe("none");
await page
.getByTestId("ai-active-provider-select")
.selectOption("openai-compatible");
const compatForm = page.getByTestId("ai-provider-config-openai-compatible");
const compatReasoning = page.locator("#ai-compat-reasoning");
await expect(compatReasoning).toHaveValue("");
await compatReasoning.selectOption("high");
await compatForm.locator('button[type="submit"]').click();
await expect.poll(() => patchBodies.length).toBe(2);
expect(patchBodies[1].compatReasoningEffort).toBe("high");
expect(patchBodies[1]).not.toHaveProperty("localReasoningEffort");
});
});
+197
View File
@@ -0,0 +1,197 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import {
appleHealthExportZip,
archiveWithoutExportXml,
FIXTURE_READINGS,
MISSING_EXPORT_XML_REASON,
} from "./fixtures/apple-health-export";
/**
* Apple Health `export.zip` → readings on the measurements list.
*
* The one journey that crosses every layer the import owns: a person drops
* an archive on `/settings/export`, the kick-off route streams it to disk and
* queues `apple-health-import-v2`, the pg-boss worker in the same process
* unpacks it and streams the XML into `Measurement` rows, the card's status
* poll turns the spinner into a written outcome, and the rows show up on
* `/measurements` carrying the units the parser resolved. Every one of those
* steps has unit coverage; none of it proves the chain holds when a real
* browser drives it against a real queue and a real database.
*
* The archives are synthetic and built in memory — see
* `fixtures/apple-health-export.ts`.
*/
type FixtureReading = (typeof FIXTURE_READINGS)[keyof typeof FIXTURE_READINGS];
/**
* Serial, because the journey mutates the one shared account and the refusal
* control reads a count off it. Two of these tests in flight at once would
* also spend the kick-off route's three-uploads-per-minute budget on each
* other rather than on what they are testing.
*/
test.describe.configure({ mode: "serial" });
/**
* The import is the slowest single action in the browser suite: an upload,
* a queue hop, an unpack, a parse, and a status poll that ticks every two
* seconds. The default 30 s budget covers none of that on a loaded runner.
*/
test.setTimeout(180_000);
/**
* Clear this account's upload bucket before each upload.
*
* `POST /api/import/apple-health-export` allows three uploads per user per
* minute, which is the right production number and exactly one too few for a
* spec that uploads twice and is expected to survive `--repeat-each`. The
* fourth upload inside the window would come back 429 and the card would
* render the rate-limit copy — a red run that says nothing about the import.
*
* Reaching for Postgres directly is the same channel `global-setup.ts` uses
* to seed and to clear the auth buckets; the alternative is to sit out a
* 60-second window, which is a sleep wearing a poll's clothing.
*/
async function clearImportUploadBucket(): Promise<void> {
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error(
"DATABASE_URL is unset — the import journey needs the same database the app is running against.",
);
}
const { default: pg } = await import("pg");
const client = new pg.Client({ connectionString });
await client.connect();
try {
await client.query(
`DELETE FROM rate_limits WHERE key LIKE 'import:apple-health:%'`,
);
} finally {
await client.end();
}
}
/** Open the import surface and hand back the Apple Health card. */
async function openImportCard(page: Page) {
await page.goto("/settings/export", { waitUntil: "domcontentloaded" });
const card = page.getByTestId("import-card-apple-health");
await expect(card).toBeVisible({ timeout: 30_000 });
return card;
}
/**
* Hand the archive to the card's own file input, which is what a drop or a
* click on "Choose file" ends up doing. The upload itself then runs through
* the card's `fetch`, so the spec seeds nothing the page would not have sent.
*/
async function uploadArchive(
page: Page,
archive: Buffer,
name: string,
): Promise<void> {
const card = await openImportCard(page);
await card.locator('input[type="file"]').setInputFiles({
name,
mimeType: "application/zip",
buffer: archive,
});
}
/** How many readings this account holds from an Apple Health import. */
async function appleHealthRowCount(page: Page): Promise<number> {
return page.evaluate(async () => {
const res = await fetch(
"/api/measurements?sourceEq=APPLE_HEALTH&limit=1&offset=0",
{ credentials: "include" },
);
const body = (await res.json()) as {
data: { meta: { total: number } } | null;
};
if (!body.data) throw new Error("measurements list returned no data");
return body.data.meta.total;
});
}
/**
* Assert one imported reading on the measurements list, by the value and the
* unit the row carries rather than by the locale text it renders.
*/
async function expectReadingOnList(
page: Page,
reading: FixtureReading,
): Promise<void> {
await page.goto(`/measurements?type=${reading.type}`, {
waitUntil: "domcontentloaded",
});
await expect(page.locator('[data-slot="measurement-rows"]')).toBeVisible({
timeout: 30_000,
});
const row = page.locator(
`[data-testid="measurement-row"][data-measurement-type="${reading.type}"]` +
`[data-measurement-value="${reading.value}"]`,
);
await expect(row).toHaveCount(1);
await expect(row).toHaveAttribute("data-measurement-unit", reading.unit);
}
test.describe("Apple Health export import", () => {
test.use({ storageState: STORAGE_STATE_PATH });
test("an uploaded export surfaces as readings with their units", async ({
page,
}) => {
await clearImportUploadBucket();
await uploadArchive(page, appleHealthExportZip(), "export.zip");
// The card polls the status route every two seconds and swaps the
// spinner for the written outcome on a terminal state. `data-outcome`
// is the outcome itself; the sentence beside it is translated copy.
const result = page.getByTestId("import-apple-health-result");
await expect(result).toBeVisible({ timeout: 150_000 });
await expect(result).toHaveAttribute("data-outcome", "success");
// The weight the archive wrote in kilograms, the blood-pressure pair it
// wrote in mmHg, and the step count it wrote as a bare count — each on
// the list, each carrying the unit the parser resolved for it.
await expectReadingOnList(page, FIXTURE_READINGS.weight);
await expectReadingOnList(page, FIXTURE_READINGS.systolic);
await expectReadingOnList(page, FIXTURE_READINGS.diastolic);
await expectReadingOnList(page, FIXTURE_READINGS.steps);
});
test("a distance written in kilometres is stored in metres", async ({
page,
}) => {
test.skip(
true,
"issue #944 — the parser resolves a record's unit from the type map " +
"and ignores the `unit` attribute the record carries, so a distance " +
"written as 2.484 km lands as 2.484 m. The fix is on a branch that " +
"has not reached main; this is the contract it has to meet, kept " +
"here at full strength rather than relaxed to match today's value.",
);
await expectReadingOnList(page, FIXTURE_READINGS.walkingDistance);
});
test("an archive without export.xml is refused and imports nothing", async ({
page,
}) => {
await clearImportUploadBucket();
await openImportCard(page);
const before = await appleHealthRowCount(page);
await uploadArchive(page, archiveWithoutExportXml(), "not-an-export.zip");
// The worker's own words, surfaced verbatim by the card: the failure
// reason is honest English free text, not a code the UI translates.
const error = page.getByTestId("import-apple-health-error");
await expect(error).toBeVisible({ timeout: 150_000 });
await expect(error).toContainText(MISSING_EXPORT_XML_REASON);
// And a refusal that still wrote something would be worse than no
// refusal at all.
expect(await appleHealthRowCount(page)).toBe(before);
});
});
+764
View File
@@ -0,0 +1,764 @@
/**
* A record, a snapshot of it, and the snapshot put back — one journey.
*
* The script this file is checked against:
*
* 1. an account records readings across three domains — two measurements, a
* medication with one dose, a mood entry — and files a small PDF in the
* vault;
* 2. it downloads its own record as the passphrase-sealed archive the export
* card offers, and the bytes are the `HLX1` envelope
* `src/lib/export/passphrase-archive.ts` documents, not a JSON file with
* a new extension;
* 3. an admin takes a snapshot from the backups console, waits for the
* pg-boss pass by asking the console's own endpoint what it holds, and
* downloads the stored copy;
* 4. the account loses a reading and a dose, gains a reading the snapshot
* never saw, and the snapshot is restored over it from the same console;
* 5. what was deleted is back under its ORIGINAL id, and what arrived after
* the snapshot is gone — which is what "the restore replaces the
* account's data tables" in `docs/ops/backup-restore.md` means when it is
* spelled out.
*
* Refusing controls, because a restore path that cannot say no is worse than
* none: a stored copy with one flipped ciphertext byte is refused and changes
* nothing, and a delegate holding whole-record READ inside the account sees no
* backup surface at all and is refused by every route behind it.
*
* One act reaches past this account, and by design: "Backup now" enqueues the
* `data-backup` pass, which writes a `WEEKLY_AUTO` row for EVERY account on the
* instance. The journey reads only its own row and deletes only its own rows,
* but it is not true that it touches nothing else. The restore is the other
* direction and is confined: the transaction is scoped to the snapshot's owner,
* and the instance-wide settings a disaster-recovery payload also carries are
* written only when the dialog's opt-in is ticked, which this file never ticks
* and asserts it never ticks.
*
* Everything the journey does, it does through the app: the readings and the
* document ride the page's own `fetch`, the archive and the snapshot ride the
* real buttons, the restore rides the typed-confirmation dialog. The only two
* things reaching Postgres directly are the ones a browser cannot express —
* resetting the account between repetitions, and corrupting one stored copy so
* the authenticated envelope has something to refuse. Both live in
* `setup/backup-journey-fixture.ts`.
*
* Serial and single-project: the four tests are four acts of one journey, they
* mutate the account destructively, and the last one moves a session's record
* selector. Its jar is its own for the reason `global-setup.ts` spells out.
*/
import { readFile } from "node:fs/promises";
import type { Page } from "@playwright/test";
import { EXPORT_ARGON2_PARAMS } from "@/lib/export/passphrase-archive";
import {
BACKUP_DELEGATE_STORAGE_STATE_PATH,
BACKUP_STORAGE_STATE_PATH,
E2E_BACKUP_ADMIN,
} from "./setup/global-setup";
import {
backupAccountId,
deleteStoredCopy,
resetBackupJourney,
storedIntakeIds,
storedMeasurements,
storeTamperedCopy,
} from "./setup/backup-journey-fixture";
import {
actWithReproof,
completeReproofWithPassword,
expireRecentProof,
useStaleSession,
} from "./setup/recent-proof";
import { expect, test } from "./setup/test";
test.describe.configure({ mode: "serial" });
/**
* The pass backs up every account in the database, the restore rewrites a
* dozen tables in one transaction, and the archive runs Argon2id at the OWASP
* cost. None of that fits the suite's 30-second default on a loaded runner.
*/
test.setTimeout(180_000);
/** Long enough to clear the export card's own 12-character minimum. */
const ARCHIVE_PASSPHRASE = "e2e-backup-journey-passphrase";
/** The reading the journey deletes and expects back, by value and by id. */
const RESTORED_WEIGHT_KG = 81.4;
/** The reading nothing touches — a restore that wiped it would be a defect. */
const UNTOUCHED_PULSE_BPM = 58;
/** The reading that arrives AFTER the snapshot and must not survive it. */
const POST_SNAPSHOT_PULSE_BPM = 66;
const MEDICATION_NAME = "E2E Backup Tablet";
/** The console's row list is painted, or its honest empty state is. */
const BACKUPS_SETTLED = '[data-slot="backup-rows"], [data-slot="empty-state"]';
/** The measurements list has finished its read, either way. */
const MEASUREMENTS_SETTLED =
'[data-slot="measurement-rows"], [data-slot="empty-state"]';
/** One stored snapshot as the console's own endpoint reports it. */
interface ConsoleRow {
id: string;
username: string;
type: string;
sizeBytes: number;
createdAt: string;
}
interface SeededRecord {
weightId: string;
intakeId: string;
medicationId: string;
documentId: string;
}
/** What the journey wrote, once the first act has written it. */
let seeded: SeededRecord | null = null;
/** The stored snapshot the first act takes; every later act addresses it. */
let snapshotId: string | null = null;
/** The deliberately corrupted copy, held so the file can take it away again. */
let tamperedCopyId: string | null = null;
function requireSeeded(): SeededRecord {
if (!seeded) throw new Error("the record was never seeded");
return seeded;
}
function requireSnapshot(): string {
if (!snapshotId) throw new Error("no snapshot was taken");
return snapshotId;
}
/**
* Write the record through the app's own routes, from the page's origin.
*
* The page's `fetch` rather than a Playwright request context, for the reason
* `glucose-journey.spec.ts` gives: a pooled context can hand a POST to a
* keep-alive socket the server has already closed, and the retry lands as a
* second row.
*/
function seedRecord(page: Page): Promise<SeededRecord> {
return page.evaluate(
async ([weightKg, pulseBpm, medicationName]: [number, number, string]) => {
const post = async (path: string, body: unknown): Promise<string> => {
const res = await fetch(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const json = (await res.json()) as {
data: { id: string } | null;
error: string | null;
};
if (!res.ok || !json.data) {
throw new Error(`${path} answered ${res.status}: ${json.error}`);
}
return json.data.id;
};
const at = (minutesAgo: number) =>
new Date(Date.now() - minutesAgo * 60_000).toISOString();
const weightId = await post("/api/measurements", {
type: "WEIGHT",
value: weightKg,
measuredAt: at(180),
});
await post("/api/measurements", {
type: "PULSE",
value: pulseBpm,
measuredAt: at(170),
});
const medicationId = await post("/api/medications", {
name: medicationName,
dose: "5 mg",
schedules: [{ windowStart: "08:00", windowEnd: "09:00" }],
});
const intakeId = await post(`/api/medications/${medicationId}/intake`, {
takenAt: at(160),
});
await post("/api/mood-entries", {
mood: "GUT",
note: "backup journey",
moodLoggedAt: at(150),
});
// The vault, through the same multipart body the upload card sends. A
// real minimal PDF: the route classifies by magic bytes and never trusts
// the wire content-type, so bytes that only claim to be one are refused.
const pdf = new TextEncoder().encode(
"%PDF-1.4\n%e2e-backup-journey\n" +
"1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n" +
"2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n" +
"3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]>>endobj\n" +
"xref\n0 4\ntrailer<</Size 4/Root 1 0 R>>\n%%EOF\n",
);
const form = new FormData();
form.append(
"file",
new File([pdf], "backup-journey.pdf", { type: "application/pdf" }),
);
form.append("title", "Backup journey probe");
const docRes = await fetch("/api/documents/inbound", {
method: "POST",
body: form,
});
const docJson = (await docRes.json()) as {
data: { id: string } | null;
error: string | null;
};
if (!docRes.ok || !docJson.data) {
throw new Error(
`/api/documents/inbound answered ${docRes.status}: ${docJson.error}`,
);
}
return { weightId, medicationId, intakeId, documentId: docJson.data.id };
},
[RESTORED_WEIGHT_KG, UNTOUCHED_PULSE_BPM, MEDICATION_NAME] as [
number,
number,
string,
],
);
}
/** This account's scheduled snapshot as the console's endpoint reports it. */
function readConsoleRow(page: Page): Promise<ConsoleRow | null> {
return page.evaluate(async (username: string) => {
const res = await fetch("/api/admin/backups", { credentials: "include" });
const body = (await res.json()) as {
data: { rows: ConsoleRow[] } | null;
};
const mine = (body.data?.rows ?? []).filter(
(row) => row.username === username && row.type === "WEEKLY_AUTO",
);
return mine[0] ?? null;
}, E2E_BACKUP_ADMIN.username);
}
/** Open the backups console and wait for its row list to settle. */
async function openBackupsConsole(page: Page): Promise<void> {
await page.goto("/admin/backups", { waitUntil: "domcontentloaded" });
await expect(page.locator(BACKUPS_SETTLED).first()).toBeVisible({
timeout: 30_000,
});
}
/**
* The console's row for one snapshot, at whichever layout is painting.
*
* Both the wide table and the narrow card list are in the tree — only CSS
* hides one — so the `:visible` filter is what keeps this a single element
* rather than a pair. This file runs in the desktop project alone (see the
* `chromium-mobile` ignore list in `playwright.config.ts`), so the table row is
* the one that answers; the card's identical attributes are what let the same
* handle hold if it ever runs narrow, and are not exercised here.
*/
function snapshotRow(page: Page, id: string) {
return page.locator(`[data-backup-id="${id}"]:visible`);
}
/**
* Drive the typed-confirmation dialog on one row and hand back the answer.
*
* A restore asks for a recent proof, and the session is made stale first, so
* the first POST is always refused and the answer waited for is the one to
* the retry the page sends after the re-proof dialog.
*/
async function restoreThroughDialog(page: Page, id: string) {
await expireRecentProof(page);
const answered = page.waitForResponse(
(response) =>
response.url().includes(`/api/admin/backups/${id}/restore`) &&
response.request().method() === "POST" &&
response.status() !== 401,
);
await snapshotRow(page, id).getByTestId("backup-restore-trigger").click();
// The instance-wide opt-in, left exactly where the dialog puts it. Asserted
// rather than merely not clicked: a default that flipped would hand this
// journey the power to rewrite the host's settings — the document size cap
// among them — for every other spec sharing the server.
await expect(
page.getByTestId("backup-restore-instance-settings"),
).not.toBeChecked();
await page.getByTestId("backup-restore-prompt").fill("RESTORE");
await page.getByTestId("backup-restore-confirm").click();
await completeReproofWithPassword(page, E2E_BACKUP_ADMIN.password);
return answered;
}
test.describe("Backup and restore, through the settings surfaces", () => {
test.use({ storageState: BACKUP_STORAGE_STATE_PATH });
// The archive, the snapshot download and every restore ask for a recent
// proof. Each test acts from a session of its own that is made stale before
// each of those presses, so the re-proof dialog is met every time, whatever
// minute of the run the journey lands in.
let endStaleSession: (() => Promise<void>) | null = null;
test.beforeEach(async ({ page }) => {
endStaleSession = await useStaleSession(page, E2E_BACKUP_ADMIN.username);
});
test.afterEach(async () => {
await endStaleSession?.();
endStaleSession = null;
});
test.beforeAll(async () => {
seeded = null;
snapshotId = null;
tamperedCopyId = null;
await resetBackupJourney();
});
test.afterAll(async () => {
if (tamperedCopyId) await deleteStoredCopy(tamperedCopyId);
tamperedCopyId = null;
});
test("a record is written, sealed into an HLX1 archive, and snapshotted", async ({
page,
}) => {
await page.goto("/measurements", { waitUntil: "domcontentloaded" });
await expect(page.locator(MEASUREMENTS_SETTLED).first()).toBeVisible({
timeout: 30_000,
});
seeded = await seedRecord(page);
const record = seeded;
// On the list, by the number the row carries rather than by the text the
// formatter prints for whoever is looking. The attribute holds the
// DISPLAYED value, after the account's unit preference is applied — the
// same number as the stored one under this account's default metric
// preference, and deliberately not a claim about the stored row. The
// database-side assertions later in the file are that claim.
await page.reload({ waitUntil: "domcontentloaded" });
await expect(
page
.locator(
'[data-testid="measurement-row"][data-measurement-type="WEIGHT"]' +
`[data-measurement-value="${RESTORED_WEIGHT_KG}"]`,
)
.first(),
).toBeVisible({ timeout: 30_000 });
// ── the account's own archive ────────────────────────────────────────
await page.goto("/settings/export", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("export-card-full-backup")).toBeVisible({
timeout: 30_000,
});
await page.getByTestId("export-full-backup-encrypt").click();
await page
.getByTestId("export-full-backup-passphrase")
.fill(ARCHIVE_PASSPHRASE);
const archiveDownload = page.waitForEvent("download");
await actWithReproof(page, E2E_BACKUP_ADMIN.password, () =>
page.getByTestId("export-action-full-backup").click(),
);
const bytes = await readFile(await (await archiveDownload).path());
// The header `passphrase-archive.ts` documents, field by field: magic,
// version, KDF id, then the Argon2 cost the archive carries so a later
// cost bump still opens it. Asserted as bytes, because "a file arrived"
// is equally true of plaintext JSON under a new extension.
expect(bytes.subarray(0, 4).toString("ascii")).toBe("HLX1");
expect(bytes[4], "HLX1 version").toBe(0x01);
expect(bytes[5], "KDF id — Argon2id").toBe(0x01);
// The cost travels in the file so it may change, so it is asserted against
// the constant the writer uses rather than against today's numbers: a
// legitimate cost bump is a correct product change, not a red spec.
expect(bytes.readUInt32BE(6), "Argon2 memory cost, KiB").toBe(
EXPORT_ARGON2_PARAMS.memoryCost,
);
expect(bytes.readUInt32BE(10), "Argon2 time cost").toBe(
EXPORT_ARGON2_PARAMS.timeCost,
);
expect(bytes[14], "Argon2 parallelism").toBe(
EXPORT_ARGON2_PARAMS.parallelism,
);
expect(bytes[15], "salt length").toBe(16);
// A record carrying five sections is not a header and an auth tag.
expect(bytes.byteLength).toBeGreaterThan(1024);
// ── the instance's own snapshot ──────────────────────────────────────
await openBackupsConsole(page);
// The row this account had before the click, or none. The poll below asks
// "is the stored copy a different one", and the server's own clock is the
// only one both sides share — comparing a server timestamp against the
// runner's would pass on a stale row under any clock skew.
const previous = await readConsoleRow(page);
const enqueued = page.waitForResponse(
(response) =>
response.url().includes("/api/admin/backups/run") &&
response.request().method() === "POST",
);
// The list is populated by now, so it is the card action that runs the
// pass; the empty state's CTA carries its own id.
await page.getByTestId("backup-run-now").click();
// Named here rather than left to the poll: with no pg-boss instance in the
// process the route answers 503 and nothing is ever enqueued, and the poll
// would spend two minutes to report that the pass stored no copy — true,
// and about the wrong subsystem. 429 is the same story on a reset that
// stopped clearing the run bucket.
expect(
(await enqueued).status(),
"the manual pass was enqueued (503 = no worker in this process, 429 = rate limit)",
).toBe(200);
// The pass runs on pg-boss inside this process, so the console cannot know
// when it finished — it can only be asked. Poll the endpoint the page
// itself reads until this account's stored copy is newer than the click.
// No sleep: a fixed wait would be a guess about a queue.
const found: { row: ConsoleRow | null } = { row: null };
await expect
.poll(
async () => {
const row = await readConsoleRow(page);
const fresh =
row !== null &&
(previous === null ||
row.id !== previous.id ||
row.createdAt !== previous.createdAt);
if (fresh) found.row = row;
return fresh;
},
{
timeout: 120_000,
intervals: [500, 1_000, 2_000],
message: "the data-backup pass never stored a copy of this account",
},
)
.toBe(true);
const row = found.row;
if (!row) throw new Error("the poll reported a row it did not keep");
expect(
row.sizeBytes,
"a stored copy of a record is not empty",
).toBeGreaterThan(512);
snapshotId = row.id;
// The console paints it, and the row's own actions are on screen.
await page.reload({ waitUntil: "domcontentloaded" });
await expect(snapshotRow(page, row.id)).toHaveCount(1, { timeout: 30_000 });
await expect(
snapshotRow(page, row.id).getByTestId("backup-restore-trigger"),
).toBeVisible();
// ── what the stored copy actually carries ────────────────────────────
const snapshotDownload = page.waitForEvent("download");
await actWithReproof(page, E2E_BACKUP_ADMIN.password, () =>
snapshotRow(page, row.id).getByTestId("backup-download").click(),
);
const payload = JSON.parse(
await readFile(await (await snapshotDownload).path(), "utf8"),
) as {
measurements: Array<{ id: string }>;
intakeEvents: Array<{ id: string }>;
moodEntries: unknown[];
documents: Array<{ id: string; contentEncrypted?: string }>;
};
expect(payload.measurements.map((m) => m.id)).toContain(record.weightId);
expect(payload.intakeEvents.map((e) => e.id)).toContain(record.intakeId);
expect(payload.moodEntries).toHaveLength(1);
expect(payload.documents.map((d) => d.id)).toContain(record.documentId);
// A disaster-recovery copy carries document content as ciphertext, and the
// restore refuses a file that brought only metadata — so an empty field
// here is a snapshot nobody could restore.
expect(
payload.documents.find((d) => d.id === record.documentId)
?.contentEncrypted ?? "",
).not.toBe("");
});
test("a stored copy with one flipped byte is refused and changes nothing", async ({
page,
}) => {
const before = await storedMeasurements();
const tamperedId = await storeTamperedCopy(requireSnapshot());
// Dropped again as soon as the control is done with it, rather than at the
// next repetition's reset: until then it is a broken row in the console's
// list for anyone who opens `/admin/backups`.
tamperedCopyId = tamperedId;
await openBackupsConsole(page);
const response = await restoreThroughDialog(page, tamperedId);
// The envelope is AES-256-GCM and its tag covers every ciphertext byte, so
// the flip is caught before the transaction opens. 422 and
// `backup.payload.undecryptable` are the refusal the route documents —
// `docs/api/openapi.yaml`, and `docs/ops/backup-restore.md` for the
// operator reading it after a key rotation — rather than whatever the
// handler happened to answer. The code is asserted and not the sentence:
// the sentence is prose that may be reworded, the code is the contract.
expect(response.status()).toBe(422);
expect(await response.json()).toMatchObject({
data: null,
meta: { errorCode: "backup.payload.undecryptable" },
});
// A refusal that still wrote something would be worse than no refusal.
expect(await storedMeasurements()).toEqual(before);
});
test("the snapshot puts back what was deleted and drops what came after", async ({
page,
}) => {
const record = requireSeeded();
await page.goto("/measurements", { waitUntil: "domcontentloaded" });
await expect(page.locator(MEASUREMENTS_SETTLED).first()).toBeVisible({
timeout: 30_000,
});
// One reading and one dose go, and a reading the snapshot never saw
// arrives. Both deletions are tombstones — the app soft-deletes a reading
// and a dose — so "back" has to mean live again, not merely present.
const laterId = await page.evaluate(
async ([weightId, medicationId, intakeId, pulse]: [
string,
string,
string,
number,
]) => {
const del = async (path: string) => {
const res = await fetch(path, { method: "DELETE" });
if (!res.ok) throw new Error(`${path} answered ${res.status}`);
};
await del(`/api/measurements/${weightId}`);
await del(`/api/medications/${medicationId}/intake/${intakeId}`);
const res = await fetch("/api/measurements", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "PULSE",
value: pulse,
measuredAt: new Date(Date.now() - 60_000).toISOString(),
}),
});
const body = (await res.json()) as { data: { id: string } | null };
if (!res.ok || !body.data) {
throw new Error(`/api/measurements answered ${res.status}`);
}
return body.data.id;
},
[
record.weightId,
record.medicationId,
record.intakeId,
POST_SNAPSHOT_PULSE_BPM,
] as [string, string, string, number],
);
const beforeRestore = await storedMeasurements();
expect(
beforeRestore.find((m) => m.id === record.weightId)?.deletedAt,
"the reading really is tombstoned before the restore",
).not.toBeNull();
expect(beforeRestore.map((m) => m.id)).toContain(laterId);
await openBackupsConsole(page);
const response = await restoreThroughDialog(page, requireSnapshot());
// The restore runs on the `backup-restore` queue: the request answers 202
// with the job and its status route, and the worker inside the server
// under test does the work. Nothing below is read until the job says it
// is done, so every assertion is about the finished restore rather than
// a moment in the middle of it.
expect(response.status()).toBe(202);
const queued = (await response.json()) as {
data: { jobId: string; status: string; statusUrl: string };
};
expect(queued.data.status).toBe("queued");
expect(queued.data.statusUrl).toBe(
`/api/admin/backups/restores/${queued.data.jobId}`,
);
await expect
.poll(
async () => {
const res = await page.request.get(queued.data.statusUrl);
const body = (await res.json()) as {
data: {
status: string;
failure: { code: string } | null;
} | null;
};
// A failed job ends the wait with its code in the message instead
// of running the clock out on a state that will never change.
return body.data?.status === "failed"
? `failed: ${body.data.failure?.code ?? "unknown"}`
: body.data?.status;
},
{ timeout: 60_000, intervals: [250, 500, 1_000] },
)
.toBe("succeeded");
const afterRestore = await storedMeasurements();
// Identity, not merely equivalence. The payload carries each row's own id,
// so a restore that re-created the reading under a fresh one would have
// written a different record that happens to read the same.
const weight = afterRestore.find((m) => m.id === record.weightId);
expect(
weight,
"the deleted reading is back under its own id",
).toBeDefined();
expect(weight?.value).toBe(RESTORED_WEIGHT_KG);
expect(
weight?.deletedAt,
"and it is live, not still tombstoned",
).toBeNull();
const dose = (await storedIntakeIds()).find(
(e) => e.id === record.intakeId,
);
expect(dose, "the deleted dose is back under its own id").toBeDefined();
expect(dose?.deletedAt).toBeNull();
// The reading nothing touched is still there. Without this, an emptied
// account would satisfy every assertion above about the tombstones.
expect(
afterRestore.filter((m) => m.value === UNTOUCHED_PULSE_BPM),
).toHaveLength(1);
// And the reading that arrived after the snapshot is gone.
// `docs/ops/backup-restore.md` says the restore "replaces the account's
// data tables", and `restore-backup.ts` puts it as "one transaction replaces
// every serialized owner-scoped class". Replacing is not merging: whoever
// restores yesterday's copy loses today's readings, and that is the
// documented behaviour rather than an accident of the implementation.
expect(afterRestore.map((m) => m.id)).not.toContain(laterId);
// The list agrees with the database.
await page.goto("/measurements", { waitUntil: "domcontentloaded" });
await expect(
page
.locator(
'[data-testid="measurement-row"][data-measurement-type="WEIGHT"]' +
`[data-measurement-value="${RESTORED_WEIGHT_KG}"]`,
)
.first(),
).toBeVisible({ timeout: 30_000 });
await expect(
page.locator(
'[data-testid="measurement-row"][data-measurement-type="PULSE"]' +
`[data-measurement-value="${POST_SNAPSHOT_PULSE_BPM}"]`,
),
).toHaveCount(0);
});
});
test.describe("A read-level delegate inside the record", () => {
test.use({ storageState: BACKUP_DELEGATE_STORAGE_STATE_PATH });
test("sees no backup surface, and every route behind it refuses", async ({
page,
}) => {
// Switched in through the switcher a person uses, not by a stamp written
// behind the app's back. The switcher is a slice of the user menu, so the
// menu opens first — the same two steps `v137-record-session-fence.spec.ts`
// takes, and the trigger's accessible name is the only handle it has.
await page.goto("/", { waitUntil: "domcontentloaded" });
const userMenu = page.getByRole("button", { name: "User menu" }).first();
await expect(userMenu).toBeVisible({ timeout: 30_000 });
await userMenu.click();
const trigger = page.locator('[data-slot="account-switcher-trigger"]');
await expect(trigger).toBeVisible({ timeout: 30_000 });
await trigger.click();
const entry = page.locator(
'[data-slot="account-switcher-entry"]' +
`[data-account-username="${E2E_BACKUP_ADMIN.username}"]`,
);
await expect(entry).toBeVisible({ timeout: 30_000 });
await entry.click();
// Wait for the shell to say the switch landed, not merely that the click
// did. The stamp is written on the session row by a request the click
// fires, so navigating straight afterwards can load the next page under
// the delegate's OWN record and find every actor surface exactly where it
// belongs — a pass that says nothing. The banner names the record and the
// affordance it resolved, so this waits for both; `view` is what
// `resolveRecordPresentation` calls a READ grant, and a grant that had
// widened would paint `view-and-add` here instead of matching.
await expect(
page.locator(
'[data-slot="shared-record-banner"]' +
`[data-account-id="${await backupAccountId()}"]` +
'[data-access-level="view"][data-record-kind="shared"]',
),
).toBeVisible({ timeout: 30_000 });
// Settings destinations that belong to the ACTOR do not mount inside
// somebody else's record: the shell paints the not-covered panel in place
// of the whole section. That panel is the positive half of this check —
// without it, an absent export card would only mean the page had not
// finished painting.
await page.goto("/settings/export", { waitUntil: "domcontentloaded" });
await expect(
page.locator('[data-slot="shared-record-unavailable"]'),
).toBeVisible({ timeout: 30_000 });
await expect(page.getByTestId("export-card-full-backup")).toHaveCount(0);
await expect(page.getByTestId("export-action-full-backup")).toHaveCount(0);
// The console is not a place a non-admin lands: `AuthShell` sends them to
// the dashboard and the admin frame paints nothing on the way.
await page.goto("/admin/backups", { waitUntil: "domcontentloaded" });
// The dashboard, by path. `/\/$/` also matches an admin URL that merely
// ends in a slash, which is the one outcome this assertion exists to rule
// out.
await expect
.poll(() => new URL(page.url()).pathname, { timeout: 30_000 })
.toBe("/");
await expect(page.getByTestId("backup-run-now")).toHaveCount(0);
await expect(page.getByTestId("backup-run-now-empty")).toHaveCount(0);
await expect(page.getByTestId("backup-restore-trigger")).toHaveCount(0);
// And the routes underneath, asked from the delegate's own session.
// `requireAdmin()` is cookie-only and refuses before the row is read, so
// the restore below names the REAL snapshot: a 403 on an id that does not
// exist would prove nothing about the one that does.
const refusals = await page.evaluate(async (snapshot: string) => {
const call = async (path: string, init?: RequestInit) => {
const res = await fetch(path, init);
const body = (await res.json()) as { error: string | null };
return { status: res.status, error: body.error };
};
return {
list: await call("/api/admin/backups"),
run: await call("/api/admin/backups/run", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{}",
}),
restore: await call(`/api/admin/backups/${snapshot}/restore`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ confirm: "RESTORE" }),
}),
};
}, requireSnapshot());
// Each refusal is named, not merely counted. A switched session is also
// fenced off non-allowlisted endpoints (`sharing.not_permitted`), and that
// fence answers 403 too — so a bare status check would stay green through
// an admin gate that had been removed, with the second guard quietly
// covering for it. The sentence says which boundary spoke.
for (const refusal of [
refusals.list,
refusals.run,
refusals.restore,
] as const) {
expect(refusal.status).toBe(403);
expect(refusal.error).toBe("Admin access required");
}
// The refused restore left the owner's record where the previous act put
// it, rather than half-applying and reporting a refusal.
const owner = await storedMeasurements();
expect(owner.filter((m) => m.value === RESTORED_WEIGHT_KG)).toHaveLength(1);
});
});
+104
View File
@@ -0,0 +1,104 @@
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
/**
* Recharts measures every tick label in one shared off-screen span
* (`#recharts_measurement_span`). Under `<body>` each read cost a
* document-wide style recalc, because the stylesheet's descendant-subject
* `:has()` rules leave Chromium no way to scope the invalidation; on a
* seeded dashboard that was about 1.8 s of main-thread time under a 4x CPU
* slowdown. The chart runtime now parks the span in a contained host under
* `<html>` (`src/components/charts/text-measurement-host.ts`).
*
* Pinned here, in a real engine:
* - the span Recharts uses is the one in the host, not a second one it
* created under `<body>`, including after a client-side round trip;
* - every string the charts drew measures exactly as it does under
* `<body>`, so the move cannot change a single tick or label.
*/
test.describe("chart text measurement host", () => {
test.use({ storageState: STORAGE_STATE_PATH });
async function assertHostInPlace(page: import("@playwright/test").Page) {
const placement = await page.evaluate(() => {
const spans = document.querySelectorAll("#recharts_measurement_span");
const span = spans[0] as HTMLElement | undefined;
return {
count: spans.length,
hostSlot: span?.parentElement?.dataset.slot ?? null,
hostParent: span?.parentElement?.parentElement?.tagName ?? null,
};
});
expect(placement).toEqual({
count: 1,
hostSlot: "chart-text-measurement-host",
hostParent: "HTML",
});
}
test("the dashboard charts measure text outside <body>, with identical results", async ({
page,
}) => {
await page.goto("/", { waitUntil: "domcontentloaded" });
await expect(page.locator(".recharts-wrapper").first()).toBeVisible({
timeout: 20_000,
});
await assertHostInPlace(page);
const parity = await page.evaluate(() => {
const host = document.getElementById(
"recharts_measurement_span",
) as HTMLElement;
const reference = document.createElement("span");
document.body.appendChild(reference);
// Recharts' own measurement style (`getStringSize`).
const base = {
position: "absolute",
top: "-20000px",
left: "0",
padding: "0",
margin: "0",
border: "none",
whiteSpace: "pre",
};
const strings = [
...new Set(
[...document.querySelectorAll(".recharts-wrapper text")]
.map((el) => el.textContent ?? "")
.filter(Boolean),
),
];
const mismatches: string[] = [];
for (const fontSize of ["10px", "12px", "14px"]) {
for (const text of strings) {
Object.assign(host.style, base, { fontSize });
Object.assign(reference.style, base, { fontSize });
host.textContent = text;
reference.textContent = text;
const a = host.getBoundingClientRect();
const b = reference.getBoundingClientRect();
if (a.width !== b.width || a.height !== b.height) {
mismatches.push(`${text}@${fontSize}`);
}
}
}
reference.remove();
return { measured: strings.length, mismatches };
});
// A chart with no labels would make the parity check vacuous.
expect(parity.measured).toBeGreaterThan(0);
expect(parity.mismatches).toEqual([]);
// A client-side round trip re-renders the shell; the host must survive
// it, or Recharts quietly recreates its span under <body>.
await page.locator('a[href="/insights"]:visible').first().click();
await page.waitForURL((url) => url.pathname === "/insights");
await page.locator('a[href="/"]:visible').first().click();
await page.waitForURL((url) => url.pathname === "/");
await expect(page.locator(".recharts-wrapper").first()).toBeVisible({
timeout: 20_000,
});
await assertHostInPlace(page);
});
});
+2 -2
View File
@@ -8,8 +8,8 @@ import { mockDashboardSnapshot } from "./utils/mock-dashboard-snapshot";
*
* Two assertions per chart visible in the dashboard's initial paint:
*
* 1. Header layout integrity — the range tabs (`7 pts / 30 pts /
* 90 pts / All`) and the cog dropdown sit on a SINGLE horizontal
* 1. Header layout integrity — the range tabs (`7d / 30d /
* 90d / All`) and the cog dropdown sit on a SINGLE horizontal
* row inside the chart card. Pre-fix the bucket-aggregation chip
* ("Weekly avg" / "Monthly avg") + comparison caption pushed the
* tabs onto a second row on Pixel 5 (and 3-4 rows on Galaxy Fold
+496
View File
@@ -0,0 +1,496 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./setup/test";
import { SEAM_BANNERS_STORAGE_STATE_PATH } from "./setup/global-setup";
/**
* The seam again, this time with chrome above it.
*
* `chrome-header-seam.spec.ts` measures the two header borders on a shell with
* nothing above them. That is the state almost every session is in, and it is
* also the only state in which the seam cannot break: with no banner painted,
* the sidebar logo band and the top bar both start at y=0 whatever the layout
* does with them.
*
* The banners are the case that breaks it. Each one is a full-width strip that
* paints above the top bar, and while they lived INSIDE the content column they
* pushed the top bar down while the sidebar band stayed where it was — one line
* across the top of the app became two lines a banner-height apart, and three
* can stack at once. Measured before the fix, on the French locale strip: one
* banner offset the two borders by 66.5px at 768px and 61.0px at 1280px, and
* all three together by 184.5px and 143.0px. So this spec forces them on and
* measures the same two borders.
*
* ## How each banner is forced
*
* Honestly, through the condition the component actually reads — no injected
* DOM, no test-only prop:
*
* - **Maintainership** paints on a locale HealthLog does not hand-maintain.
* The context cookie is switched from `en` to `fr`, which is what a
* French-speaking user's browser carries. The swap happens with no page
* alive (`about:blank`): `I18nProvider` rewrites `healthlog-locale` from
* its own active locale on mount, so a cookie written under a live English
* page is reverted within the second.
* - **Shared record** paints while this session is inside somebody else's
* record, so this file switches into one. It used to fake the state instead
* — capture `/api/auth/me`, serve it back with the sharing block filled —
* because the switch is stamped on the SESSION ROW and moving the shared
* jar's row would move it for every spec holding that cookie. v1.37.0 took
* that shortcut away and gave back the thing that made it necessary: the
* record context is now proved across the payload, the fence store and the
* transition machine together, so a payload alone cannot produce it; and a
* spec that switches gets a login of its own
* (`SEAM_BANNERS_STORAGE_STATE_PATH`), which is what keeps this file's reach
* inside this file. The grant is the seeded whole-record READ on
* `e2e-level-read` — whole-record deliberately, because a narrowed one drops
* nav destinations and that is a different spec's subject.
* - **Offline** paints while `navigator.onLine` is false, which
* `context.setOffline(true)` produces for real, event and all. It is armed
* last because it is the only stage a navigation cannot follow, and it is
* armed after the switch for the same reason: entering a record is a
* network act.
*
* The demo banner is the one that cannot be forced from a spec: `DEMO_MODE` is
* a server env var read by the root layout, and the suite shares one server
* whose mutations would all be blocked by turning it on. It is the same strip
* as the other three (`border-b px-3 py-2 text-xs`) in the same place in the
* stack, so the three forced here exercise its geometry; nothing in the stack
* is specific to which banner is in it.
*
* ## What is asserted
*
* Two properties, and the second is why the banners were hoisted above the
* shell row rather than nudged inside it:
*
* 1. The seam holds — the two header borders keep sharing one line at every
* stack depth, so chrome above the header cannot displace one band and
* not the other.
* 2. The shell stays inside the viewport — the banners are part of the
* `h-dvh` budget, not added on top of it, so no depth of stack introduces
* a page-level scrollbar. `<main>` remains the only vertical scroller.
*
* Property 2 is measured below `md` as well as above it, where there is no
* sidebar and therefore no seam, because the scroll model is the half of the
* layout that the hoist could have broken at that breakpoint. It used to get
* there by running the file in the `chromium-mobile` project. It cannot any
* more: this file moves a session's record selector, and a second PROJECT is
* the one thing a separate cookie jar cannot fix — it would drive the same
* session row from two browsers at once. So the narrow viewport is measured
* inside the desktop project instead. Nothing is lost by that: the shell picks
* its column layout and its scroller from width-driven rules, and the property
* under test is a scroll height in CSS pixels.
*/
const LOCALE_COOKIE = "healthlog-locale";
/**
* Every banner that can paint above the top bar, so a stage can assert how many
* are up rather than only that the one it armed is.
*/
const BANNER_SLOTS = [
"offline-banner",
"shared-record-banner",
"demo-banner",
"maintainership-banner",
] as const;
type Band = { bottom: number; height: number; borderBottomWidth: number };
type ShellGeometry = {
topBar: Band | null;
sidebar: Band | null;
bannerCount: number;
bannerHeight: number;
/** `scrollHeight - clientHeight` of the document's scrolling element. */
documentOverflow: number;
viewportHeight: number;
};
async function readShell(page: Page): Promise<ShellGeometry> {
return page.evaluate(
(slots: string[]) => {
const band = (slot: string) => {
const el = document.querySelector(`[data-slot="${slot}"]`);
if (!el) return null;
const rect = el.getBoundingClientRect();
return {
bottom: rect.bottom,
height: rect.height,
borderBottomWidth: parseFloat(
getComputedStyle(el).borderBottomWidth || "0",
),
};
};
const banners = slots
.map((slot) => document.querySelector(`[data-slot="${slot}"]`))
.filter((el): el is Element => el != null);
const scroller = document.scrollingElement ?? document.documentElement;
return {
topBar: band("top-bar"),
sidebar: band("sidebar-header"),
bannerCount: banners.length,
bannerHeight: banners.reduce(
(sum, el) => sum + el.getBoundingClientRect().height,
0,
),
documentOverflow: scroller.scrollHeight - scroller.clientHeight,
viewportHeight: window.innerHeight,
};
},
BANNER_SLOTS as unknown as string[],
);
}
/** The seeded whole-record READ grant this file switches into. */
const TARGET_USERNAME = "e2e-level-read";
const sharedRecordBanner = (page: Page) =>
page.locator('[data-slot="shared-record-banner"]');
/**
* Wait until the shell is usable rather than merely present.
*
* The hydration gate is the shell's own hold while it settles which record it
* is showing. Measuring geometry through it would measure the placeholder. The
* budget is deliberately larger than the suite default: ten seconds is a
* statement about machine load, thirty about the gate never releasing.
*
* The paired positive control is the top bar and not an accessible name: half
* of this file runs under the French strip, and a helper that reached for an
* English label would be a helper that only works before the locale swap.
*/
async function expectShellReady(page: Page): Promise<void> {
await expect(
page.locator('[data-slot="record-scope-hydration-gate"]'),
).toHaveCount(0, { timeout: 30_000 });
await expect(page.locator('[data-slot="top-bar"]')).toBeVisible({
timeout: 30_000,
});
}
/**
* Start outside any record.
*
* The first stage asserts that nothing is painted above the top bar, and this
* jar's session row keeps whatever the previous test — or the previous attempt,
* on a CI retry — left it pointed at. Without this the "no banner" stage is a
* statement about run order.
*/
async function ensureOwnRecord(page: Page): Promise<void> {
const banner = sharedRecordBanner(page);
if ((await banner.count()) === 0) return;
await page.locator('[data-slot="shared-record-banner-exit"]').click();
await expect(banner).toHaveCount(0, { timeout: 30_000 });
await expectShellReady(page);
}
/**
* Switch into the target record, and re-press the button if the switch did not
* land.
*
* `POST /api/account/switch` is a compare-and-set on the session's record epoch
* and the client reconciles and retries exactly once, which is the right call
* for a person at a keyboard and one attempt short for a fixture that has just
* navigated. Bounded at three and asserted: if the record is not entered by
* then, that is a failure and it fails.
*/
async function enterSharedRecord(page: Page): Promise<void> {
const banner = sharedRecordBanner(page);
if ((await banner.count()) > 0) return;
for (let attempt = 0; attempt < 3; attempt++) {
await page.getByRole("button", { name: "User menu" }).first().click();
await page.locator('[data-slot="account-switcher-trigger"]').click();
const entry = page.locator(
`[data-slot="account-switcher-entry"][data-account-username="${TARGET_USERNAME}"]`,
);
await expect(entry).toBeVisible();
await entry.click();
try {
await expect(banner).toBeVisible({ timeout: 15_000 });
await expectShellReady(page);
return;
} catch {
// The switcher menu may still be open over the page; start clean.
await page.goto("/");
await expectShellReady(page);
}
}
await expect(banner).toBeVisible({ timeout: 15_000 });
}
/**
* Swap the context's pinned locale for one HealthLog ships as an AI-initial
* translation, so the maintainership strip has a reason to paint.
*
* The page is parked on `about:blank` for the swap. `I18nProvider` mirrors its
* ACTIVE locale into this cookie from an effect, so a cookie written while an
* English page is mounted is reverted before the next navigation can read it —
* measured, not assumed: the value flipped back inside one second. With no page
* running, the next navigation sends `fr` and the provider then mirrors `fr`.
*/
async function armUnmaintainedLocale(page: Page): Promise<void> {
const host = new URL(page.url()).hostname;
await page.goto("about:blank");
await page.context().addCookies([
{
name: LOCALE_COOKIE,
value: "fr",
domain: host,
path: "/",
expires: Math.floor(Date.now() / 1000) + 3600,
httpOnly: false,
secure: false,
sameSite: "Lax",
},
]);
}
/**
* Take the context offline and make sure the banner hears about it.
*
* `setOffline` produces the real condition — `navigator.onLine` flips to false,
* which is asserted here rather than assumed. Delivery of the `offline` EVENT
* to an already-loaded page is the part that is not reliable: this spec caught
* it missing once under a fully parallel run while passing three for three on
* its own. `<OfflineBanner>` only reads `navigator.onLine` at mount and
* otherwise waits on the event, so the event is re-dispatched here. That is the
* notification, not the condition, and the condition is verified first.
*/
async function armOffline(page: Page): Promise<void> {
// Let whatever is in flight land first. The Playwright context runs with
// `serviceWorkers: "block"`, so nothing has pre-cached the app shell and a
// lazily-imported chunk cut off mid-download throws the whole tree to the
// global error boundary — "Failed to load chunk … from module …", no top bar,
// no banner. That is a property of the harness rather than of the shell (a
// real install serves those chunks from the worker cache), so it is waited
// out rather than asserted on. Best-effort: a polling surface can keep the
// network from ever going fully idle.
await page.waitForLoadState("networkidle", { timeout: 5000 }).catch(() => {});
await page.context().setOffline(true);
await expect.poll(() => page.evaluate(() => navigator.onLine)).toBe(false);
await page.evaluate(() => window.dispatchEvent(new Event("offline")));
}
/**
* Serial, and for the same reason the file has its own jar: both tests move
* this session row's record selector, and two workers running them at once
* would move it under each other.
*/
test.describe.serial("app-chrome header seam under banners", () => {
test.use({ storageState: SEAM_BANNERS_STORAGE_STATE_PATH });
test("the header seam survives every depth of the banner stack", async ({
page,
}) => {
// Four stages measured at two widths, with a full page load per stage, a
// real record switch and a network settle either side of the offline one.
// Comfortably inside the suite default when it runs alone; the default 30s
// is not enough headroom for it on a loaded machine.
test.setTimeout(90_000);
await page.goto("/", { waitUntil: "domcontentloaded" });
const topBar = page.locator('[data-slot="top-bar"]');
const sidebarHeader = page.locator('[data-slot="sidebar-header"]');
await expect(topBar).toBeVisible();
await expect(sidebarHeader).toBeVisible();
await expectShellReady(page);
await ensureOwnRecord(page);
// Each stage adds one banner and leaves the previous ones up, so the last
// stage measures the whole stack rather than one banner at a time.
//
// `beforeResize` / `afterResize` exist for the offline stage alone: a
// viewport change can pull a chunk the page has not loaded yet, and a chunk
// fetch that fails with no network takes the whole shell down to the global
// error boundary. Observed once under `--repeat-each=3`, as a missing top
// bar and a "Failed to load chunk" screen. So the network comes back for
// the resize and the stage re-arms after it — the measurement is still
// taken offline, with the banner up.
type Stage = {
label: string;
arm: () => Promise<void>;
beforeResize?: () => Promise<void>;
afterResize?: () => Promise<void>;
};
// The shared record is armed FIRST, before the locale swap: entering a
// record is done through the switcher, and the switcher's controls are
// reached by their accessible names. Under the French strip those names are
// French, and a spec that drove the UI in one language while asserting the
// labels of another would be testing the translation bundle.
const stages: Stage[] = [
{ label: "no banner", arm: async () => {} },
{
label: "1 banner (shared record)",
arm: async () => {
await enterSharedRecord(page);
await expect(sharedRecordBanner(page)).toBeVisible();
},
},
{
label: "2 banners (+ maintainership)",
arm: async () => {
await armUnmaintainedLocale(page);
await page.goto("/", { waitUntil: "domcontentloaded" });
await expectShellReady(page);
await expect(
page.locator('[data-slot="maintainership-banner"]'),
).toBeVisible();
await expect(sharedRecordBanner(page)).toBeVisible();
},
},
{
label: "3 banners (+ offline)",
arm: async () => {},
beforeResize: async () => {
await page.context().setOffline(false);
await expect
.poll(() => page.evaluate(() => navigator.onLine))
.toBe(true);
},
afterResize: async () => {
await armOffline(page);
await expect(
page.locator('[data-slot="offline-banner"]'),
).toBeVisible();
},
},
];
// Stage outside, width inside: each banner is armed once and the resulting
// stack measured at both widths. 768px is the `md` breakpoint where the
// sidebar first appears — the narrowest shell that has a seam at all, and
// the width where a banner is most likely to wrap onto a second line.
for (const [index, stage] of stages.entries()) {
await stage.arm();
for (const width of [768, 1280] as const) {
await stage.beforeResize?.();
await page.setViewportSize({ width, height: 900 });
await expect
.poll(() => page.evaluate(() => window.innerWidth))
.toBe(width);
await stage.afterResize?.();
await expect(topBar).toBeVisible();
await expect(sidebarHeader).toBeVisible();
const shell = await readShell(page);
const at = `at ${width}px, ${stage.label}`;
expect(shell.topBar, `top bar missing ${at}`).not.toBeNull();
expect(shell.sidebar, `sidebar band missing ${at}`).not.toBeNull();
const top = shell.topBar!;
const side = shell.sidebar!;
// Two borders that do not exist also "line up".
expect(
top.borderBottomWidth,
`top bar has no bottom border ${at}`,
).toBeGreaterThan(0);
expect(
side.borderBottomWidth,
`sidebar band has no bottom border ${at}`,
).toBeGreaterThan(0);
// The stage armed what it said it armed. Without this a change that
// stopped every banner from painting would make the seam assertion
// below trivially true.
expect(
shell.bannerCount,
`${at}: expected ${index} banner(s) painted, found ${shell.bannerCount}`,
).toBe(index);
if (index > 0) {
expect(
shell.bannerHeight,
`${at}: the banners paint no height, so this stage proves nothing`,
).toBeGreaterThan(0);
}
// The seam. A banner that displaces one band and not the other shows
// up here as a step the size of the stack.
expect(
Math.abs(side.bottom - top.bottom),
`${at}: header seam steps by ${(side.bottom - top.bottom).toFixed(
2,
)}px — the banner stack (${shell.bannerHeight.toFixed(
2,
)}px) is displacing one band and not the other`,
).toBeLessThan(1);
// The banners come out of the viewport budget, not on top of it.
expect(
shell.documentOverflow,
`${at}: the document scrolls by ${shell.documentOverflow.toFixed(
2,
)}px — the banner stack pushed the shell past the viewport`,
).toBeLessThan(1);
}
}
});
test("the banner stack never pushes the shell past the viewport", async ({
page,
}) => {
// A real switch, a page load either side of it and a network settle before
// the offline stage, at two widths.
test.setTimeout(90_000);
await page.goto("/", { waitUntil: "domcontentloaded" });
await expect(page.locator('[data-slot="top-bar"]')).toBeVisible();
await expectShellReady(page);
await enterSharedRecord(page);
await armUnmaintainedLocale(page);
await page.goto("/", { waitUntil: "domcontentloaded" });
await expectShellReady(page);
await expect(
page.locator('[data-slot="maintainership-banner"]'),
).toBeVisible();
await expect(sharedRecordBanner(page)).toBeVisible();
await armOffline(page);
await expect(page.locator('[data-slot="offline-banner"]')).toBeVisible();
// 393px is the narrow end — a Pixel-5 viewport, below `md`, where the shell
// stacks in a column and there is no sidebar. 1280px is the wide end. The
// network comes back for the resize and the stage re-arms after it, for the
// reason written at the offline stage of the test above: a chunk fetch that
// fails with no network takes the whole shell down to the error boundary.
for (const [width, height] of [
[393, 851],
[1280, 900],
] as const) {
await page.context().setOffline(false);
await expect.poll(() => page.evaluate(() => navigator.onLine)).toBe(true);
await page.setViewportSize({ width, height });
await expect
.poll(() => page.evaluate(() => window.innerWidth))
.toBe(width);
await armOffline(page);
await expect(page.locator('[data-slot="offline-banner"]')).toBeVisible();
const shell = await readShell(page);
const at = `at ${width}px`;
expect(shell.bannerCount, `${at}: the stack did not arm`).toBe(3);
expect(shell.bannerHeight).toBeGreaterThan(0);
expect(
shell.documentOverflow,
`${at}: the document scrolls by ${shell.documentOverflow.toFixed(
2,
)}px under a ${shell.bannerHeight.toFixed(2)}px banner stack`,
).toBeLessThan(1);
// The top bar is still fully painted below the stack rather than pushed
// off the bottom of the viewport.
const top = shell.topBar!;
expect(top.height, `${at}: the top bar paints no height`).toBeGreaterThan(
32,
);
expect(
top.bottom,
`${at}: the banner stack pushed the top bar out of the viewport`,
).toBeLessThanOrEqual(shell.viewportHeight);
}
});
});
+135
View File
@@ -0,0 +1,135 @@
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
/**
* The bottom border of the top bar and the bottom border of the sidebar logo
* band form one horizontal line across the top of the app. The two elements
* sit in different columns of the shell flex row, so nothing in the layout
* makes them agree; both read `SHELL_HEADER_BAND`
* (`src/components/layout/shell-metrics.ts`) for the height AND the border,
* which is what keeps the line continuous.
*
* The structural half of that contract is asserted in
* `src/components/layout/__tests__/chrome-header-seam.test.tsx`. This spec
* asserts the painted result: same border bottom edge, same border width, at
* four widths spanning the sidebar's visible range, in both the expanded
* sidebar and the collapsed icon rail.
*
* The waits below settle on the two bands being VISIBLE and on the viewport
* having actually resized. Nothing here waits on a height or an offset, so a
* regression cannot hide behind the setup.
*/
// 768 px is the `md` breakpoint where the sidebar first appears; 1024 px is
// `lg`, where an unset collapse preference flips the rail to icons. Both
// boundaries and one width either side of them.
const WIDTHS = [768, 900, 1024, 1280] as const;
const SIDEBAR_COLLAPSED_KEY = "healthlog-sidebar-collapsed";
type BandGeometry = {
bottom: number;
height: number;
borderBottomWidth: number;
};
test.describe("app-chrome header seam", () => {
test.use({ storageState: STORAGE_STATE_PATH });
test.beforeEach(({}, testInfo) => {
test.skip(
testInfo.project.name === "chromium-mobile",
"the global sidebar is desktop-only (md+), so below md there is no seam",
);
});
for (const collapsed of [false, true] as const) {
test(`top bar and sidebar borders share one line (${
collapsed ? "collapsed rail" : "expanded sidebar"
})`, async ({ page }) => {
// Pin the rail state instead of letting the viewport default decide, so
// each run covers both shapes at every width.
await page.addInitScript(
([key, value]) => {
window.localStorage.setItem(key, value);
},
[SIDEBAR_COLLAPSED_KEY, String(collapsed)] as const,
);
await page.goto("/", { waitUntil: "domcontentloaded" });
const topBar = page.locator('[data-slot="top-bar"]');
const sidebarHeader = page.locator('[data-slot="sidebar-header"]');
for (const width of WIDTHS) {
await page.setViewportSize({ width, height: 900 });
// Settle on paint, not on geometry: both bands present and visible,
// the logo link inside the sidebar band rendered, and the viewport
// actually at the requested width.
await expect(topBar).toBeVisible();
await expect(sidebarHeader).toBeVisible();
await expect(sidebarHeader.locator("a[href='/']")).toBeVisible();
await expect
.poll(() => page.evaluate(() => window.innerWidth))
.toBe(width);
const seam = await page.evaluate(() => {
const read = (slot: string) => {
const el = document.querySelector(`[data-slot="${slot}"]`);
if (!el) return null;
const rect = el.getBoundingClientRect();
const style = getComputedStyle(el);
return {
bottom: rect.bottom,
height: rect.height,
borderBottomWidth: parseFloat(style.borderBottomWidth),
};
};
return {
topBar: read("top-bar"),
sidebar: read("sidebar-header"),
} as { topBar: BandGeometry | null; sidebar: BandGeometry | null };
});
const at = `at ${width}px (${collapsed ? "collapsed" : "expanded"})`;
expect(seam.topBar, `top bar missing ${at}`).not.toBeNull();
expect(seam.sidebar, `sidebar band missing ${at}`).not.toBeNull();
const top = seam.topBar!;
const side = seam.sidebar!;
// Two borders that do not exist also "line up". Prove each band
// actually paints a line, and paints it at the same weight, before
// comparing where the lines sit.
expect(
top.borderBottomWidth,
`top bar has no bottom border ${at}`,
).toBeGreaterThan(0);
expect(
side.borderBottomWidth,
`sidebar band has no bottom border ${at}`,
).toBeGreaterThan(0);
expect(
side.borderBottomWidth,
`the two borders are drawn at different weights ${at}`,
).toBeCloseTo(top.borderBottomWidth, 1);
// The bands are collapsed neither to zero nor to a sliver.
expect(top.height, `top bar has no height ${at}`).toBeGreaterThan(32);
expect(side.height, `sidebar band has no height ${at}`).toBeGreaterThan(
32,
);
// The seam itself: the bottom border sits on the band's border-box
// bottom edge, so equal bottoms means one continuous line.
expect(
Math.abs(side.bottom - top.bottom),
`header seam steps by ${(side.bottom - top.bottom).toFixed(
2,
)}px ${at}`,
).toBeLessThan(1);
}
});
}
});
+336
View File
@@ -0,0 +1,336 @@
import { mkdirSync } from "node:fs";
import { join } from "node:path";
import type { Locator, Page, Route, TestInfo } from "@playwright/test";
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
/**
* The geometry of a Coach answer, at 1440 x 900 (desktop project) and
* 390 x 844 (mobile project).
*
* Contracts under test:
*
* 1. Under an answer there is exactly one action row: the icon group and
* the time on the left, the tokens and model on the right, both halves
* on one line (their centres within 2 px, the row no taller than one
* 44 px target), the left group starting on the bubble's left edge and
* the meta ending inside the answer column.
* 2. The follow-up chips sit in the answer's column: their left edge is
* the bubble's, their text is the answer's size, and a chip is at most
* 36 px tall beside a pointer and at least 44 px on a phone.
* 3. Under a question, copy and remember share one row; nothing stacks
* below it.
* 4. Scrolled away from the end, a round button appears; it brings the
* thread back to the end and goes away again.
* 5. No thumbs, no evidence disclosure, no horizontal overflow.
*
* Screenshots are attached to the report (no pixel baselines) and, with
* `COACH_SHOT_DIR` set, written there too.
*/
const CONVERSATION_ID = "coach-answer-layout-e2e";
const TITLE = "Blood pressure and sleep";
const ANSWERS = [
"Your blood pressure stayed in a steady band over the last month. The morning readings sat a little higher than the evening ones, which is common, and none of the weeks stands out from the others.",
"Sleep looked regular on most nights. The weekends ran about forty minutes later at both ends, so the total stayed much the same while the timing moved.",
"Your resting heart rate held steady across the same weeks. Nothing in it lines up with the later weekend nights, so the two seem to move independently for now.",
"The period before looked much the same for blood pressure. Two readings in the second week were higher than the rest, and both were taken shortly after a workout.",
"Taken together, the month reads calm: steady blood pressure, regular sleep and a resting heart rate without surprises. Measuring at the same time each morning keeps the trend easy to read.",
];
const QUESTIONS = [
"How was my blood pressure this month?",
"And my sleep?",
"What about my resting heart rate?",
"Compare blood pressure with the period before",
"Sum it up for me",
];
const STEPS = [
{
id: "s1",
tool: "get_metric_series",
labelKey: "coach.step.readWindow",
label: "Checking: Blood pressure, last 30 days",
domain: "bp",
window: "last30days",
status: "done",
count: 28,
},
{
id: "s2",
tool: "get_sleep",
labelKey: "coach.step.readWindow",
label: "Checking: Sleep, last 30 days",
domain: "sleep",
window: "last30days",
status: "done",
count: 30,
},
];
const FOLLOW_UPS = [
{
id: "f1",
kind: "previous_period",
labelKey: "coach.followUp.previousPeriod",
label: "Compare with the period before",
reuse: false,
origin: "server",
},
{
id: "f2",
kind: "related_metric",
labelKey: "coach.followUp.relatedMetric",
label: "See also: Resting HR",
reuse: false,
origin: "server",
},
];
function messages() {
// Today, a few minutes apart, so the time reads as a bare clock.
const base = Date.now() - 60 * 60 * 1000;
const at = (minute: number) =>
new Date(base + minute * 60 * 1000).toISOString();
return ANSWERS.flatMap((answer, index) => [
{
id: `${CONVERSATION_ID}-u${index + 1}`,
role: "user",
content: QUESTIONS[index],
createdAt: at(index * 2),
metricSource: null,
providerType: null,
promptVersion: null,
tokensUsed: null,
model: null,
},
{
id: `${CONVERSATION_ID}-a${index + 1}`,
role: "assistant",
content: answer,
createdAt: at(index * 2 + 1),
metricSource: {
windows: ["last30days"],
metrics: ["bp", "sleep"],
steps: STEPS,
...(index === ANSWERS.length - 1 ? { followUps: FOLLOW_UPS } : {}),
},
providerType: "mock",
promptVersion: "e2e",
tokensUsed: 1234,
model: "gpt-4o-mini-2024-07-18",
},
]);
}
function fulfilJson(route: Route, data: unknown) {
return route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ data, error: null }),
});
}
async function mockConversation(page: Page) {
const summary = {
id: CONVERSATION_ID,
title: TITLE,
createdAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
updatedAt: new Date().toISOString(),
messageCount: ANSWERS.length * 2,
fenced: false,
attachments: [],
documentTitle: null,
};
await page.route(
/\/api\/insights\/chat(?:\/[^?]+)?(?:\?.*)?$/,
async (route) => {
const url = new URL(route.request().url());
if (url.pathname.startsWith(`/api/insights/chat/${CONVERSATION_ID}/`)) {
return fulfilJson(route, { results: [] });
}
if (url.pathname === `/api/insights/chat/${CONVERSATION_ID}`) {
return fulfilJson(route, {
...summary,
attachmentCount: 0,
summary: null,
messages: messages(),
});
}
return fulfilJson(route, { conversations: [summary], nextCursor: null });
},
);
await page.route("**/api/insights/coach/nudge-status*", (route) =>
fulfilJson(route, { nudgedAt: null, unread: false }),
);
await page.route("**/api/coach/about-me/questions*", (route) =>
fulfilJson(route, { questions: [] }),
);
}
async function box(locator: Locator) {
const b = await locator.boundingBox();
expect(b, "element has a box").not.toBeNull();
return b!;
}
async function shoot(page: Page, testInfo: TestInfo, name: string) {
const body = await page.screenshot({ fullPage: false });
await testInfo.attach(name, { body, contentType: "image/png" });
const dir = process.env.COACH_SHOT_DIR;
if (dir) {
mkdirSync(dir, { recursive: true });
await page.screenshot({ path: join(dir, `${name}.png`) });
}
}
const VIEWPORTS = {
"chromium-desktop": { width: 1440, height: 900, label: "1440" },
"chromium-mobile": { width: 390, height: 844, label: "390" },
} as const;
test.describe("Coach answer layout", () => {
test.use({ storageState: STORAGE_STATE_PATH });
test("one action row, chips in the answer column, jump to the latest", async ({
page,
}, testInfo) => {
const viewport = VIEWPORTS[testInfo.project.name as keyof typeof VIEWPORTS];
test.skip(!viewport, "measured in the desktop and the mobile project");
const desktop = viewport.width >= 640;
await page.setViewportSize({
width: viewport.width,
height: viewport.height,
});
await page.emulateMedia({ reducedMotion: "reduce" });
await serveAiBlock(page, aiBlockAvailable());
await mockConversation(page);
await page.goto(`/coach?c=${CONVERSATION_ID}`, {
waitUntil: "domcontentloaded",
});
const thread = page.locator('[data-slot="coach-message-thread"]');
const answers = page.locator('[data-slot="coach-bubble-assistant"]');
await expect(answers).toHaveCount(ANSWERS.length, { timeout: 15_000 });
const last = answers.last();
await expect(last).toContainText(ANSWERS.at(-1)!.slice(0, 40));
// The thread opens at its end.
await expect
.poll(() =>
thread.evaluate(
(el) => el.scrollHeight - el.scrollTop - el.clientHeight,
),
)
.toBeLessThanOrEqual(2);
if (desktop) await last.hover();
await shoot(page, testInfo, `answer-${viewport.label}`);
// 5. Nothing of the old furniture.
await expect(
page.locator('[data-slot^="coach-message-feedback"]'),
).toHaveCount(0);
await expect(page.locator('[data-slot^="coach-evidence"]')).toHaveCount(0);
await expect(page.locator('[data-slot="coach-token-footer"]')).toHaveCount(
0,
);
for (const el of [page.locator("#main-content"), thread]) {
const overflow = await el.evaluate((n) => n.scrollWidth - n.clientWidth);
expect(overflow, "no horizontal overflow").toBeLessThanOrEqual(0);
}
// 1. One action row under the answer.
const bubble = last.locator('[data-slot="coach-answer-bubble"]');
const column = last.locator('[data-slot="coach-answer-column"]');
const row = last.locator('[data-slot="coach-answer-actions"]');
const left = row.locator('[data-slot="coach-answer-actions-left"]');
const meta = row.locator('[data-slot="coach-answer-meta"]');
await expect(row).toHaveCount(1);
await expect(meta).toContainText("1,234 tokens");
await expect(row).toHaveCSS("opacity", "1");
const [bubbleBox, columnBox, rowBox, leftBox, metaBox] = await Promise.all(
[bubble, column, row, left, meta].map(box),
);
expect(
Math.abs(
leftBox.y + leftBox.height / 2 - (metaBox.y + metaBox.height / 2),
),
"left group and meta share one line",
).toBeLessThanOrEqual(2);
expect(rowBox.height, "the row is one line").toBeLessThanOrEqual(44);
expect(Math.abs(leftBox.x - bubbleBox.x)).toBeLessThanOrEqual(1);
expect(metaBox.x + metaBox.width).toBeLessThanOrEqual(
columnBox.x + columnBox.width + 1,
);
await expect(left.locator('[data-slot="coach-message-time"]')).toHaveCount(
1,
);
// 2. The chips in the answer's column, at the answer's size.
const chips = last.locator('[data-slot="coach-follow-up-chips"]');
await expect(chips.locator("[data-follow-up-id]")).toHaveCount(2);
const chipsBox = await box(chips);
expect(Math.abs(chipsBox.x - bubbleBox.x)).toBeLessThanOrEqual(1);
expect(chipsBox.y).toBeGreaterThanOrEqual(rowBox.y + rowBox.height - 1);
const answerSize = await bubble.evaluate(
(el) => getComputedStyle(el).fontSize,
);
for (const chip of await chips.locator("[data-follow-up-id]").all()) {
await expect(chip).toHaveCSS("font-size", answerSize);
const chipBox = await box(chip);
if (desktop) expect(chipBox.height).toBeLessThanOrEqual(36);
else expect(chipBox.height).toBeGreaterThanOrEqual(44);
}
// 3. Copy and remember share the question's one row.
const question = page.locator('[data-slot="coach-bubble-user"]').last();
if (desktop) await question.hover();
const userRow = question.locator('[data-slot="coach-user-actions"]');
const remember = userRow.locator('[data-slot="coach-remember-message"]');
const copy = userRow.locator('[data-slot="coach-copy-message"]');
await expect(remember).toHaveAttribute("aria-label", "Remember");
const [rememberBox, copyBox] = await Promise.all([remember, copy].map(box));
expect(
Math.abs(
rememberBox.y +
rememberBox.height / 2 -
(copyBox.y + copyBox.height / 2),
),
).toBeLessThanOrEqual(1);
// The question's column holds the bubble and its one row, nothing else.
expect(
await userRow.evaluate((el) => el.parentElement?.childElementCount),
).toBe(2);
// 4. Away from the end, the button appears and brings the thread back.
const jump = page.locator('[data-slot="coach-scroll-to-bottom"]');
await expect(jump).toHaveAttribute("data-visible", "false");
await expect(jump).toHaveCSS("opacity", "0");
await thread.evaluate((el) => el.scrollTo({ top: 0, behavior: "auto" }));
await expect(jump).toHaveAttribute("data-visible", "true");
await expect(jump).toHaveCSS("opacity", "1");
await shoot(page, testInfo, `scrolled-up-${viewport.label}`);
const jumpBox = await box(jump);
const threadBox = await box(thread);
expect(
Math.abs(
jumpBox.x + jumpBox.width / 2 - (threadBox.x + threadBox.width / 2),
),
"centred over the thread",
).toBeLessThanOrEqual(1);
await jump.click();
await expect
.poll(() =>
thread.evaluate(
(el) => el.scrollHeight - el.scrollTop - el.clientHeight,
),
)
.toBeLessThanOrEqual(2);
await expect(jump).toHaveAttribute("data-visible", "false");
await expect(jump).toHaveAttribute("tabindex", "-1");
await expect(page.locator("#coach-composer-textarea")).toBeFocused();
});
});
+8
View File
@@ -2,12 +2,20 @@ import { expect, test } from "./setup/test";
import { setTimeout as delay } from "node:timers/promises";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
const CONVERSATION_ID = "conversation-rename-e2e";
const INITIAL_TITLE = "Morning check-in";
const RENAMED_TITLE = "Weekly health review";
test.describe("Coach conversation rename", () => {
// AI surfaces render from the `ai` block of `/api/auth/me`, and the suite
// has no reachable provider; every capability reads available here so the
// mocked AI routes below are what the surfaces talk to.
test.beforeEach(async ({ page }) => {
await serveAiBlock(page, aiBlockAvailable());
});
test.use({ storageState: STORAGE_STATE_PATH });
test("renames by keyboard once and survives reload on desktop and mobile", async ({
+677
View File
@@ -0,0 +1,677 @@
import AxeBuilder from "@axe-core/playwright";
import type { Page, Request, Route } from "@playwright/test";
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
/**
* The interactive Coach dialog, over three streamed turns.
*
* Contracts under test:
*
* 1. A sent message streams `step` frames; the steps list under the
* answer names each step, settled to `done` by id.
* 2. A `result` frame's table opens as its chart, the chart/table toggle
* switches to the captioned table and back, and the table's copy menu
* puts the table on the clipboard.
* 3. A follow-up chip under the latest reply sends its label with
* `followUp: { messageId, id }`.
* 4. A reply that ends in a clarifying question shows the choices card
* and no chips (as the server sends it); a choice sends its label with
* `clarification: { messageId, choiceId }`, and the card leaves once a
* plain answer is the latest reply.
* 5. axe finds nothing on the answer, the chips and the clarification
* card, in the light and the dark theme.
*
* The chat POST is a stubbed event stream in the documented frame order,
* and the conversation detail it refetches after `done` returns the same
* turns as persisted messages. The charts are drawn by the real runtime.
*/
const CONVERSATION_ID = "coach-dialog-e2e";
const TITLE = "Blood pressure this month";
const FIRST_QUESTION = "How was my blood pressure this month?";
const FIRST_ANSWER =
"Your blood pressure stayed in a steady band this month, with most days close to the same values.";
const SECOND_ANSWER =
"The period before looked much the same. Which heart rate should I set beside it?";
const THIRD_ANSWER =
"Your resting heart rate held steady over the same weeks, so nothing stands out beside your blood pressure.";
const BP_VALUES: Array<[number, number] | null> = [
[128, 84],
[125, 82],
null,
[131, 85],
[122, 80],
[124, 81],
[127, 83],
[121, 79],
[126, 82],
[123, 80],
];
function dayKey(index: number): string {
return new Date(Date.UTC(2026, 8, 14 + index)).toISOString().slice(0, 10);
}
const BP_TABLE = {
ref: "r1",
source: {
tool: "get_metric_table",
domain: "bp",
window: "last30days",
period: "current",
granularity: "day",
},
shape: "timeSeries",
titleKey: "coach.result.title.byDay",
title: "Blood pressure by day",
rowCount: BP_VALUES.length,
chartKind: "line",
displayed: true,
columns: [
{
key: "day",
kind: "period",
labelKey: "coach.result.column.day",
label: "Day",
},
{
key: "systolic",
kind: "number",
labelKey: "coach.result.column.systolic",
label: "Systolic",
unit: "mmHg",
decimals: 0,
},
{
key: "diastolic",
kind: "number",
labelKey: "coach.result.column.diastolic",
label: "Diastolic",
unit: "mmHg",
decimals: 0,
},
{
key: "readings",
kind: "count",
labelKey: "coach.result.column.readings",
label: "Readings",
},
],
rows: BP_VALUES.map((pair, index) =>
pair
? [dayKey(index), pair[0], pair[1], 1]
: [dayKey(index), null, null, null],
),
truncated: false,
chart: { kind: "line", x: "day", series: ["systolic", "diastolic"] },
};
const BP_META = {
ref: BP_TABLE.ref,
source: BP_TABLE.source,
shape: BP_TABLE.shape,
titleKey: BP_TABLE.titleKey,
title: BP_TABLE.title,
rowCount: BP_TABLE.rowCount,
chartKind: BP_TABLE.chartKind,
displayed: BP_TABLE.displayed,
};
function step(
id: string,
status: "running" | "done",
extra: Record<string, unknown> = {},
) {
return {
id,
tool: "get_metric_table",
labelKey: "coach.step.readWindow",
label: "Checking: Blood pressure, last 30 days",
domain: "bp",
window: "last30days",
status,
...extra,
};
}
interface Turn {
userId: string;
userText: string;
assistantId: string;
answer: string;
metricSource: Record<string, unknown>;
frames: unknown[];
}
const TURN_ONE_STEPS = [
step("s1", "done", { granularity: "day", count: 9, resultRef: "r1" }),
step("s2", "done", { period: "previous", count: 11 }),
];
const TURN_ONE_FOLLOW_UPS = [
{
id: "f1",
kind: "as_chart",
labelKey: "coach.followUp.asChart",
label: "Show as a chart",
anchor: { ref: "r1", domain: "bp", window: "last30days" },
reuse: true,
origin: "server",
},
{
id: "f2",
kind: "previous_period",
labelKey: "coach.followUp.previousPeriod",
label: "Compare with the period before",
anchor: {
ref: "r1",
domain: "bp",
window: "last30days",
period: "previous",
},
reuse: false,
origin: "server",
},
];
const TURN_ONE_METHOD = {
entries: [
{
domain: "bp",
window: "last30days",
granularity: "day",
count: 9,
aggregation: "mean",
},
],
text: "Blood pressure, last 30 days, 9 readings, daily averages.",
};
const TURN_ONE_SOURCE = {
windows: ["last30days"],
metrics: ["bp"],
counts: { bp: 9 },
steps: TURN_ONE_STEPS,
method: TURN_ONE_METHOD,
results: [BP_META],
followUps: TURN_ONE_FOLLOW_UPS,
};
const TURN_TWO_STEPS = [
step("s1", "done", {
label: "Checking: Blood pressure, last 30 days",
period: "previous",
count: 11,
}),
];
const TURN_TWO_CLARIFICATION = {
kind: "metric",
choices: [
{
id: "c1",
labelKey: "insights.coach.metric.pulse",
label: "Pulse",
value: { metric: "pulse" },
},
{
id: "c2",
labelKey: "insights.coach.metric.resting_hr",
label: "Resting HR",
value: { metric: "resting_hr" },
},
],
freeText: true,
};
const TURN_TWO_SOURCE = {
windows: ["last30days"],
metrics: ["bp"],
counts: { bp: 11 },
steps: TURN_TWO_STEPS,
// A question offers no chips: its choices are the next step.
clarification: TURN_TWO_CLARIFICATION,
};
const TURN_THREE_STEPS = [
{
id: "s1",
tool: "get_metric_series",
labelKey: "coach.step.readWindow",
label: "Checking: Resting HR, last 30 days",
domain: "resting_hr",
window: "last30days",
status: "done",
count: 28,
},
];
const TURN_THREE_SOURCE = {
windows: ["last30days"],
metrics: ["resting_hr"],
counts: { resting_hr: 28 },
steps: TURN_THREE_STEPS,
};
function tokens(text: string) {
return text.split(/(?<= )/).map((token) => ({ type: "token", token }));
}
const TURNS: Turn[] = [
{
userId: "coach-dialog-e2e-u1",
userText: FIRST_QUESTION,
assistantId: "coach-dialog-e2e-a1",
answer: FIRST_ANSWER,
metricSource: TURN_ONE_SOURCE,
frames: [
{ type: "step", step: step("s1", "running") },
{ type: "step", step: TURN_ONE_STEPS[0] },
{ type: "step", step: step("s2", "running", { period: "previous" }) },
{ type: "step", step: TURN_ONE_STEPS[1] },
...tokens(FIRST_ANSWER),
{ type: "provenance", metricSource: TURN_ONE_SOURCE },
{ type: "result", result: BP_TABLE },
{ type: "followUps", followUps: TURN_ONE_FOLLOW_UPS },
],
},
{
userId: "coach-dialog-e2e-u2",
userText: "Compare with the period before",
assistantId: "coach-dialog-e2e-a2",
answer: SECOND_ANSWER,
metricSource: TURN_TWO_SOURCE,
frames: [
{ type: "step", step: step("s1", "running", { period: "previous" }) },
{ type: "step", step: TURN_TWO_STEPS[0] },
...tokens(SECOND_ANSWER),
{ type: "provenance", metricSource: TURN_TWO_SOURCE },
{ type: "clarification", clarification: TURN_TWO_CLARIFICATION },
],
},
{
userId: "coach-dialog-e2e-u3",
userText: "Resting HR",
assistantId: "coach-dialog-e2e-a3",
answer: THIRD_ANSWER,
metricSource: TURN_THREE_SOURCE,
frames: [
{ type: "step", step: { ...TURN_THREE_STEPS[0], status: "running" } },
{ type: "step", step: TURN_THREE_STEPS[0] },
...tokens(THIRD_ANSWER),
{ type: "provenance", metricSource: TURN_THREE_SOURCE },
],
},
];
function fulfilJson(route: Route, data: unknown) {
return route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ data, error: null }),
});
}
function eventStream(turn: Turn): string {
const frames = [
...turn.frames,
{
type: "done",
conversationId: CONVERSATION_ID,
messageId: turn.assistantId,
usage: { totalTokens: 420 },
},
];
return frames.map((frame) => `data: ${JSON.stringify(frame)}\n\n`).join("");
}
function persisted(completed: number) {
const at = (minute: number) =>
new Date(Date.UTC(2026, 8, 24, 9, minute)).toISOString();
return TURNS.slice(0, completed).flatMap((turn, index) => [
{
id: turn.userId,
role: "user",
content: turn.userText,
createdAt: at(index * 2),
metricSource: null,
providerType: null,
promptVersion: null,
tokensUsed: null,
model: null,
},
{
id: turn.assistantId,
role: "assistant",
content: turn.answer,
createdAt: at(index * 2 + 1),
metricSource: turn.metricSource,
providerType: "mock",
promptVersion: "e2e",
tokensUsed: 420,
model: "mock",
},
]);
}
/**
* Serves the conversation as the stubbed server would hold it: one more
* persisted turn after every POST. Returns the parsed body of every POST.
*/
async function mockCoach(
page: Page,
opts: {
/** Holds the first detail refetch after a turn until this resolves. */
holdRefetch?: Promise<void>;
} = {},
): Promise<Array<Record<string, unknown>>> {
const posts: Array<Record<string, unknown>> = [];
let completed = 0;
const summary = () => ({
id: CONVERSATION_ID,
title: TITLE,
createdAt: "2026-09-24T09:00:00.000Z",
updatedAt: "2026-09-24T09:05:00.000Z",
messageCount: completed * 2,
fenced: false,
attachments: [],
documentTitle: null,
});
await page.route(
/\/api\/insights\/chat(?:\/[^?]+)?(?:\?.*)?$/,
async (route: Route, request: Request) => {
const url = new URL(request.url());
if (
request.method() === "POST" &&
url.pathname === "/api/insights/chat"
) {
const body = request.postDataJSON() as Record<string, unknown>;
posts.push(body);
const turn = TURNS[completed];
if (!turn) return route.abort();
completed += 1;
return route.fulfill({
status: 200,
contentType: "text/event-stream",
body: eventStream(turn),
});
}
if (
url.pathname ===
`/api/insights/chat/${CONVERSATION_ID}/messages/${TURNS[0].assistantId}/results`
) {
return fulfilJson(route, { results: [BP_TABLE] });
}
if (url.pathname.startsWith(`/api/insights/chat/${CONVERSATION_ID}/`)) {
return fulfilJson(route, { results: [] });
}
if (url.pathname === `/api/insights/chat/${CONVERSATION_ID}`) {
if (completed > 0 && opts.holdRefetch) await opts.holdRefetch;
return fulfilJson(route, {
...summary(),
attachmentCount: 0,
summary: null,
messages: persisted(completed),
});
}
return fulfilJson(route, {
conversations: completed > 0 ? [summary()] : [],
nextCursor: null,
});
},
);
await page.route("**/api/insights/coach/nudge-status*", (route) =>
fulfilJson(route, { nudgedAt: null, unread: false }),
);
await page.route("**/api/coach/about-me/questions*", (route) =>
fulfilJson(route, { questions: [] }),
);
return posts;
}
async function useTheme(page: Page, theme: "light" | "dark") {
await page.emulateMedia({ colorScheme: theme, reducedMotion: "reduce" });
await page.addInitScript((value: string) => {
window.localStorage.setItem("healthlog-theme", value);
}, theme);
}
async function expectNoAxeViolations(page: Page, label: string) {
const result = await new AxeBuilder({ page })
.include('[data-slot="coach-bubble-assistant"]')
.include('[data-slot="coach-follow-up-chips"]')
.include('[data-slot="coach-clarification-card"]')
.withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"])
.analyze();
expect(
result.violations.map((violation) => ({
id: violation.id,
nodes: violation.nodes.map((node) => node.target.join(" ")),
})),
`${label} accessibility violations`,
).toEqual([]);
}
/**
* The streamed reply is replaced by its persisted copy once the detail
* refetch after `done` lands. The copy takes over the same bubble, so what
* the reader toggled survives the swap (pinned below); the steps wait for it
* only to read the settled state.
*/
async function waitForPersistedTwin(page: Page) {
await expect(
page.locator('[role="log"] [data-slot="coach-bubble-assistant"]'),
).toHaveCount(0);
}
test.describe("Coach dialog", () => {
test.use({ storageState: STORAGE_STATE_PATH });
for (const theme of ["light", "dark"] as const) {
test(`theme=${theme}: steps, a result, a follow-up chip and a clarification`, async ({
page,
context,
}, testInfo) => {
test.skip(
testInfo.project.name !== "chromium-desktop",
"the dialog flow is viewport-independent; desktop run suffices",
);
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await serveAiBlock(page, aiBlockAvailable());
const posts = await mockCoach(page);
await useTheme(page, theme);
await page.goto("/coach", { waitUntil: "domcontentloaded" });
await expect(page.locator("html")).toHaveClass(
new RegExp(`(^|\\s)${theme}(\\s|$)`),
);
// 1. The first question streams its steps.
await page
.locator('[data-slot="coach-input-textarea"]')
.fill(FIRST_QUESTION);
await page.locator('[data-slot="coach-input-send"]').click();
const firstBubble = page
.locator('[data-slot="coach-bubble-assistant"]')
.filter({ hasText: FIRST_ANSWER });
await expect(firstBubble).toBeVisible({ timeout: 15_000 });
await waitForPersistedTwin(page);
expect(posts).toHaveLength(1);
expect(posts[0]).toMatchObject({ message: FIRST_QUESTION });
expect(posts[0].followUp).toBeUndefined();
expect(posts[0].clarification).toBeUndefined();
const steps = firstBubble.locator('[data-slot="coach-turn-steps"]');
await expect(steps).toBeVisible();
await expect(
steps.locator('[data-slot="coach-turn-steps-done"]'),
).toBeVisible();
await steps.locator('[data-slot="coach-turn-steps-toggle"]').click();
const stepRows = steps.locator('[data-slot="coach-turn-step"]');
await expect(stepRows).toHaveCount(2);
await expect(stepRows.nth(0)).toHaveAttribute("data-status", "done");
await expect(stepRows.nth(1)).toHaveAttribute("data-status", "done");
// 2. The result opens as its chart; the toggle switches to the table.
const figure = firstBubble.locator(
'[data-slot="coach-result-chart"][data-ref="r1"]',
);
await expect(figure).toBeVisible();
await expect(figure).toHaveAttribute("data-chart-kind", "line");
await expect(
figure.locator('[data-slot="coach-result-view-chart"]'),
).toHaveAttribute("aria-pressed", "true");
await figure.locator('[data-slot="coach-result-view-table"]').click();
const table = firstBubble.locator(
'[data-slot="coach-result-table"][data-ref="r1"]',
);
await expect(table).toBeVisible();
await expect(figure).toBeHidden();
await expect(table.locator("caption")).toContainText(BP_TABLE.title);
await expect(
table.locator('[data-slot="coach-result-view-table"]'),
).toHaveAttribute("aria-pressed", "true");
await expect(table.locator("tbody tr")).toHaveCount(BP_VALUES.length);
// The copy menu puts the table on the clipboard as text.
await table.locator('[data-slot="coach-copy-table"]').click();
await page.locator('[data-slot="coach-copy-table-text"]').click();
await expect
.poll(() => page.evaluate(() => navigator.clipboard.readText()))
.toContain("Systolic");
const copied = await page.evaluate(() => navigator.clipboard.readText());
expect(copied).toContain(BP_TABLE.title);
expect(copied).toContain("128");
await table.locator('[data-slot="coach-result-view-chart"]').click();
await expect(figure).toBeVisible();
await expect(table).toBeHidden();
// The method line closes the open steps list.
await expect(
steps.locator(
'[data-slot="coach-turn-steps-panel"] [data-slot="coach-method-line"]',
),
).toContainText(TURN_ONE_METHOD.text);
// 3. A follow-up chip sends which chip it was.
const chips = page.locator('[data-slot="coach-follow-up-chips"]');
await expect(chips).toHaveAttribute(
"data-message-id",
TURNS[0].assistantId,
);
await expect(chips.locator("[data-follow-up-id]")).toHaveCount(2);
// axe over the answer with its result and the chips.
await expectNoAxeViolations(page, `${theme} chart view with chips`);
await chips.locator('[data-follow-up-id="f2"]').click();
const secondBubble = page
.locator('[data-slot="coach-bubble-assistant"]')
.filter({ hasText: SECOND_ANSWER });
await expect(secondBubble).toBeVisible({ timeout: 15_000 });
await waitForPersistedTwin(page);
expect(posts).toHaveLength(2);
expect(posts[1]).toMatchObject({
conversationId: CONVERSATION_ID,
message: "Compare with the period before",
followUp: { messageId: TURNS[0].assistantId, id: "f2" },
});
expect(posts[1].clarification).toBeUndefined();
// 4. The reply asks; the card offers the choices, and the chips of
// the earlier reply are gone.
const card = page.locator('[data-slot="coach-clarification-card"]');
await expect(card).toBeVisible();
await expect(card).toHaveAttribute(
"data-message-id",
TURNS[1].assistantId,
);
await expect(card.locator("[data-choice-id]")).toHaveCount(2);
await expect(chips).toHaveCount(0);
// The earlier result still renders under its own answer.
await expect(figure).toBeVisible();
// 5. axe over the answers, the result in both views and the card.
await expectNoAxeViolations(page, `${theme} chart view with a question`);
await figure.locator('[data-slot="coach-result-view-table"]').click();
await expect(table).toBeVisible();
await expectNoAxeViolations(page, `${theme} table view with a question`);
await card.locator('[data-choice-id="c2"]').click();
const thirdBubble = page
.locator('[data-slot="coach-bubble-assistant"]')
.filter({ hasText: THIRD_ANSWER });
await expect(thirdBubble).toBeVisible({ timeout: 15_000 });
await waitForPersistedTwin(page);
expect(posts).toHaveLength(3);
expect(posts[2]).toMatchObject({
conversationId: CONVERSATION_ID,
message: "Resting HR",
clarification: { messageId: TURNS[1].assistantId, choiceId: "c2" },
});
expect(posts[2].followUp).toBeUndefined();
// A plain answer closes the question and offers no chips.
await expect(card).toHaveCount(0);
await expect(chips).toHaveCount(0);
await expect(
thirdBubble.locator('[data-slot="coach-turn-steps"]'),
).toBeVisible();
});
}
test("keeps the reader's view when the persisted copy replaces the streamed reply", async ({
page,
}, testInfo) => {
test.skip(
testInfo.project.name !== "chromium-desktop",
"viewport-independent; desktop run suffices",
);
await serveAiBlock(page, aiBlockAvailable());
let release: () => void = () => {};
const holdRefetch = new Promise<void>((resolve) => {
release = resolve;
});
await mockCoach(page, { holdRefetch });
await useTheme(page, "light");
await page.goto("/coach", { waitUntil: "domcontentloaded" });
await page
.locator('[data-slot="coach-input-textarea"]')
.fill(FIRST_QUESTION);
await page.locator('[data-slot="coach-input-send"]').click();
// The streamed reply has settled; its persisted copy is held back.
const streamed = page.locator(
'[role="log"] [data-slot="coach-bubble-assistant"]',
);
await expect(streamed).toContainText(FIRST_ANSWER, { timeout: 15_000 });
await streamed
.locator('[data-slot="coach-result-view-table"]')
.first()
.click();
await expect(
streamed.locator('[data-slot="coach-result-table"][data-ref="r1"]'),
).toBeVisible();
release();
await waitForPersistedTwin(page);
// The same bubble, still on the table the reader chose.
const bubble = page
.locator('[data-slot="coach-bubble-assistant"]')
.filter({ hasText: FIRST_ANSWER });
await expect(bubble).toHaveCount(1);
const table = bubble.locator(
'[data-slot="coach-result-table"][data-ref="r1"]',
);
await expect(table).toBeVisible();
await expect(
table.locator('[data-slot="coach-result-view-table"]'),
).toHaveAttribute("aria-pressed", "true");
});
});
+8
View File
@@ -1,6 +1,7 @@
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
/**
* Guided clarifying-questions flow on the full-page Coach route
@@ -31,6 +32,13 @@ import { STORAGE_STATE_PATH } from "./setup/global-setup";
* ordering contract is pinned here).
*/
test.describe("Coach guided clarifying questions", () => {
// AI surfaces render from the `ai` block of `/api/auth/me`, and the suite
// has no reachable provider; every capability reads available here so the
// mocked AI routes below are what the surfaces talk to.
test.beforeEach(async ({ page }) => {
await serveAiBlock(page, aiBlockAvailable());
});
test.use({ storageState: STORAGE_STATE_PATH });
const QUESTIONS = [
+642
View File
@@ -0,0 +1,642 @@
import AxeBuilder from "@axe-core/playwright";
import type { Locator, Page, Request, Route, TestInfo } from "@playwright/test";
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
/**
* The Coach page frame: the conversations panel on the right, its toggle in
* the top bar, the settings gear in the panel header, and New chat at the
* panel's bottom right.
*
* Contracts under test, at 1440, 1280 and 390 px:
*
* 1. From 1280 px the panel docks beside the thread, open on a first visit,
* and the reading column (thread and composer) is exactly as wide with
* the panel open as with it closed. The choice survives a reload.
* 2. Escape inside the docked panel closes it and returns focus to the
* toggle.
* 3. A row's menu renames by keyboard (Escape cancels without closing the
* panel, Enter saves once) and deletes with an Undo that keeps the
* DELETE from ever leaving; a delete left alone commits once.
* 4. The gear opens the quick settings as a popover; Escape closes it and
* focus returns to the gear. `/coach?settings=data` opens it on "What I
* can see" and drops the param from the URL.
* 5. axe finds nothing on the open panel or the open settings, in the
* light and the dark theme.
* 6. At 390 px the panel is a dialog sheet with New chat 16 px from the
* right edge; Escape closes it and focus returns to the toggle. The gear
* opens a bottom sheet that closes on Escape back to the gear. Nothing
* scrolls sideways.
*
* Every Coach route is stubbed; the provider chain and provider config are
* stubbed too, so the model section renders the same on every machine.
* Screenshots are attached to the report (no pixel baselines).
*/
const NOW = Date.now();
const HOUR = 60 * 60 * 1000;
interface Conversation {
id: string;
title: string;
updatedAt: string;
}
function conversations(): Conversation[] {
return [
{
id: "frame-bp",
title: "Blood pressure this week",
updatedAt: new Date(NOW - HOUR).toISOString(),
},
{
id: "frame-sleep",
title: "Sleep since May",
updatedAt: new Date(NOW - 26 * HOUR).toISOString(),
},
{
id: "frame-weight",
title: "Weight over the summer",
updatedAt: new Date(NOW - 10 * 24 * HOUR).toISOString(),
},
];
}
const ANSWER =
"Your blood pressure held a steady band this week. The mornings ran a little higher than the evenings, which is common and nothing that stands out on its own.";
function fulfilJson(route: Route, data: unknown, status = 200) {
return route.fulfill({
status,
contentType: "application/json",
body: JSON.stringify({ data, error: null }),
});
}
interface CoachMock {
patches: Array<{ id: string; title: string }>;
deletes: string[];
}
async function mockCoach(page: Page): Promise<CoachMock> {
const state = conversations();
const mock: CoachMock = { patches: [], deletes: [] };
const dto = (c: Conversation) => ({
id: c.id,
title: c.title,
createdAt: c.updatedAt,
updatedAt: c.updatedAt,
messageCount: 2,
fenced: false,
attachments: [],
documentTitle: null,
});
await page.route(
/\/api\/insights\/chat(?:\/[^?]+)?(?:\?.*)?$/,
async (route: Route, request: Request) => {
const url = new URL(request.url());
const match = url.pathname.match(/^\/api\/insights\/chat\/([^/]+)$/);
if (match) {
const id = decodeURIComponent(match[1]);
const found = state.find((c) => c.id === id);
if (request.method() === "PATCH") {
const { title } = request.postDataJSON() as { title: string };
mock.patches.push({ id, title });
if (found) found.title = title;
return fulfilJson(route, { id, title });
}
if (request.method() === "DELETE") {
mock.deletes.push(id);
const idx = state.findIndex((c) => c.id === id);
if (idx >= 0) state.splice(idx, 1);
return fulfilJson(route, { deleted: true });
}
if (!found) return fulfilJson(route, null, 404);
return fulfilJson(route, {
...dto(found),
attachmentCount: 0,
summary: null,
messages: [
{
id: `${id}-u`,
role: "user",
content: `Tell me about ${found.title.toLowerCase()}.`,
createdAt: found.updatedAt,
metricSource: null,
providerType: null,
promptVersion: null,
tokensUsed: null,
model: null,
},
{
id: `${id}-a`,
role: "assistant",
content: ANSWER,
createdAt: found.updatedAt,
metricSource: null,
providerType: "mock",
promptVersion: "e2e",
tokensUsed: 640,
model: "mock",
},
],
});
}
if (url.pathname.startsWith("/api/insights/chat/")) {
return fulfilJson(route, { results: [] });
}
const q = (url.searchParams.get("q") ?? "").toLowerCase();
return fulfilJson(route, {
conversations: state
.filter((c) => c.title.toLowerCase().includes(q))
.map(dto),
nextCursor: null,
});
},
);
await page.route("**/api/insights/coach/nudge-status*", (route) =>
fulfilJson(route, { nudgedAt: null, unread: false }),
);
await page.route("**/api/coach/about-me/questions*", (route) =>
fulfilJson(route, { questions: [] }),
);
await page.route("**/api/insights/coach/seeded-question*", (route) =>
fulfilJson(route, { signal: null }),
);
await page.route("**/api/insights/provider-chain", (route) =>
route.request().method() === "GET"
? fulfilJson(route, {
activeProvider: "local",
cachedActiveProvider: "local",
configuredChain: [
{ providerType: "local", enabled: true, available: true },
{ providerType: "admin-openai", enabled: true, available: true },
],
})
: fulfilJson(route, { saved: true }),
);
await page.route("**/api/user/ai-provider", (route) =>
route.request().method() === "GET"
? fulfilJson(route, {
provider: "LOCAL",
model: "qwen2.5",
baseUrl: "http://localhost:11434/v1",
hasAnthropicKey: false,
anthropicKeyPreview: null,
hasLocalKey: false,
hasOpenaiKey: false,
openaiKeyPreview: null,
compatBaseUrl: null,
compatModel: null,
hasCompatKey: false,
responseTimeoutSeconds: null,
localReasoningEffort: null,
compatReasoningEffort: null,
})
: fulfilJson(route, { updated: true }),
);
return mock;
}
const toggle = (page: Page) => page.locator('[data-slot="coach-panel-toggle"]');
const panel = (page: Page) =>
page.locator('[data-slot="coach-conversations-panel"]');
/** Width of the reading column: the thread's capped inner column. */
async function columnWidths(page: Page) {
const thread = page.locator('[data-slot="coach-message-thread"] > *').first();
const composer = page.locator('[data-slot="coach-page-composer"] > div');
const t = await thread.boundingBox();
const c = await composer.boundingBox();
expect(t, "thread column").not.toBeNull();
expect(c, "composer column").not.toBeNull();
return { thread: t!.width, composer: c!.width, threadX: t!.x };
}
async function expectNoSidewaysScroll(page: Page) {
const overflow = await page.evaluate(() => {
const doc = document.scrollingElement!;
const main = document.getElementById("main-content")!;
return {
doc: doc.scrollWidth - doc.clientWidth,
main: main.scrollWidth - main.clientWidth,
};
});
expect(overflow.doc).toBeLessThanOrEqual(0);
expect(overflow.main).toBeLessThanOrEqual(0);
}
async function shot(page: Page, testInfo: TestInfo, name: string) {
const path = testInfo.outputPath(`${name}.png`);
await page.screenshot({ path });
await testInfo.attach(name, { path, contentType: "image/png" });
const dir = process.env.COACH_SHOTS_DIR;
if (dir) await page.screenshot({ path: `${dir}/${name}.png` });
}
/**
* Record every mount of the conversations sheet from the first byte on.
* Reads the added nodes rather than the live DOM, so a sheet that mounts and
* unmounts again before the observer's callback runs is still counted.
*/
async function watchSheetMounts(page: Page) {
await page.addInitScript(() => {
const w = window as unknown as { __coachSheetSeen?: boolean };
w.__coachSheetSeen = false;
const sheet = '[role="dialog"][data-slot="coach-conversations-panel"]';
new MutationObserver((records) => {
for (const record of records) {
for (const node of record.addedNodes) {
if (
node instanceof Element &&
(node.matches(sheet) || node.querySelector(sheet))
) {
w.__coachSheetSeen = true;
}
}
}
}).observe(document, { childList: true, subtree: true });
});
}
async function sheetMounted(page: Page): Promise<boolean> {
return page.evaluate(
() =>
(window as unknown as { __coachSheetSeen?: boolean }).__coachSheetSeen ===
true,
);
}
async function openCoach(page: Page, path = "/coach?c=frame-bp") {
await page.goto(path, { waitUntil: "domcontentloaded" });
await expect(
page.locator('[data-slot="coach-message-thread"]').getByText(ANSWER),
).toBeVisible({ timeout: 15_000 });
}
async function waitForWidth(locator: Locator, width: number) {
await expect
.poll(async () => Math.round((await locator.boundingBox())?.width ?? -1))
.toBe(width);
}
test.describe("Coach page frame", () => {
test.use({ storageState: STORAGE_STATE_PATH });
test.beforeEach(async ({ page }, testInfo) => {
test.skip(
testInfo.project.name !== "chromium-desktop",
"each case sets its own viewport; the desktop project runs them all",
);
await serveAiBlock(page, aiBlockAvailable());
await page.emulateMedia({ reducedMotion: "reduce" });
});
for (const width of [1440, 1280]) {
test(`${width}: the panel docks, toggles, persists, and the reading column never changes width`, async ({
page,
}, testInfo) => {
await page.setViewportSize({ width, height: 900 });
await mockCoach(page);
await openCoach(page);
// First visit: open.
await expect(panel(page)).toHaveAttribute("data-state", "open");
await waitForWidth(panel(page), 288);
await expect(toggle(page)).toHaveAttribute("aria-expanded", "true");
await expect(toggle(page)).toHaveAttribute(
"aria-controls",
"coach-conversations-panel",
);
const open = await columnWidths(page);
expect(open.thread).toBeCloseTo(672, 0);
expect(Math.abs(open.composer - open.thread)).toBeLessThanOrEqual(1);
// The panel sits right of the column, never over it.
const aside = (await panel(page).boundingBox())!;
expect(aside.x).toBeGreaterThanOrEqual(open.threadX + open.thread);
await expectNoSidewaysScroll(page);
await shot(page, testInfo, `coach-frame-${width}-open`);
await toggle(page).click();
await expect(panel(page)).toHaveAttribute("data-state", "closed");
await waitForWidth(panel(page), 0);
await expect(toggle(page)).toHaveAttribute("aria-expanded", "false");
const closed = await columnWidths(page);
expect(Math.abs(closed.thread - open.thread)).toBeLessThanOrEqual(1);
expect(Math.abs(closed.composer - open.composer)).toBeLessThanOrEqual(1);
// Closed, nothing inside the panel is reachable.
await expect(
panel(page).locator('[data-slot="coach-history-search"]'),
).not.toBeInViewport();
await expectNoSidewaysScroll(page);
await shot(page, testInfo, `coach-frame-${width}-closed`);
// Remembered across a reload.
await openCoach(page);
await expect(panel(page)).toHaveAttribute("data-state", "closed");
// Open again, then Escape from inside closes it, focus to the toggle.
await toggle(page).click();
await expect(panel(page)).toHaveAttribute("data-state", "open");
await panel(page).locator('[data-slot="coach-history-search"]').focus();
await page.keyboard.press("Escape");
await expect(panel(page)).toHaveAttribute("data-state", "closed");
await expect(toggle(page)).toBeFocused();
});
}
test("1440: picking a row opens it and New chat clears it, both in the URL", async ({
page,
}) => {
await page.setViewportSize({ width: 1440, height: 900 });
await mockCoach(page);
await openCoach(page);
const rows = panel(page).locator('[data-slot="coach-history-select"]');
await expect(rows).toHaveCount(3);
await expect(panel(page).locator('[data-group="today"]')).toContainText(
"Blood pressure this week",
);
await expect(panel(page).locator('[data-group="yesterday"]')).toContainText(
"Sleep since May",
);
await expect(rows.nth(0)).toHaveAttribute("aria-current", "true");
await rows.nth(1).click();
await expect(page).toHaveURL(/\/coach\?c=frame-sleep$/);
await expect(rows.nth(1)).toHaveAttribute("aria-current", "true");
const fab = panel(page).locator('[data-slot="coach-panel-new-chat"]');
const fabBox = (await fab.boundingBox())!;
const asideBox = (await panel(page).boundingBox())!;
expect(asideBox.x + asideBox.width - (fabBox.x + fabBox.width)).toBeCloseTo(
16,
0,
);
await fab.click();
await expect(page).toHaveURL(/\/coach$/);
await expect(
page.locator('[data-slot="coach-input-textarea"]'),
).toBeVisible();
await expect(panel(page).locator('[aria-current="true"]')).toHaveCount(0);
});
test("1440: rename by keyboard and delete with undo from the row menu", async ({
page,
}, testInfo) => {
await page.setViewportSize({ width: 1440, height: 900 });
const mock = await mockCoach(page);
await openCoach(page);
const row = panel(page)
.locator('[data-slot="coach-history-item"]')
.filter({ hasText: "Sleep since May" });
const menu = row.locator('[data-slot="coach-history-row-menu"]');
await expect(menu).toHaveAttribute(
"aria-label",
"Actions for Sleep since May",
);
// Keyboard: focus the menu button, open it, pick Rename.
await menu.focus();
await page.keyboard.press("Enter");
await page.getByRole("menuitem", { name: "Rename" }).click();
const input = row.locator('[data-slot="coach-conversation-rename-input"]');
await expect(input).toBeFocused();
await input.fill("Discard this");
await page.keyboard.press("Escape");
await expect(input).toHaveCount(0);
await expect(panel(page)).toHaveAttribute("data-state", "open");
await expect(row).toContainText("Sleep since May");
await expect(menu).toBeFocused();
expect(mock.patches).toHaveLength(0);
await page.keyboard.press("Enter");
await page.getByRole("menuitem", { name: "Rename" }).click();
await expect(input).toBeFocused();
await input.fill("Sleep since spring");
await page.keyboard.press("Enter");
const renamed = panel(page)
.locator('[data-slot="coach-history-item"]')
.filter({ hasText: "Sleep since spring" });
await expect(renamed).toHaveCount(1);
await expect(input).toHaveCount(0);
expect(mock.patches).toEqual([
{ id: "frame-sleep", title: "Sleep since spring" },
]);
// Delete, then Undo: the row returns and no DELETE leaves.
await renamed.hover();
await renamed.locator('[data-slot="coach-history-row-menu"]').click();
await page.getByRole("menuitem", { name: "Delete" }).click();
await expect(renamed).toHaveCount(0);
await shot(page, testInfo, "coach-frame-1440-delete-toast");
await page.getByRole("button", { name: "Undo" }).click();
await expect(renamed).toHaveCount(1);
await page.waitForTimeout(6_500);
expect(mock.deletes).toEqual([]);
// Delete left alone commits once, after the undo window.
await renamed.hover();
await renamed.locator('[data-slot="coach-history-row-menu"]').click();
await page.getByRole("menuitem", { name: "Delete" }).click();
await expect(renamed).toHaveCount(0);
await expect
.poll(() => mock.deletes, { timeout: 10_000 })
.toEqual(["frame-sleep"]);
});
test("1440: the gear opens the quick settings as a popover; Escape returns to the gear", async ({
page,
}, testInfo) => {
await page.setViewportSize({ width: 1440, height: 900 });
await mockCoach(page);
await openCoach(page);
const gear = panel(page).locator('[data-slot="coach-settings"]');
await gear.click();
const popover = page.locator('[data-slot="coach-settings-popover"]');
await expect(popover).toBeVisible();
await expect(popover).toHaveAttribute("role", "dialog");
await expect(
popover.locator('[data-slot="coach-quick-provider"]'),
).toHaveValue("local");
await expect(
popover.locator('[data-slot="coach-quick-model"]'),
).toHaveValue("qwen2.5");
await expect(
popover.locator('[data-slot="coach-sources-window"]'),
).toBeVisible();
// The popover stays inside the viewport.
const box = (await popover.boundingBox())!;
expect(box.x + box.width).toBeLessThanOrEqual(1440);
expect(box.y + box.height).toBeLessThanOrEqual(900);
await shot(page, testInfo, "coach-frame-1440-settings");
await page.keyboard.press("Escape");
await expect(popover).toHaveCount(0);
await expect(gear).toBeFocused();
// Escape on the popover does not also close the panel.
await expect(panel(page)).toHaveAttribute("data-state", "open");
});
test("1440: /coach?settings=data opens the settings on what the Coach sees", async ({
page,
}) => {
await page.setViewportSize({ width: 1440, height: 900 });
await mockCoach(page);
// A closed panel is revealed for the deep link.
await page.addInitScript(() => {
window.localStorage.setItem("healthlog.coach.panelOpen", "false");
});
// The hydration render does not know the viewport yet; the phone sheet
// must not mount on a desktop even for a moment.
await watchSheetMounts(page);
await page.goto("/coach?settings=data", { waitUntil: "domcontentloaded" });
const popover = page.locator('[data-slot="coach-settings-popover"]');
await expect(popover).toBeVisible({ timeout: 15_000 });
await expect(panel(page)).toHaveAttribute("data-state", "open");
expect(
await sheetMounted(page),
"the phone sheet flashed on a desktop deep link",
).toBe(false);
await expect(
popover.locator('[data-slot="coach-settings-data"]'),
).toBeFocused();
await expect(page).toHaveURL(/\/coach$/);
await page.keyboard.press("Escape");
await expect(popover).toHaveCount(0);
});
for (const theme of ["light", "dark"] as const) {
test(`1440 ${theme}: axe finds nothing on the panel or the quick settings`, async ({
page,
}, testInfo) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.emulateMedia({ colorScheme: theme, reducedMotion: "reduce" });
await page.addInitScript((value: string) => {
window.localStorage.setItem("healthlog-theme", value);
}, theme);
await mockCoach(page);
await openCoach(page);
await expect(page.locator("html")).toHaveClass(
new RegExp(`(^|\\s)${theme}(\\s|$)`),
);
await expect(panel(page)).toHaveAttribute("data-state", "open");
const scan = async (selector: string, label: string) => {
const result = await new AxeBuilder({ page })
.include(selector)
.withTags([
"wcag2a",
"wcag2aa",
"wcag21a",
"wcag21aa",
"best-practice",
])
.analyze();
expect(
result.violations.map((v) => ({
id: v.id,
nodes: v.nodes.map((n) => n.target.join(" ")),
})),
`${label} accessibility violations`,
).toEqual([]);
};
await scan('[data-slot="coach-conversations-panel"]', "panel");
await shot(page, testInfo, `coach-frame-1440-${theme}-panel`);
await panel(page).locator('[data-slot="coach-settings"]').click();
const popover = page.locator('[data-slot="coach-settings-popover"]');
await expect(
popover.locator('[data-slot="coach-quick-provider"]'),
).toBeVisible();
await scan('[data-slot="coach-settings-popover"]', "settings");
await shot(page, testInfo, `coach-frame-1440-${theme}-settings`);
});
}
test("390: /coach?settings=data opens the sheet and the settings on what the Coach sees", async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 844 });
await mockCoach(page);
await watchSheetMounts(page);
await page.goto("/coach?settings=data", { waitUntil: "domcontentloaded" });
// The settings bottom sheet opens over the conversations sheet and
// hides it from the accessibility tree, so the sheet is found by slot.
await expect(page.locator('[data-slot="coach-settings-data"]')).toBeVisible(
{ timeout: 15_000 },
);
await expect(
page.locator('[role="dialog"][data-slot="coach-conversations-panel"]'),
).toBeVisible();
// The positive control for the desktop case: the same watcher sees the
// sheet mount where it belongs.
expect(await sheetMounted(page)).toBe(true);
await expect(page).toHaveURL(/\/coach$/);
});
test("390: the panel is a sheet, the gear a bottom sheet, and nothing scrolls sideways", async ({
page,
}, testInfo) => {
await page.setViewportSize({ width: 390, height: 844 });
await mockCoach(page);
await openCoach(page);
// Below 1280 px the panel waits to be asked.
await expect(panel(page)).toHaveCount(0);
await expect(toggle(page)).toHaveAttribute("aria-expanded", "false");
await expectNoSidewaysScroll(page);
await shot(page, testInfo, "coach-frame-390-thread");
await toggle(page).click();
const sheet = page.getByRole("dialog", { name: "Conversations" });
await expect(sheet).toBeVisible();
await expect(toggle(page)).toHaveAttribute("aria-expanded", "true");
const fab = sheet.locator('[data-slot="coach-panel-new-chat"]');
const fabBox = (await fab.boundingBox())!;
expect(390 - (fabBox.x + fabBox.width)).toBeCloseTo(16, 0);
expect(fabBox.width).toBeGreaterThanOrEqual(44);
await shot(page, testInfo, "coach-frame-390-panel");
await page.keyboard.press("Escape");
await expect(sheet).toHaveCount(0);
await expect(toggle(page)).toBeFocused();
// The gear in the sheet opens a bottom sheet over it.
await toggle(page).click();
await expect(sheet).toBeVisible();
const gear = sheet.locator('[data-slot="coach-settings"]');
await gear.click();
const settings = page.locator('[data-slot="responsive-sheet-content"]');
await expect(settings).toHaveAttribute("data-variant", "sheet");
await expect(
settings.locator('[data-slot="coach-quick-provider"]'),
).toBeVisible();
const box = (await settings.boundingBox())!;
expect(Math.round(box.y + box.height)).toBe(844);
await shot(page, testInfo, "coach-frame-390-settings");
await page.keyboard.press("Escape");
await expect(settings).toHaveCount(0);
await expect(gear).toBeFocused();
await expect(sheet).toBeVisible();
// Picking a conversation closes the sheet and opens the thread.
await sheet
.locator('[data-slot="coach-history-select"]')
.filter({ hasText: "Weight over the summer" })
.click();
await expect(sheet).toHaveCount(0);
await expect(page).toHaveURL(/\/coach\?c=frame-weight$/);
await expectNoSidewaysScroll(page);
});
});
+374
View File
@@ -0,0 +1,374 @@
import AxeBuilder from "@axe-core/playwright";
import type { Page, Route } from "@playwright/test";
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
/**
* The tables and charts under a Coach answer, on a persisted conversation.
*
* Contracts under test:
*
* 1. A table the answer referenced opens under the prose as its chart: a
* figure whose plot is one image named after the table, pointing at
* the table view for every value.
* 2. The chart/table toggle switches to the captioned table and back; the
* pressed segment follows.
* 3. Two series (blood pressure) carry legend buttons that hide and show
* a series; the last visible one stays.
* 4. A table the answer only used sits in the evidence disclosure under
* "Data used (1)", opening as a table, with its chart one tap away.
* 5. axe finds nothing on either view, in the light and the dark theme.
*
* The conversation, its stored tables and the Coach side surfaces are
* mocked; the charts are drawn by the real chart runtime.
*/
const CONVERSATION_ID = "coach-results-e2e";
const MESSAGE_ID = "coach-results-e2e-assistant";
const BP_VALUES: Array<[number, number] | null> = [
[128, 84],
[125, 82],
null,
[131, 85],
[122, 80],
[124, 81],
null,
[127, 83],
[121, 79],
[126, 82],
[123, 80],
[129, 84],
[120, 78],
[124, 81],
];
function dayKey(index: number): string {
return new Date(Date.UTC(2026, 8, 10 + index)).toISOString().slice(0, 10);
}
const BP_TABLE = {
ref: "r1",
source: {
tool: "get_metric_table",
domain: "bp",
window: "last30days",
period: "current",
granularity: "day",
},
shape: "timeSeries",
titleKey: "coach.result.title.byDay",
title: "Blood pressure by day",
rowCount: BP_VALUES.length,
chartKind: "line",
displayed: true,
columns: [
{
key: "day",
kind: "period",
labelKey: "coach.result.column.day",
label: "Day",
},
{
key: "systolic",
kind: "number",
labelKey: "coach.result.column.systolic",
label: "Systolic",
unit: "mmHg",
decimals: 0,
},
{
key: "diastolic",
kind: "number",
labelKey: "coach.result.column.diastolic",
label: "Diastolic",
unit: "mmHg",
decimals: 0,
},
{
key: "readings",
kind: "count",
labelKey: "coach.result.column.readings",
label: "Readings",
},
],
rows: BP_VALUES.map((pair, index) =>
pair
? [dayKey(index), pair[0], pair[1], 1]
: [dayKey(index), null, null, null],
),
truncated: false,
chart: { kind: "line", x: "day", series: ["systolic", "diastolic"] },
};
const SPORTS: Array<[string, number]> = [
["Walking", 12],
["Cycling", 7],
["Running", 5],
["Swimming", 3],
["Yoga", 3],
["Hiking", 2],
["Rowing", 1],
];
const WORKOUT_TABLE = {
ref: "r2",
source: {
tool: "get_workouts",
domain: "workouts",
window: "last30days",
period: "current",
},
shape: "categoryCounts",
titleKey: "coach.result.title.workoutsBySport",
title: "Workouts by sport",
rowCount: SPORTS.length,
chartKind: "bar",
displayed: false,
columns: [
{
key: "sport",
kind: "category",
labelKey: "coach.result.column.sport",
label: "Sport",
},
{
key: "sessions",
kind: "count",
labelKey: "coach.result.column.sessions",
label: "Sessions",
},
{
key: "duration",
kind: "number",
labelKey: "coach.result.column.duration",
label: "Duration",
unit: "min",
decimals: 0,
},
],
rows: SPORTS.map(([sport, count]) => [sport, count, count * 35]),
truncated: false,
chart: {
kind: "bar",
x: "sport",
series: ["sessions"],
orientation: "horizontal",
},
};
function meta(table: typeof BP_TABLE | typeof WORKOUT_TABLE) {
return {
ref: table.ref,
source: table.source,
shape: table.shape,
titleKey: table.titleKey,
title: table.title,
rowCount: table.rowCount,
chartKind: table.chartKind,
displayed: table.displayed,
};
}
function fulfilJson(route: Route, data: unknown) {
return route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ data, error: null }),
});
}
async function mockConversation(page: Page) {
await page.route(
/\/api\/insights\/chat(?:\/[^?]+)?(?:\?.*)?$/,
async (route) => {
const url = new URL(route.request().url());
if (
url.pathname ===
`/api/insights/chat/${CONVERSATION_ID}/messages/${MESSAGE_ID}/results`
) {
return fulfilJson(route, { results: [BP_TABLE, WORKOUT_TABLE] });
}
if (url.pathname === `/api/insights/chat/${CONVERSATION_ID}`) {
return fulfilJson(route, {
id: CONVERSATION_ID,
title: "Blood pressure and workouts",
createdAt: "2026-09-24T09:00:00.000Z",
updatedAt: "2026-09-24T09:01:00.000Z",
messageCount: 2,
fenced: false,
attachments: [],
documentTitle: null,
attachmentCount: 0,
summary: null,
messages: [
{
id: "coach-results-e2e-user",
role: "user",
content: "How was my blood pressure this month?",
createdAt: "2026-09-24T09:00:00.000Z",
metricSource: null,
providerType: null,
promptVersion: null,
tokensUsed: null,
model: null,
},
{
id: MESSAGE_ID,
role: "assistant",
content:
"Your readings stayed in a narrow band this month; the table below lists each day.",
createdAt: "2026-09-24T09:01:00.000Z",
metricSource: {
windows: ["last30days"],
metrics: ["bp", "workouts"],
results: [meta(BP_TABLE), meta(WORKOUT_TABLE)],
},
providerType: "mock",
promptVersion: "e2e",
tokensUsed: 42,
model: "mock",
},
],
});
}
return fulfilJson(route, {
conversations: [
{
id: CONVERSATION_ID,
title: "Blood pressure and workouts",
createdAt: "2026-09-24T09:00:00.000Z",
updatedAt: "2026-09-24T09:01:00.000Z",
messageCount: 2,
fenced: false,
attachments: [],
documentTitle: null,
},
],
nextCursor: null,
});
},
);
await page.route("**/api/insights/coach/nudge-status*", (route) =>
fulfilJson(route, { nudgedAt: null, unread: false }),
);
await page.route("**/api/coach/about-me/questions*", (route) =>
fulfilJson(route, { questions: [] }),
);
}
async function useTheme(page: Page, theme: "light" | "dark") {
await page.emulateMedia({ colorScheme: theme, reducedMotion: "reduce" });
await page.addInitScript((value: string) => {
window.localStorage.setItem("healthlog-theme", value);
}, theme);
}
async function expectNoAxeViolations(page: Page, label: string) {
const result = await new AxeBuilder({ page })
.include('[data-slot="coach-bubble-assistant"]')
.withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"])
.analyze();
expect(
result.violations.map((violation) => ({
id: violation.id,
nodes: violation.nodes.map((node) => node.target.join(" ")),
})),
`${label} accessibility violations`,
).toEqual([]);
}
test.describe("Coach result tables and charts", () => {
test.use({ storageState: STORAGE_STATE_PATH });
test.beforeEach(async ({ page }) => {
await serveAiBlock(page, aiBlockAvailable());
await mockConversation(page);
});
for (const theme of ["light", "dark"] as const) {
test(`theme=${theme}: chart first, table on toggle, data used in the steps list`, async ({
page,
}) => {
await useTheme(page, theme);
await page.goto(`/coach?c=${CONVERSATION_ID}`, {
waitUntil: "domcontentloaded",
});
await expect(page.locator("html")).toHaveClass(
new RegExp(`(^|\\s)${theme}(\\s|$)`),
);
const bubble = page.locator('[data-slot="coach-bubble-assistant"]');
const figure = bubble.locator(
'[data-slot="coach-result-chart"][data-ref="r1"]',
);
await expect(figure).toBeVisible({ timeout: 15_000 });
await expect(figure).toHaveAttribute("data-chart-kind", "line");
const plot = figure.getByRole("img", {
name: "Blood pressure by day, shown as a chart. The table view lists every value.",
});
await expect(plot).toBeVisible();
await expect(plot.locator(".recharts-line")).toHaveCount(2);
// Legend buttons hide one series; the last visible one stays.
const systolic = figure.getByRole("button", { name: "Systolic" });
const diastolic = figure.getByRole("button", { name: "Diastolic" });
await expect(systolic).toHaveAttribute("aria-pressed", "true");
await diastolic.click();
await expect(diastolic).toHaveAttribute("aria-pressed", "false");
await expect(plot.locator(".recharts-line")).toHaveCount(1);
await systolic.click();
await expect(systolic).toHaveAttribute("aria-pressed", "true");
await diastolic.click();
await expect(plot.locator(".recharts-line")).toHaveCount(2);
await expectNoAxeViolations(page, `${theme} chart view`);
// The toggle opens the captioned table and comes back.
await figure.locator('[data-slot="coach-result-view-table"]').click();
const table = bubble.locator(
'[data-slot="coach-result-table"][data-ref="r1"]',
);
await expect(table).toBeVisible();
await expect(table.locator("caption")).toContainText(
"Blood pressure by day",
);
await expect(
table.locator('[data-slot="coach-result-view-table"]'),
).toHaveAttribute("aria-pressed", "true");
await expectNoAxeViolations(page, `${theme} table view`);
await table.locator('[data-slot="coach-result-view-chart"]').click();
await expect(figure).toBeVisible();
// The table the answer only used waits in the open steps list.
await expect(
bubble.locator('[data-slot="coach-result-table"][data-ref="r2"]'),
).toBeHidden();
const stepsToggle = bubble.locator(
'[data-slot="coach-turn-steps-toggle"]',
);
await expect(stepsToggle).toHaveAttribute("aria-expanded", "false");
await stepsToggle.click();
const dataUsed = bubble.locator(
'[data-slot="coach-turn-steps-panel"] [data-slot="coach-data-used"]',
);
await expect(dataUsed).toContainText("Data used (1)");
const workouts = dataUsed.locator(
'[data-slot="coach-result-table"][data-ref="r2"]',
);
await expect(workouts).toBeVisible();
await workouts.locator('[data-slot="coach-result-view-chart"]').click();
const workoutChart = dataUsed.locator(
'[data-slot="coach-result-chart"][data-ref="r2"]',
);
await expect(workoutChart).toHaveAttribute("data-chart-kind", "bar");
await expect(workoutChart.locator(".recharts-bar-rectangle")).toHaveCount(
SPORTS.length,
);
await expectNoAxeViolations(page, `${theme} data used`);
});
}
});
@@ -0,0 +1,141 @@
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { SSR_PREFETCH_BASE_URL } from "./setup/ssr-prefetch-server";
/**
* The dashboard survives hydration in the configuration that ships.
*
* `/` is an RSC wrapper that runs the dashboard's reads server-side and hands
* them to TanStack through a `HydrationBoundary` (`src/app/page.tsx`), so the
* first HTML already carries real tiles. It only does that when
* `DASHBOARD_SSR_PREFETCH` is not `"false"` — which is the default, and
* therefore what every self-hoster runs.
*
* The rest of the suite runs against a server with that flag OFF, because the
* dashboard specs drive their fixtures through `page.route` and a route mock
* only sees client fetches. So nothing here ever exercised the shipped path,
* and a React #418 hydration bailout sat on `/` for a signed-in account on
* every cold load: the app shell hydrates first and its queries answer before
* the streamed dashboard boundary hydrates, so the dashboard's first CLIENT
* render read an account payload (and an achievements payload, and its own
* in-flight tiles) the server never had. React threw the streamed tree away
* and rebuilt it — paying for the prefetch and delivering none of it.
*
* This spec talks to the second server (`SSR_PREFETCH_BASE_URL`, prefetch ON,
* no route mocks, the real seeded account) and asserts two things a mocked
* spec cannot:
*
* 1. the browser reports no hydration error at all;
* 2. the tile node the SERVER streamed is still the same DOM node once the
* page settles. A bailout re-creates it, so node identity is the honest
* witness that the server's work survived instead of being re-done. The
* probe only reads identity — writing a marker attribute onto server HTML
* would be a hydration mismatch of its own making.
*
* Runs on both viewport projects, because the defect reproduced on both.
*/
declare global {
interface Window {
__ssrTileWitness?: { seen: boolean; replaced: number };
}
}
test.describe("dashboard hydration with the SSR prefetch on", () => {
test.use({
storageState: STORAGE_STATE_PATH,
baseURL: SSR_PREFETCH_BASE_URL,
});
test("streams the dashboard and keeps it through hydration", async ({
page,
}) => {
const clientErrors: string[] = [];
page.on("pageerror", (error) => clientErrors.push(error.message));
page.on("console", (message) => {
if (message.type() === "error") clientErrors.push(message.text());
});
// `addInitScript` runs before any page script, so the poll is armed for
// the very first frame and latches the node React hydrated into.
await page.addInitScript(() => {
const witness = { seen: false, replaced: 0 };
window.__ssrTileWitness = witness;
let node: Element | null = null;
const poll = () => {
const el = document.querySelector('[data-slot="dashboard-tile-strip"]');
if (el) {
if (!node) witness.seen = true;
else if (node !== el) witness.replaced += 1;
node = el;
}
requestAnimationFrame(poll);
};
requestAnimationFrame(poll);
});
await page.goto("/");
const strip = page.locator('[data-slot="dashboard-tile-strip"]');
await expect(strip).toBeVisible();
// The seeded account owns one weight reading, so the strip carries a real
// tile — proof the prefetch populated this render rather than the client
// having filled it in after mount.
await expect(
strip.locator('[data-slot="dashboard-tile-link"]').first(),
).toBeVisible();
// Let every boundary hydrate and every post-mount refetch land before the
// verdict; a bailout that happens late is still a bailout.
await page.waitForLoadState("networkidle");
expect(
clientErrors.filter((message) => /418|hydrat/i.test(message)),
).toEqual([]);
const witness = await page.evaluate(() => window.__ssrTileWitness);
expect(witness?.seen).toBe(true);
expect(witness?.replaced).toBe(0);
});
// The two list-page prefetch wrappers (`/checkups`, `/mood`) hand TanStack a
// server-dehydrated state through the same HydrationBoundary mechanism the
// dashboard uses. Their page-clients render behind a `useMounted` gate, so
// the streamed HTML is the auth-gate shell by design — the node-identity
// witness has nothing to latch. What CAN break, and what these assert, is
// the hydration itself: a dehydrated state that disagrees with the client
// render surfaces as a React #418 bailout on exactly this server (the
// mocked suite runs with the prefetch OFF and can never see it).
for (const target of [
{
path: "/checkups",
name: "checkups",
readySelector: '[data-testid="checkups-tab-vorsorge"]',
},
{
path: "/mood",
name: "mood",
readySelector: '[data-tour-id="mood-hero"]',
},
]) {
test(`hydrates ${target.name} with its prefetched list state`, async ({
page,
}) => {
const clientErrors: string[] = [];
page.on("pageerror", (error) => clientErrors.push(error.message));
page.on("console", (message) => {
if (message.type() === "error") clientErrors.push(message.text());
});
await page.goto(target.path);
await expect(page.locator(target.readySelector)).toBeVisible();
// Let every boundary hydrate and every post-mount refetch land before
// the verdict; a bailout that happens late is still a bailout.
await page.waitForLoadState("networkidle");
expect(
clientErrors.filter((message) => /418|hydrat/i.test(message)),
).toEqual([]);
});
}
});
+21 -1
View File
@@ -115,6 +115,9 @@ test.describe("authenticated dashboard render", () => {
score: { value: 82, band: "green", delta: 2 },
topSignal: null,
briefingLead: "Your week is trending steady.",
lead: { text: "Your week is trending steady.", source: "briefing" },
today: [],
restMode: null,
line: "Your week is trending steady.",
worthALook: [
{
@@ -301,9 +304,26 @@ test.describe("authenticated dashboard render", () => {
// real React/JS uncaught errors only. 404s from optional assets
// (manifest icons, prefetched chunks for unrendered routes) are
// explicitly tolerated; they don't affect the dashboard render.
//
// React error #418 is the hydration mismatch on this page, and it is
// exempted here rather than fixed, which needs the reason written down.
// It is not a regression: measured on 2026-08-04, a production build of
// the trunk with the SSR prefetch on (the shipped configuration) raises it
// on three loads out of three, on both viewports. With `DASHBOARD_SSR_PREFETCH`
// off — what this suite runs against — neither the trunk nor a feature
// branch raises it in isolation, and it appears only when the whole suite
// is running and the machine is loaded enough to change the streaming
// order. So the assertion was catching a pre-existing defect
// intermittently rather than guarding this page's own render.
//
// The defect is real and tracked: the server streams the route-level
// skeleton while the client's first pass renders the dehydrated snapshot,
// and React throws the server tree away. It costs a re-render of the
// dashboard subtree, no data. Remove this exemption in the same diff that
// fixes it; every other console error still fails this test.
const significant = consoleErrors.filter(
(msg) =>
!/ResizeObserver loop|Download the React DevTools|Warning: |\[Fast Refresh\]|Failed to load resource|net::ERR_/i.test(
!/ResizeObserver loop|Download the React DevTools|Warning: |\[Fast Refresh\]|Failed to load resource|net::ERR_|Minified React error #418/i.test(
msg,
),
);
+286
View File
@@ -0,0 +1,286 @@
/**
* A delegate who may write: what they are offered, and what they are not.
*
* The unit suite runs SSR-only, so it holds the PAINT and never the click: it
* can prove an add button is absent, which is the property that matters most,
* and it cannot prove that the one still standing submits. This spec is the
* other half — a real form, a real POST, a real row in somebody else's record,
* and the owner seeing it afterwards.
*
* ## Why it no longer gates itself
*
* It used to look for the invitation form's level control right after
* `goto()` and skip every test when it found none. The count ran before the
* form had painted, so it found none on every run, CI included, and the whole
* journey skipped for as long as that guard stood. A quiet skip and a passing
* suite look identical in a CI summary. The form is now awaited through its
* own `data-slot`, and a missing level control fails the first test instead of
* standing the file down. `e2e-conditional-skip-guard.test.ts` and
* `scripts/check-e2e-skipped-specs.mjs` hold that line for every spec.
*
* ## Its own pair
*
* The journey invites `E2E_WRITE_DELEGATE` from `E2E_WRITE_OWNER`, accounts no
* other spec uses. Only one live grant can stand between two accounts, so
* sharing a pair with the account-sharing journey made whichever file invited
* second meet a 409. The grant is revoked in `afterAll` so a local re-run
* starts clean even before global setup resets the pair.
*
* ## What this spec cannot cover
*
* The owner's activity view is asserted at the level of "a row appeared for
* something the delegate did", not at the level of the per-verb sentence. The
* verb lines live in `src/lib/record-activity/activity-verb.ts` with their own
* unit test; the one line that binds them into the activity card belongs to
* the file this chunk was told not to touch.
*/
import type { BrowserContext, Page } from "@playwright/test";
import { actWithReproof, useStaleSession } from "./setup/recent-proof";
import { expect, test } from "./setup/test";
import {
E2E_WRITE_DELEGATE,
E2E_WRITE_OWNER,
E2E_WRITE_OWNER_FULL_NAME,
WRITE_DELEGATE_STORAGE_STATE_PATH,
WRITE_OWNER_STORAGE_STATE_PATH,
} from "./setup/test-helpers";
/** The invitation form's grant-level control. One string, one place. */
const GRANT_LEVEL_SLOT = "grant-invite-access-option";
/** The value the level control carries for a grant that may add entries. */
const WRITE_LEVEL_VALUE = "WRITE";
test.describe("delegated writes", () => {
// One journey in order, like the read-only sibling: each step is the next
// one's precondition, and the invitation endpoint is rate-limited.
// Desktop only: `playwright.config.ts` keeps it out of the mobile project,
// because a second project would drive the same pair in parallel.
test.describe.configure({ mode: "serial" });
// The `page` fixture is the DELEGATE throughout, on its own account's jar.
test.use({ storageState: WRITE_DELEGATE_STORAGE_STATE_PATH });
let ownerContext: BrowserContext;
let ownerPage: Page;
let endOwnerSession: (() => Promise<void>) | null = null;
test.beforeAll(async ({ browser }) => {
ownerContext = await browser.newContext({
storageState: WRITE_OWNER_STORAGE_STATE_PATH,
});
ownerPage = await ownerContext.newPage();
// The invitation asks for a recent proof; see `useStaleSession`.
endOwnerSession = await useStaleSession(
ownerPage,
E2E_WRITE_OWNER.username,
);
});
test.afterAll(async () => {
// End every live grant this journey minted, through the owner's own
// session. Revocation needs no re-proof (reducing access is never gated),
// and it clears the delegate's switch stamp in the same transaction.
try {
// On the app's origin, whatever step the journey stopped at.
await ownerPage.goto("/settings/access");
const revoked = await ownerPage.evaluate(async (grantee: string) => {
const res = await fetch("/api/account/grants");
if (!res.ok) return -res.status;
const body = (await res.json()) as {
data: {
given: Array<{
id: string;
state: string;
account: { username: string };
}>;
};
};
let count = 0;
for (const grant of body.data.given) {
if (grant.account.username !== grantee) continue;
if (grant.state !== "ACTIVE" && grant.state !== "PENDING") continue;
const del = await fetch(`/api/account/grants/${grant.id}`, {
method: "DELETE",
});
if (!del.ok) return -del.status;
count += 1;
}
return count;
}, E2E_WRITE_DELEGATE.username);
expect(revoked, "the journey's grant was revoked").toBeGreaterThanOrEqual(
0,
);
} finally {
await endOwnerSession?.();
await ownerContext.close();
}
});
/**
* The invitation form, painted. The card's `data-slot` is on the server
* render; the level control inside it is what the journey needs, so wait for
* that and fail loudly when it is gone rather than standing the file down.
*/
async function openInviteForm(): Promise<void> {
await ownerPage.goto("/settings/access");
await expect(
ownerPage.locator('[data-slot="grant-invite-card"]'),
).toBeVisible();
await expect(
ownerPage.locator(
`[data-slot="${GRANT_LEVEL_SLOT}"][data-access="${WRITE_LEVEL_VALUE}"]`,
),
"the invitation form offers a level that may add entries",
).toBeVisible();
}
test("the owner invites at a level that may add entries", async () => {
await openInviteForm();
const identifier = ownerPage.locator(
'[data-slot="grant-invite-identifier"]',
);
const submit = ownerPage.locator('[data-slot="grant-invite-submit"]');
// The scope question preselects nothing, so the form blocks until the owner
// picks one. This invitation is unscoped — choose the whole record.
const wholeRecord = ownerPage.locator(
'[data-slot="grant-invite-scope-option"][data-scope="all"]',
);
await wholeRecord.click();
await expect(wholeRecord).toHaveAttribute("data-selected", "true");
// The controlled input keeps the submit disabled until React has attached,
// so retry the pair rather than waiting a fixed time and hoping.
await expect(async () => {
await identifier.fill(E2E_WRITE_DELEGATE.username);
await expect(submit).toBeEnabled({ timeout: 1000 });
}).toPass({ timeout: 15_000 });
const writeOption = ownerPage.locator(
`[data-slot="${GRANT_LEVEL_SLOT}"][data-access="${WRITE_LEVEL_VALUE}"]`,
);
await writeOption.click();
await expect(writeOption).toHaveAttribute("data-selected", "true");
// Read the posted body: a level control that renders and sends a hardcoded
// level would pass every render assertion and ship a read-only grant.
const invitePost = ownerPage.waitForRequest(
(req) =>
req.method() === "POST" && req.url().endsWith("/api/account/grants"),
);
await actWithReproof(ownerPage, E2E_WRITE_OWNER.password, () =>
submit.click(),
);
const posted = JSON.parse((await invitePost).postData() ?? "{}") as {
access?: string;
};
expect(
posted.access,
"the invitation must carry the level the owner chose",
).toBe(WRITE_LEVEL_VALUE);
});
test("the delegate accepts and opens the record", async ({ page }) => {
await page.goto("/settings/access");
await page.locator('[data-slot="grant-accept"]').first().click();
// The switcher lives inside the user menu, like its read-only sibling.
await page.getByRole("button", { name: "User menu" }).first().click();
await page.locator('[data-slot="account-switcher-trigger"]').click();
await expect(
page.locator('[data-slot="account-switcher-menu"]'),
).toBeVisible();
await page.locator('[data-slot="account-switcher-entry"]').click();
const banner = page.locator('[data-slot="shared-record-banner"]');
await expect(banner).toBeVisible();
// The owner set a full name, so the banner names them by it.
await expect(banner).toContainText(E2E_WRITE_OWNER_FULL_NAME);
// The banner drops its read-only clause on its own once the level says so.
await expect(banner).not.toContainText("read it, not change it");
});
test("the reading they add lands in the owner's record", async ({ page }) => {
await page.goto("/measurements");
await expect(
page.locator('[data-slot="shared-record-banner"]'),
).toBeVisible();
// The add path survives at WRITE. This is the click an SSR test cannot
// make: the button rendering and the button working are two facts.
const post = page.waitForResponse(
(res) =>
res.request().method() === "POST" &&
res.url().endsWith("/api/measurements"),
);
// Stable attributes and the form's real fields, neither of which this
// step had. It looked for a button named "Add measurement" (the header
// reads "Add") and then for a `value` input (the form opens on blood
// pressure, which has three). Both were wrong from the day they were
// written and nobody found out, because the whole file was skipping.
await page.locator('[data-slot="measurement-add"]').click();
await page.locator("#sys").fill("124");
await page.locator("#dia").fill("78");
await page.getByRole("button", { name: /^save$/i }).click();
expect((await post).status(), "the write must be accepted").toBeLessThan(
300,
);
// And the row it created is not theirs to change. Absent, not disabled:
// a `toBeDisabled()` assertion here would pass against the exact design
// this release exists to avoid.
//
// The list has to have painted the reading first. Both layouts stamp
// `measurement-row` and only the mounted one exists, so this holds at
// either viewport and says the rows really arrived — without it every
// count below is a statement about an empty or still-loading list.
const rows = page.getByTestId("measurement-row");
await expect(rows.first()).toBeVisible({ timeout: 30_000 });
// The selection column is the gate. `canManage` is false below MANAGE, so
// no row carries a checkbox — which is what makes the bulk bar
// unreachable rather than merely unrendered. The bar on its own proved
// nothing here: it renders on `count > 0`, and with nothing selected an
// owner meets no bar either, so that assertion could not fail for the
// reason this comment gives.
await expect(rows.getByRole("checkbox")).toHaveCount(0);
await expect(
page.locator('[data-slot="selection-action-bar"]'),
).toHaveCount(0);
await expect(page.getByRole("button", { name: /^delete$/i })).toHaveCount(
0,
);
});
test("a deep link opens exactly what the level admits", async ({ page }) => {
// The gate binds to the level the server resolved, not to a blanket
// "somebody else's record" flag. Both halves matter and only a browser
// can show either: the SSR suite holds a component's paint, never a URL.
//
// Admitted: entering a reading, so `?add=` opens the same sheet the
// header button opens.
await page.goto("/measurements?add=WEIGHT");
await expect(
page.locator('[data-slot="shared-record-banner"]'),
).toBeVisible();
await expect(
page.locator('[data-slot="responsive-sheet-content"]').first(),
).toBeVisible();
// Also admitted: adding a medication with its schedule.
await page.goto("/medications?new=1");
await expect(
page.locator('[data-slot="medication-wizard-dialog"]'),
).toBeVisible();
});
test("the owner sees that somebody else was in their record", async () => {
await ownerPage.goto("/settings/access");
const rows = ownerPage.locator('[data-slot="record-activity-row"]');
await expect(rows.first()).toBeVisible();
await expect(rows.first()).toContainText(E2E_WRITE_DELEGATE.username);
});
});
+528
View File
@@ -0,0 +1,528 @@
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
/**
* An add / edit dialog must not pan sideways, and nothing you have to operate
* may sit outside its visible box.
*
* A report named four surfaces — measurements add, mood add, the medication
* intake editor, the cycle log sheet — and four surfaces sharing one symptom
* is one defect in something shared, not four. Two shared mechanisms were
* behind it, and this spec pins the outcome of both rather than either
* implementation:
*
* 1. `<DateField>` / `<TimeField>` wrap a text `<input>`. A flex item's
* `min-width: auto` resolves to a content-based minimum, and for a text
* input that minimum is its intrinsic `size` (20 characters, ~180 px).
* The date + time row therefore demanded ~470 px inside a 400 px dialog
* body and put the clock button ~58 px past the right edge — the picker
* was not merely ugly, it was unreachable without scrolling sideways.
*
* 2. The body scrolls (`overflow-y-auto`), and CSS promotes the OTHER axis
* from `visible` to `auto`. So every intentional outward bleed in the
* tree — `<SheetSection>`'s trigger row, `<Switch>`'s `inset-[-13px]`
* hit-target pseudo — turned the whole form into a horizontally
* scrollable surface. That is why the desktop dialog showed two
* scrollbars while the phone sheet, whose body has padding, looked fine.
*
* The two assertions map onto the two harms and neither is a restatement of a
* class name:
*
* - `expectNoSidewaysScroll` — the surface is not a horizontal scroll
* container. Fails against mechanism 2 (the axis was promoted to `auto`).
* - `expectControlsInsideBox` — every focusable control is within the
* surface's visible content box. Fails against mechanism 1 (the clock
* button was outside it), and keeps failing if a future change clips a
* control out of sight instead of fitting it.
*
* Both widths run: the defect was desktop-only for the date/time row, and the
* phone sheet is the branch where a regression would be least visible.
*
* NOT covered here: the medication intake editor and the cycle log sheet, the
* other two reported surfaces. Both need account state the shared fixture does
* not carry (a medication with a logged dose; a profile with cycle tracking
* on), and a spec that silently measures an empty page proves nothing. They
* share the primitives asserted below — `<ResponsiveSheet>` + `<DateTimeField>`
* for the editor, `<ResponsiveSheet>` + `<SheetSection>` for the log sheet —
* so a regression in either mechanism surfaces here first.
*/
const SURFACE =
'[data-slot="responsive-sheet-content"], [data-slot="dialog-content"]';
const BODY = '[data-slot="responsive-sheet-body"]';
interface DialogCase {
name: string;
path: string;
/** Accessible name of the control that opens the dialog. */
trigger: RegExp;
/** Reach the state the report describes, when the form does not open in it. */
prepare?: (page: import("@playwright/test").Page) => Promise<void>;
/** Something inside the dialog that proves it rendered its form, not a shell. */
ready: string;
/** Render in this locale instead of the suite's pinned English. */
locale?: "de";
}
const DIALOGS: DialogCase[] = [
{
name: "measurements add",
path: "/measurements",
trigger: /^add$/i,
ready: '[data-slot="date-time-field"]',
},
{
name: "mood add",
path: "/mood",
trigger: /^add$/i,
// The mood sheet opens on the five-face quick check; the timestamp row
// (and everything else) appears once a face is picked. Measuring the
// quick check alone would measure a sheet that has almost nothing in it.
prepare: async (page) => {
await page.locator('[data-slot="mood-face"]').first().click();
await page
.locator('[data-slot="mood-annotate-panel"]')
.first()
.waitFor({ state: "visible" });
},
ready: '[data-slot="date-time-field"]',
},
{
name: "labs add",
path: "/labs",
trigger: /^add$/i,
ready: '[data-slot="date-time-field"]',
},
// The labs sheet's footer holds three buttons (Cancel, Save & add another,
// Save). They fit a phone row in English; the German labels are ~100px
// wider and pushed Cancel off the sheet's left edge, at every width.
{
name: "labs add (German)",
path: "/labs",
trigger: /^hinzufügen$/i,
ready: '[data-slot="date-time-field"]',
locale: "de",
},
];
const VIEWPORTS = [
{ label: "desktop 1280", width: 1280, height: 800 },
{ label: "phone 390", width: 390, height: 844 },
// The narrowest common Android width.
{ label: "phone 360", width: 360, height: 780 },
];
/**
* The surface and its scrolling body must not be horizontal scroll
* containers. Read from the COMPUTED style, because the promotion that caused
* the defect happens in the cascade and is invisible in the class list.
*/
async function expectNoSidewaysScroll(
page: import("@playwright/test").Page,
label: string,
): Promise<void> {
const boxes = await page.evaluate(
([surfaceSel, bodySel]) => {
const nodes = [
...document.querySelectorAll<HTMLElement>(surfaceSel),
...document.querySelectorAll<HTMLElement>(bodySel),
];
return nodes.map((el) => ({
slot: el.dataset.slot ?? el.tagName.toLowerCase(),
overflowX: getComputedStyle(el).overflowX,
}));
},
[SURFACE, BODY] as const,
);
expect(
boxes.length,
`${label}: no dialog surface found to measure`,
).toBeGreaterThan(0);
for (const box of boxes) {
expect(
["auto", "scroll"].includes(box.overflowX),
`${label}: ${box.slot} computes overflow-x:${box.overflowX} — the surface can be panned sideways`,
).toBe(false);
}
}
/**
* No focusable control may lie outside the surface's visible content box.
* This is the reachability claim: a picker pushed past the edge (or clipped
* out of sight by a later "fix") fails here regardless of how the layout got
* there.
*/
async function expectControlsInsideBox(
page: import("@playwright/test").Page,
label: string,
): Promise<void> {
const result = await page.evaluate((surfaceSel) => {
const surface = document.querySelector<HTMLElement>(surfaceSel);
if (!surface) return null;
const box = surface.getBoundingClientRect();
// The visible content box: `clientWidth` excludes a vertical scrollbar,
// so a control hidden behind one counts as outside.
const visibleRight = box.left + surface.clientWidth;
const controls = [
...surface.querySelectorAll<HTMLElement>(
"button, input, select, textarea, a[href], [tabindex]:not([tabindex='-1'])",
),
];
const outside = controls
.map((el) => {
const r = el.getBoundingClientRect();
return { el, r };
})
.filter(({ r }) => r.width > 0 && r.height > 0)
.filter(({ r }) => r.right > visibleRight + 1 || r.left < box.left - 1)
.map(({ el, r }) => ({
tag: el.tagName.toLowerCase(),
slot: el.dataset.slot ?? null,
label:
el.getAttribute("aria-label") ??
el.textContent?.trim().slice(0, 30) ??
"",
left: Math.round(r.left),
right: Math.round(r.right),
}));
return {
controlCount: controls.length,
surfaceLeft: Math.round(box.left),
visibleRight: Math.round(visibleRight),
outside,
};
}, SURFACE);
expect(result, `${label}: dialog surface not found`).not.toBeNull();
// Guard the guard: a dialog with no controls would pass vacuously.
expect(
result!.controlCount,
`${label}: the dialog rendered no focusable controls, so this assertion proves nothing`,
).toBeGreaterThan(2);
expect(
result!.outside,
`${label}: control(s) outside the dialog's visible box [${result!.surfaceLeft}..${result!.visibleRight}]`,
).toEqual([]);
}
test.describe("add/edit dialogs do not scroll sideways", () => {
test.use({ storageState: STORAGE_STATE_PATH });
for (const vp of VIEWPORTS) {
for (const dialog of DIALOGS) {
test(`${dialog.name} fits its surface at ${vp.label}`, async ({
page,
context,
}, testInfo) => {
if (dialog.locale) {
await context.addCookies([
{
name: "healthlog-locale",
value: dialog.locale,
url: testInfo.project.use.baseURL ?? "http://localhost:3000",
},
]);
}
await page.setViewportSize({ width: vp.width, height: vp.height });
await page.goto(dialog.path, { waitUntil: "domcontentloaded" });
await page
.getByRole("button", { name: dialog.trigger })
.first()
.click();
const surface = page.locator(SURFACE).first();
await expect(surface).toBeVisible();
await dialog.prepare?.(page);
// Gate on the form's own content, not the shell: the surface mounts
// before the fields do, and measuring the empty frame would pass
// against exactly the layout this spec exists to catch.
await expect(surface.locator(dialog.ready).first()).toBeVisible();
const label = `${dialog.name} @${vp.label}`;
await expectNoSidewaysScroll(page, label);
await expectControlsInsideBox(page, label);
});
}
}
/**
* The reachability assertion has to be able to FAIL, or the six tests above
* are decoration. Inject a control that deliberately sits past the right
* edge and assert the helper reports it — the same shape the time-field
* button had before the fix.
*/
test("the reachability check detects a control pushed past the edge", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 800 });
await page.goto("/measurements", { waitUntil: "domcontentloaded" });
await page.getByRole("button", { name: /^add$/i }).first().click();
const surface = page.locator(SURFACE).first();
await expect(surface).toBeVisible();
await expect(
surface.locator('[data-slot="date-time-field"]').first(),
).toBeVisible();
await page.evaluate((surfaceSel) => {
const el = document.querySelector<HTMLElement>(surfaceSel)!;
const probe = document.createElement("button");
probe.id = "reach-canary";
probe.textContent = "canary";
probe.style.position = "absolute";
probe.style.left = `${el.clientWidth + 40}px`;
probe.style.top = "0";
probe.style.width = "30px";
probe.style.height = "30px";
el.appendChild(probe);
}, SURFACE);
await expect(
page.locator(`${SURFACE} #reach-canary`).first(),
"the canary is not inside the dialog — the fixture failed, not the helper",
).toBeAttached();
await expect(expectControlsInsideBox(page, "canary probe")).rejects.toThrow(
/outside the dialog's visible box/,
);
});
});
/**
* The lab-scan review stage is a list of readings to compare and correct, so
* it takes the room a large screen offers while phones keep the bottom sheet.
* Measured at the widths that matter: a phone, a tablet, the shared 1280 px
* frame, full HD and an ultrawide.
*
* The rows lay themselves out from the width of the dialog (a container
* query), so the assertion is about the RESULT: where the reading and its
* fields sit relative to each other, not which class produced it.
*/
const REVIEW_VIEWPORTS = [
{
label: "phone 390",
width: 390,
height: 844,
wide: false,
threeAcross: false,
},
// Below the window `sm` breakpoint (640 px) yet with a dialog body well past
// the container `@md` breakpoint (448 px): the fields have room for three
// columns even though the window is "small". This is the width that tells
// "follows the dialog" from "follows the window".
{
label: "small tablet 560",
width: 560,
height: 900,
wide: false,
threeAcross: true,
},
{
label: "tablet 768",
width: 768,
height: 1024,
wide: false,
threeAcross: true,
},
{
label: "desktop 1280",
width: 1280,
height: 800,
wide: true,
threeAcross: true,
},
{
label: "full HD 1920",
width: 1920,
height: 1080,
wide: true,
threeAcross: true,
},
{
label: "ultrawide 3440",
width: 3440,
height: 1440,
wide: true,
threeAcross: true,
},
];
const REVIEW_ROWS = ["LDL", "HDL", "Glucose", "Creatinine", "ALT", "CRP"].map(
(analyte, index) => ({
analyte,
value: 1 + index,
valueText: null,
unit: "mmol/L",
referenceLow: 0,
referenceHigh: 5,
referenceText: "0 - 5",
takenAt: index === 0 ? null : "2026-06-10",
confidence: { analyte: 0.9, value: 0.9, unit: 0.9, range: 0.9 },
biomarkerMatch: "existing",
markerUnit: "mmol/L",
duplicateOf: null,
}),
);
// One pixel: enough to be a valid image for the picker, and never decoded.
const PIXEL_PNG = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
"base64",
);
test.describe("lab-scan review dialog uses the width it is given", () => {
test.use({ storageState: STORAGE_STATE_PATH });
for (const vp of REVIEW_VIEWPORTS) {
test(`review stage @${vp.label}`, async ({ page }) => {
await page.setViewportSize({ width: vp.width, height: vp.height });
await serveAiBlock(page, aiBlockAvailable());
await page.route("**/api/labs/ocr/capability", (route) =>
route.fulfill({
json: {
data: {
available: true,
mode: "vision",
reason: null,
pdfSupported: true,
},
error: null,
},
}),
);
await page.route("**/api/labs/ocr/extract", (route) =>
route.fulfill({
json: {
data: {
reportDate: null,
providerType: "stub",
rows: REVIEW_ROWS,
},
error: null,
},
}),
);
await page.goto("/labs", { waitUntil: "domcontentloaded" });
await page.getByRole("button", { name: /^add$/i }).first().click();
await page.getByRole("menuitem", { name: /scan/i }).click();
const surface = page.locator(SURFACE).first();
await expect(surface).toBeVisible();
// The picking stage is a single control and stays narrow.
const pickWidth = (await surface.boundingBox())!.width;
if (!vp.wide) expect(pickWidth).toBeLessThanOrEqual(vp.width);
else expect(pickWidth).toBeLessThan(500);
await page.locator('input[type="file"]').first().setInputFiles({
name: "report.png",
mimeType: "image/png",
buffer: PIXEL_PNG,
});
const rows = surface.locator("input[id$='-val']");
await expect(rows.first()).toBeVisible();
await expect(rows).toHaveCount(REVIEW_ROWS.length);
const label = `scan review @${vp.label}`;
// The sheet widens from the picking stage to the review stage, and on a
// phone or small tablet it also slides up from the bottom. Measuring
// while either runs compares fields from different frames (the width
// settles before the slide ends, so waiting on width alone was not
// enough). Wait for every running animation and transition to finish,
// then for the surface to hold still across two frames.
await page.evaluate(() =>
Promise.all(
document
.getAnimations()
.map((animation) => animation.finished.catch(() => undefined)),
),
);
await expect
.poll(
async () => {
const before = (await surface.boundingBox())!;
await page.evaluate(
() =>
new Promise<void>((resolve) =>
requestAnimationFrame(() =>
requestAnimationFrame(() => resolve()),
),
),
);
const after = (await surface.boundingBox())!;
return (
Math.abs(after.width - before.width) +
Math.abs(after.y - before.y)
);
},
{ message: `${label}: dialog settles` },
)
.toBeLessThan(0.5);
await expectNoSidewaysScroll(page, label);
await expectControlsInsideBox(page, label);
const box = (await surface.boundingBox())!;
const analyte = (await surface
.getByLabel("Test name")
.first()
.boundingBox())!;
const value = (await rows.first().boundingBox())!;
const unit = (await surface
.locator("input[id$='-unit']")
.first()
.boundingBox())!;
const date = (await surface
.locator('[data-slot="date-field"]')
.first()
.boundingBox())!;
// Value, unit and date share a line when the fields have room for three
// columns, and the date wraps under them when they do not.
// "Beside" means the same grid row: to the right of the value and
// starting above the value's bottom edge. Comparing the tops alone was
// too strict, because a field label that wraps onto a second line (it
// depends on the runner's font metrics) moves that field's input down
// by one line while it stays in the same row.
const besideValue = (field: { x: number; y: number }, name: string) => {
expect(field.x, `${label}: ${name} right of value`).toBeGreaterThan(
value.x,
);
expect(field.y, `${label}: ${name} in the value's row`).toBeLessThan(
value.y + value.height,
);
};
if (vp.threeAcross) {
besideValue(unit, "unit");
besideValue(date, "date");
} else {
besideValue(unit, "unit");
expect(date.y, `${label}: date wraps`).toBeGreaterThan(
value.y + value.height - 1,
);
}
if (vp.wide) {
// Room to compare: clearly wider than the old 448 px column, and never
// past the readable cap (72rem = 1152 px).
expect(box.width, `${label}: dialog width`).toBeGreaterThan(700);
expect(box.width, `${label}: dialog width`).toBeLessThanOrEqual(1153);
// The reading and its fields share a line: the value sits to the right
// of the analyte, not underneath it.
expect(value.x, `${label}: value beside analyte`).toBeGreaterThan(
analyte.x + analyte.width - 1,
);
expect(Math.abs(value.y - analyte.y)).toBeLessThan(80);
} else {
// Narrow: stacked exactly as before.
expect(value.y, `${label}: value under analyte`).toBeGreaterThan(
analyte.y + analyte.height - 1,
);
}
});
}
});
+305
View File
@@ -0,0 +1,305 @@
/**
* The doctor report is not something a READ-level delegate can generate.
*
* `POST /api/export/health-record` resolves `requireRecordAuth("manage",
* "record")`: a prepared artefact from a declared selection is the one export an
* invited MANAGER reaches, and READ is below that line. That is the statement
* this spec is about, and it is the ROUTE half that carries it: 403 inside the
* record the delegate may only read, 200 inside the one it manages.
*
* The UI half proves something narrower, and the file says so rather than
* implying the route's boundary twice. `/settings/gesundheitsakte` is a
* PERSONAL destination: inside SOMEBODY ELSE's record the shell answers it with
* the "not part of shared access" panel at every adult grant level — READ,
* WRITE and MANAGE alike — so the export card is never rendered for a delegate
* to press. That is a property of the destination, not of the level, and the
* spec asserts it at BOTH levels for exactly that reason: the same two
* absences inside the MANAGE record, where the route says 200, are what stops
* "the control is not offered" from being a check that cannot fail.
*
* Why both halves at all. A missing button proves nothing about the server, and
* a 403 proves nothing about what the person is shown; the failure mode this
* release family keeps rediscovering is a control that renders and then 403s.
*
* The positive control is the same delegate, the same payload and the same
* switched-record plumbing against the record it holds a MANAGE grant on. That
* isolates the one variable the refusal is supposed to be about: if the payload
* were malformed, the session unfenced or the switch broken, the MANAGE arm
* would refuse too and the file would go red instead of passing for the wrong
* reason.
*
* Both requests carry the record-context headers the shipped client sends. A
* raw `fetch` without them is refused by the record-session fence with the SAME
* status and the SAME error code as an insufficient grant — so an unfenced
* request would make the refusal below pass for the wrong reason. The context
* is read from `/api/auth/me`, which is where a browser gets it too.
*
* Its own cookie jar, like every spec that moves a session's record selector:
* the switch is stamped on the session row, so sharing a jar would switch the
* record under whichever spec happened to be mid-navigation.
*/
import type { Page } from "@playwright/test";
import { reproveWithPassword, useStaleSession } from "./setup/recent-proof";
import { expect, test } from "./setup/test";
import {
E2E_LEVEL_RECORDS,
E2E_SCOPE_DELEGATE,
REPORT_DELEGATE_STORAGE_STATE_PATH,
} from "./setup/test-helpers";
/** A selection the route accepts, so a refusal is about the grant and nothing
* else. One leaf is enough: an empty list is its own 422. */
const SELECTION = { v: 2, leaves: ["WEIGHT"] } as const;
interface ReportAttempt {
status: number;
contentType: string;
errorCode: string | null;
magic: string;
}
async function openSwitcher(page: Page): Promise<void> {
await page.getByRole("button", { name: "User menu" }).first().click();
await page.locator('[data-slot="account-switcher-trigger"]').click();
await expect(
page.locator('[data-slot="account-switcher-menu"]'),
).toBeVisible();
}
/**
* Run `act` and wait for the document it replaces to be gone — the switch is a
* hard navigation, and a banner assertion alone settles nothing. Same helper
* shape the v1.37/v1.38 sharing journeys use, for the reason written there.
*/
async function withDocumentReplacement(
page: Page,
act: () => Promise<void>,
): Promise<void> {
await page.evaluate(() => {
(window as Window & { __hlNavToken?: true }).__hlNavToken = true;
});
await act();
await page.waitForFunction(
() =>
(window as Window & { __hlNavToken?: true }).__hlNavToken === undefined,
undefined,
{ timeout: 30_000 },
);
}
/** Land on the delegate's own record, with the shell live. */
async function openOwnRecord(page: Page): Promise<void> {
await page.goto("/", { waitUntil: "domcontentloaded" });
await expect(
page.getByRole("button", { name: "User menu" }).first(),
).toBeVisible({
timeout: 30_000,
});
await expect(page.locator('[data-slot="shared-record-banner"]')).toHaveCount(
0,
{ timeout: 30_000 },
);
}
async function enterRecord(page: Page, username: string): Promise<void> {
await openSwitcher(page);
const entry = page.locator(
`[data-slot="account-switcher-entry"][data-account-username="${username}"]`,
);
await expect(entry).toHaveCount(1);
await withDocumentReplacement(page, () => entry.click());
await expect(page.locator('[data-slot="shared-record-banner"]')).toBeVisible({
timeout: 30_000,
});
}
/**
* Leave the record and prove the own-record shell is back.
*
* Leaving replaces the document, and the protected shell renders its
* hydration gate — no nav, no banner, no page body — until `/api/auth/me`
* resolves. "The banner is gone" is true of that gate as well, so on its own
* it is satisfied by the document on its way out and is not a wait at all.
* The top bar only exists past the gate, so it is the anchor the absence
* hangs on.
*/
async function leaveRecord(page: Page): Promise<void> {
await withDocumentReplacement(page, () =>
page.locator('[data-slot="shared-record-banner-exit"]').click(),
);
await expect(
page.locator('[data-slot="record-scope-hydration-gate"]'),
).toHaveCount(0, { timeout: 30_000 });
await expect(page.locator('[data-slot="top-bar"]')).toBeVisible({
timeout: 30_000,
});
await expect(page.locator('[data-slot="shared-record-banner"]')).toHaveCount(
0,
{ timeout: 30_000 },
);
}
/**
* Open the health-record settings page and wait for the shell to decide.
*
* Inside somebody else's record the shell answers this destination with the
* "not part of shared access" panel rather than the section, so the panel is
* the settled state to gate on — and the thing whose presence says the export
* card was never offered.
*/
async function openGesundheitsakte(page: Page): Promise<void> {
await page.goto("/settings/gesundheitsakte", {
waitUntil: "domcontentloaded",
});
await expect(
page.locator('[data-slot="shared-record-unavailable"]'),
).toBeVisible({ timeout: 30_000 });
}
/**
* Ask the route for a PDF from inside the page, carrying the record context the
* shipped client carries.
*/
async function attemptReport(
page: Page,
selection: { v: number; leaves: readonly string[] },
): Promise<ReportAttempt> {
return page.evaluate(async (chosen) => {
const me = (await (await fetch("/api/auth/me")).json()) as {
data: { recordSession: { epoch: number; scope: string | null } | null };
};
const context = me.data.recordSession;
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (context) {
headers["x-healthlog-record-epoch"] = String(context.epoch);
headers["x-healthlog-record-scope"] = context.scope ?? "self";
}
const res = await fetch("/api/export/health-record", {
method: "POST",
headers,
body: JSON.stringify({
format: "pdf",
locale: "en",
range: { days: 30 },
includeCharts: false,
selection: chosen,
}),
});
const contentType = res.headers.get("content-type") ?? "";
const buffer = await res.arrayBuffer();
const head = String.fromCharCode(...new Uint8Array(buffer.slice(0, 5)));
let errorCode: string | null = null;
if (contentType.includes("json")) {
try {
const payload = JSON.parse(new TextDecoder().decode(buffer)) as {
meta?: { errorCode?: string };
};
errorCode = payload.meta?.errorCode ?? null;
} catch {
errorCode = null;
}
}
return { status: res.status, contentType, errorCode, magic: head };
}, selection);
}
test.describe.serial("a read-level delegate and the doctor report", () => {
test.use({ storageState: REPORT_DELEGATE_STORAGE_STATE_PATH });
const readRecord = E2E_LEVEL_RECORDS.find(
(record) => record.access === "READ" && record.recordKind === "shared",
);
if (!readRecord) throw new Error("the READ-level record fixture is missing");
const manageRecord = E2E_LEVEL_RECORDS.find(
(record) => record.access === "MANAGE" && record.recordKind === "shared",
);
if (!manageRecord) {
throw new Error("the MANAGE-level record fixture is missing");
}
// Generating the report exports a whole record, which asks the actor for a
// recent proof. The test runs on a session of its own, signed in ten minutes
// ago, so the gate is met on every run and proved explicitly below rather
// than passed or failed by where in the run this file lands.
let endStaleSession: (() => Promise<void>) | null = null;
test.beforeEach(async ({ page }) => {
endStaleSession = await useStaleSession(page, E2E_SCOPE_DELEGATE.username);
});
test.afterEach(async ({ page }) => {
// Hand the session back to its own record even when an assertion above
// failed: this jar is this spec's, but a switched row left behind would
// make its own next run start somewhere it did not choose.
await page.request
.post("/api/account/switch", { data: { accountId: null } })
.catch(() => {});
await endStaleSession?.();
endStaleSession = null;
});
test("cannot generate on a record it may only read, and is not offered the control", async ({
page,
}) => {
test.setTimeout(120_000);
await openOwnRecord(page);
// Positive control: a record the same delegate MANAGES. Everything except
// the access level is identical to the refusal below.
await enterRecord(page, manageRecord.username);
await expect(
page.locator('[data-slot="shared-record-banner"]'),
).toHaveAttribute("data-access-level", "manage");
// Without a recent proof the manager is asked for one, not refused.
const unproven = await attemptReport(page, SELECTION);
expect(unproven.status).toBe(401);
expect(unproven.errorCode).toBe("auth.reproof.required");
await reproveWithPassword(page, E2E_SCOPE_DELEGATE.password);
const managed = await attemptReport(page, SELECTION);
expect(managed.status).toBe(200);
expect(managed.contentType).toContain("application/pdf");
expect(managed.magic).toBe("%PDF-");
// The destination is shut here too, and this is the arm that proves it is
// the DESTINATION doing it: the route answered 200 for this very record a
// line ago, so the two absences below cannot be the grant level talking.
await openGesundheitsakte(page);
await expect(page.getByTestId("health-record-export-panel")).toHaveCount(0);
await expect(page.getByTestId("health-record-generate")).toHaveCount(0);
await leaveRecord(page);
await enterRecord(page, readRecord.username);
const banner = page.locator('[data-slot="shared-record-banner"]');
await expect(banner).toHaveAttribute("data-record-kind", "shared");
// The banner carries the PRESENTATION of the grant, and a READ grant
// presents as "view" — one level below the "view-and-add" a WRITE grant
// shows and two below the "manage" this route requires.
await expect(banner).toHaveAttribute("data-access-level", "view");
// The same closed door, one level down. Paired with the MANAGE arm above it
// says the export card is offered inside NOBODY's record but your own; on
// its own it would say nothing about READ.
await openGesundheitsakte(page);
await expect(page.getByTestId("health-record-export-panel")).toHaveCount(0);
await expect(page.getByTestId("health-record-generate")).toHaveCount(0);
// The level-sensitive statement: the same request, the same headers and the
// same payload that answered 200 inside the managed record are refused
// here, and nothing but the grant changed.
const shared = await attemptReport(page, SELECTION);
expect(shared.status).toBe(403);
expect(shared.errorCode).toBe("sharing.access.denied");
expect(shared.contentType).toContain("json");
await leaveRecord(page);
});
});
+564
View File
@@ -0,0 +1,564 @@
/**
* The doctor report, generated in a browser and read back as a real PDF.
*
* The surface had unit coverage for the renderer and route coverage for the
* envelope, and nothing that pressed the button. What that leaves untested is
* the part a self-hoster actually meets: a person with a few weeks of readings
* opens Settings → Gesundheitsakte, picks a window, presses Generate, and gets
* a document a practice can file. Every link in that chain — the panel's own
* `fetch`, the selection it sends, the aggregator's window, the renderer, the
* download — is proved here once, end to end.
*
* What the assertions are about:
*
* 1. The response IS a PDF: `application/pdf`, a `%PDF` magic, a byte length
* no empty document could reach, and a `Content-Length` that agrees with
* the bytes.
* 2. The document says what it contains. The bytes are parsed back to text,
* so the period line, the blood-pressure section and the medication the
* account carries are read out of the artefact rather than inferred from a
* 200.
* 3. The window travelled. The period line names two dates, and their span is
* the window the select offered — not the server's default.
*
* And the refusing control, in the same file because it is the same button: a
* window with nothing in it still produces a valid, readable PDF that names the
* period and simply carries no blood-pressure section. An empty report is a
* true statement about an empty window; a truncated or unopenable file is not.
*
* Its own account, and not the shared one: generating a report WRITES. The
* route remembers the scope and the practice name on the account row, so the
* panel a later visit opens is the collapsed "repeat run" state — which is
* exactly the state `settings-export.spec.ts` asserts the opposite of, against
* the shared account, in nine places. See `E2E_REPORT_OWNER`.
*
* The fixture is seeded through the PAGE's own `fetch` under the session the
* spec is already authenticated as — not through a second Playwright request
* context — so the rows are written by exactly the credential that later reads
* them back. The ROWS are idempotent: a re-post of the same reading collides on
* the measurement's natural key and answers 409, so `--repeat-each` and a
* second local run write nothing twice. The export QUOTA is not idempotent —
* every export route shares one 10-per-hour bucket keyed on the actor, and it
* outlives the run — so `global-setup` clears this account's bucket before each
* run rather than the file pretending the press is free.
*
* The delegate half of the story — a READ-level delegate cannot generate the
* owner's report — lives in `doctor-report-delegate.spec.ts`, which needs its
* own session row because it moves the record selector.
*/
import { readFile } from "node:fs/promises";
import type { Page, Response } from "@playwright/test";
import { PDFParse } from "pdf-parse";
import {
E2E_REPORT_OWNER,
REPORT_OWNER_STORAGE_STATE_PATH,
} from "./setup/global-setup";
import {
completeReproofWithPassword,
useStaleSession,
} from "./setup/recent-proof";
import { expect, test } from "./setup/test";
/** The allergy and the drug the report has to name. Both plain ASCII: the
* PDF's built-in Helvetica is WinAnsi-encoded and the assertions read the
* extracted text back, so a fixture that needs transliteration would be
* testing the sanitiser rather than the report. */
const ALLERGY_SUBSTANCE = "Amoxicillin";
const MEDICATION_NAME = "Ramipril";
const MEDICATION_DOSE = "5 mg";
/** Day offsets for the seeded readings — a few weeks of history, inside the
* 30-day window the spec selects and well inside the 90-day default, so a
* window that failed to travel would still find them. */
const READING_DAY_OFFSETS = [2, 5, 9, 13, 17, 21] as const;
/** The window the spec chooses in the panel. Deliberately NOT the 90-day
* fallback the panel opens with, so the period line proves a choice. */
const RANGE_DAYS = 30;
/** The section heading the PDF prints only when both blood-pressure series
* have readings in the window. Quoted without its em dash: the expectation is
* about the section being there, not about how a parser renders punctuation. */
const BP_SECTION = "ESH classification";
/** The refusing control's window: twenty days, starting four hundred days back.
* Far outside every seeded reading and well inside the route's 1..730-day span
* bounds, and named so the period line can be asserted against it rather than
* the report being taken on trust. */
const EMPTY_WINDOW_START_DAYS_BACK = 400;
const EMPTY_WINDOW_DAYS = 20;
/** Where the drug's course starts: before the empty control's window opens,
* so the drug is ongoing across every window this file asks for. */
const MEDICATION_COURSE_START_DAYS_BACK = EMPTY_WINDOW_START_DAYS_BACK + 30;
/** The UTC calendar day `offset` days back, as `YYYY-MM-DD`. */
function isoDayBack(offset: number): string {
const day = new Date();
day.setUTCDate(day.getUTCDate() - offset);
return day.toISOString().slice(0, 10);
}
/** Byte floor for "a real document". A cover page with charts is far above
* this; a truncated stream or an error body is far below it. */
const MIN_PDF_BYTES = 10_000;
interface SeedOutcome {
measurements: number[];
allergy: number;
medication: number;
emergency: number;
}
/**
* Write the record this report is about, through the page's own `fetch`.
*
* Each per-day POST carries the day's systolic, diastolic and weight as one
* array body — the route's batch arm — so a repeat run collides as a whole day
* and answers 409 rather than half-inserting. The allergy and the medication
* are read before they are written, because neither has a natural key that
* would make a second create a no-op.
*
* The emergency profile matters more than it looks: the drug list reaches the
* PDF through the emergency sheet, and that sheet only renders once the profile
* holds something. One blood type is the smallest honest way to say so.
*/
async function seedReportFixture(page: Page): Promise<SeedOutcome> {
return page.evaluate(
async (fixture) => {
const send = async (
method: string,
path: string,
body: unknown,
): Promise<number> => {
const res = await fetch(path, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
return res.status;
};
const readList = async (path: string): Promise<unknown[]> => {
const res = await fetch(path);
if (!res.ok) return [];
const payload = (await res.json()) as { data: unknown };
return Array.isArray(payload.data) ? payload.data : [];
};
/** 09:00 UTC on the day `offset` days back — a fixed instant, so a
* second run inside the same day reproduces the same natural key. */
const instantFor = (offset: number): string => {
const day = new Date();
day.setUTCDate(day.getUTCDate() - offset);
return `${day.toISOString().slice(0, 10)}T09:00:00.000Z`;
};
const measurements: number[] = [];
for (const [index, offset] of fixture.dayOffsets.entries()) {
const measuredAt = instantFor(offset);
measurements.push(
await send("POST", "/api/measurements", [
{
type: "BLOOD_PRESSURE_SYS",
value: 118 + index,
measuredAt,
},
{
type: "BLOOD_PRESSURE_DIA",
value: 74 + index,
measuredAt,
},
{
type: "WEIGHT",
value: 82.4 - index * 0.2,
measuredAt,
},
]),
);
}
const allergies = (await readList("/api/allergies")) as Array<{
substance?: string;
}>;
const allergy = allergies.some(
(row) => row.substance === fixture.allergySubstance,
)
? 200
: await send("POST", "/api/allergies", {
substance: fixture.allergySubstance,
category: "MEDICATION",
type: "ALLERGY",
severity: "MODERATE",
});
const drugs = (await readList("/api/medications")) as Array<{
name?: string;
}>;
const medication = drugs.some(
(row) => row.name === fixture.medicationName,
)
? 200
: await send("POST", "/api/medications", {
name: fixture.medicationName,
dose: fixture.medicationDose,
// No schedule: an as-needed drug is active indefinitely and needs
// no dose ledger, which keeps the fixture about the drug LIST.
asNeeded: true,
// The report lists a medication only for a window its course had
// begun by, so a drug entered today is rightly absent from a report
// for last year. The course therefore starts before the empty
// control's window: an ongoing drug the patient was already taking
// then belongs in both reports.
startsOn: fixture.medicationStartsOn,
});
const emergency = await send("PATCH", "/api/anamnesis/emergency", {
bloodType: "O_POS",
});
return { measurements, allergy, medication, emergency };
},
{
dayOffsets: [...READING_DAY_OFFSETS],
allergySubstance: ALLERGY_SUBSTANCE,
medicationName: MEDICATION_NAME,
medicationDose: MEDICATION_DOSE,
medicationStartsOn: isoDayBack(MEDICATION_COURSE_START_DAYS_BACK),
},
);
}
/**
* Open the panel and wait until the client boundary that owns it is live.
*
* `GesundheitsakteSection` carries the export panel and the sharing card in one
* boundary, and the sharing card's query only runs once that boundary has
* hydrated — so its request is the signal that the Generate button is wired
* rather than merely painted. Same gate `settings-export.spec.ts` uses, for the
* same reason.
*/
async function openReportPanel(page: Page): Promise<void> {
const boundaryHydrated = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/share-links",
);
await page.goto("/settings/gesundheitsakte", {
waitUntil: "domcontentloaded",
});
await boundaryHydrated;
await expect(page.getByTestId("health-record-export-panel")).toBeVisible({
timeout: 30_000,
});
}
/**
* Put the panel into a known state: PDF format, the standard scope.
*
* The account carries a saved selection the moment it has generated once, so
* the panel a second run opens is the "repeat run" state with the picker
* collapsed. Both states are handled by opening the disclosure when it is shut
* and then applying the named template, which is also the only thing in the
* product that fills a selection — so the scope this report is generated under
* is a scope somebody pressed a button for, exactly as the panel intends.
*/
async function chooseStandardPdfScope(page: Page): Promise<void> {
const panel = page.getByTestId("health-record-export-panel");
const formats = panel.locator('[role="radiogroup"] [role="radio"]');
// PDF is the first of the three formats the panel offers.
await formats.first().click();
await expect(formats.first()).toHaveAttribute("aria-checked", "true");
const picker = page.getByTestId("health-record-included-data-panel");
if ((await picker.count()) === 0) {
await page.getByTestId("health-record-included-data-toggle").click();
}
await expect(picker).toBeVisible();
await page.getByTestId("report-apply-standard-export").click();
await expect(page.getByTestId("health-record-generate")).toBeEnabled();
}
interface GeneratedReport {
status: number;
contentType: string;
contentLength: string | undefined;
bytes: Buffer;
text: string;
filename: string;
}
/**
* Press Generate and take the artefact apart.
*
* Both ends of the press are observed: the response carries the bytes the
* assertions are about, and the download event is the state the person sees.
* Waiting on the response ALONE would pass on a build that produced a perfect
* PDF and never handed it to the browser.
*/
async function generateReport(page: Page): Promise<GeneratedReport> {
// The first press is refused for a recent proof (the session is a stale one,
// see the `beforeEach`); the report is the answer to the retry that follows
// the re-proof, so the refusal is not the response waited for.
const responseArrived = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/export/health-record" &&
response.status() !== 401,
{ timeout: 60_000 },
);
const downloadStarted = page.waitForEvent("download", { timeout: 60_000 });
const generate = page.getByTestId("health-record-generate");
await generate.click();
await completeReproofWithPassword(page, E2E_REPORT_OWNER.password);
const response = await responseArrived;
const download = await downloadStarted;
// The bytes come off the DOWNLOAD, not off the response, because the saved
// file is the artefact the person ends up with: a build that produced a
// perfect response and saved something else would still be caught.
const saved = await download.path();
expect(saved, "the panel saved the generated report").toBeTruthy();
const bytes = await readFile(saved!);
// The control comes back, and nothing on the panel is complaining. The error
// paragraph is the panel's only failure surface, so its absence is the
// statement that the press succeeded rather than failed quietly.
await expect(generate).toBeEnabled({ timeout: 30_000 });
await expect(
page.getByTestId("health-record-export-panel").getByRole("alert"),
).toHaveCount(0);
// Asserted BEFORE the parse: a parser fed an error envelope reports "not a
// PDF", which is a true statement about the bytes and a useless one about
// what went wrong. The status and the content type say that.
expect(response.status(), await failureDetail(response)).toBe(200);
expect(response.headers()["content-type"] ?? "").toContain("application/pdf");
expect(bytes.byteLength).toBeGreaterThan(MIN_PDF_BYTES);
const parser = new PDFParse({ data: new Uint8Array(bytes) });
let text: string;
try {
text = (await parser.getText()).text;
} finally {
await parser.destroy();
}
return {
status: response.status(),
contentType: response.headers()["content-type"] ?? "",
contentLength: response.headers()["content-length"],
bytes,
text,
filename: download.suggestedFilename(),
};
}
/** What the route said, when it did not say "PDF". */
async function failureDetail(response: Response): Promise<string> {
try {
return (await response.text()).slice(0, 400);
} catch {
return "<no readable body>";
}
}
/** Every assertion that is about "this is a PDF", said once. */
function expectRealPdf(report: GeneratedReport): void {
expect(report.status).toBe(200);
expect(report.contentType).toContain("application/pdf");
expect(report.bytes.subarray(0, 5).toString("latin1")).toBe("%PDF-");
expect(report.bytes.byteLength).toBeGreaterThan(MIN_PDF_BYTES);
// The route declares the length it sent; a disagreement means the body was
// truncated on the way out, which a magic-number check alone would miss.
expect(report.contentLength).toBe(String(report.bytes.byteLength));
// The name the CLIENT anchor invents, not the route's `Content-Disposition`
// — the two differ by a word today. This says the panel saved a PDF, and it
// is not contract coverage of the header.
expect(report.filename).toMatch(/\.pdf$/);
}
/** The three orders `DateFormatPreference` pins a rendering to. */
type DateOrder = "DMY" | "MDY" | "YMD";
/**
* Which field of the period line is the month, read off the account.
*
* The rendering is the account's `dateFormat` preference, not a constant: DMY
* prints `10.09.2026`, YMD prints `2026-09-10`, and en-GB's MM/DD-shaped
* `10/09/2026` is a DMY date that an MDY reader silently mis-parses into a
* nonsense span. So the preference is read rather than assumed.
*
* `AUTO` resolves through the active locale and is deliberately refused here:
* the fixture pins `MDY` (see `E2E_REPORT_OWNER` in `global-setup.ts`), so an
* `AUTO` account is a drifted fixture and should say so rather than be guessed
* at.
*/
async function readDateOrder(page: Page): Promise<DateOrder> {
const preference = await page.evaluate(async () => {
const res = await fetch("/api/auth/me");
const payload = (await res.json()) as { data: { dateFormat?: string } };
return payload.data.dateFormat ?? "AUTO";
});
expect(
["DMY", "MDY", "YMD"],
"the account pins an explicit date order for the period line",
).toContain(preference);
return preference as DateOrder;
}
/**
* The period line's two dates, as a span in days.
*
* The line is rendered in the account's date order and its timezone, so the
* dates are read structurally and compared as a SPAN. A span is timezone-proof
* in a way an absolute date is not: both ends move together.
*
* The separator is captured once and back-referenced, so `10.09.2026`,
* `09/10/2026` and `2026-09-10` all parse and none of them can be read as the
* other two.
*/
function periodSpanDays(text: string, order: DateOrder): number {
const match =
/Reporting period:\s*(\d{2,4})([./-])(\d{2})\2(\d{2,4})\s*\D{1,3}\s*(\d{2,4})\2(\d{2})\2(\d{2,4})/.exec(
text,
);
expect(match, "the report prints a reporting period with two dates").not.toBe(
null,
);
const start = utcMidnight(match![1], match![3], match![4], order);
const end = utcMidnight(match![5], match![6], match![7], order);
return Math.round((end - start) / 86_400_000);
}
function utcMidnight(
first: string,
second: string,
third: string,
order: DateOrder,
): number {
const [a, b, c] = [Number(first), Number(second), Number(third)];
const [year, month, day] =
order === "YMD" ? [a, b, c] : order === "DMY" ? [c, b, a] : [c, a, b];
return Date.UTC(year, month - 1, day);
}
test.describe.serial("the doctor report", () => {
// This journey's own account owns the readings, the allergy and the drug, and
// the page's own `fetch` writes them under its session.
test.use({ storageState: REPORT_OWNER_STORAGE_STATE_PATH });
// Generating the report exports the whole record, which asks for a sign-in
// or re-proof within five minutes. The shared jar is fresh only early in a
// run, so each test starts from a session signed in ten minutes ago and
// answers the re-proof dialog the way the owner would.
let endStaleSession: (() => Promise<void>) | null = null;
test.beforeEach(async ({ page }) => {
endStaleSession = await useStaleSession(page, E2E_REPORT_OWNER.username);
});
test.afterEach(async () => {
await endStaleSession?.();
endStaleSession = null;
});
test("generates a PDF that names the period, the vitals and the medication", async ({
page,
}) => {
// A production build rendering a charted PDF over a seeded window is well
// past the 30 s default, and a timeout here would report a failure that
// says nothing about the report.
test.setTimeout(120_000);
await openReportPanel(page);
const seeded = await seedReportFixture(page);
// 201 on a first run, 409 on a repeat — both mean the readings are there.
for (const status of seeded.measurements) {
expect([201, 409]).toContain(status);
}
expect([200, 201]).toContain(seeded.allergy);
expect([200, 201]).toContain(seeded.medication);
expect(seeded.emergency).toBe(200);
// Reload so the panel is looking at the record that now exists.
await openReportPanel(page);
await chooseStandardPdfScope(page);
// The period: a window the panel offers, and not the one it defaults to.
await page.locator("#hr-range").selectOption({ value: String(RANGE_DAYS) });
await expect(page.locator("#hr-range")).toHaveValue(String(RANGE_DAYS));
const report = await generateReport(page);
expectRealPdf(report);
// The document says what it is about.
expect(report.text).toContain("Reporting period");
const span = periodSpanDays(report.text, await readDateOrder(page));
expect(span).toBeGreaterThanOrEqual(RANGE_DAYS - 1);
expect(span).toBeLessThanOrEqual(RANGE_DAYS + 1);
// The blood-pressure section only prints when both series carried readings
// in the window, so its presence is the seeded history arriving.
expect(report.text).toContain(BP_SECTION);
// And the record the clinician reads first: the drug and the allergy.
expect(report.text).toContain(MEDICATION_NAME);
expect(report.text).toContain(ALLERGY_SUBSTANCE);
});
test("a window with no readings is an empty report, not a broken one", async ({
page,
}) => {
test.setTimeout(120_000);
await openReportPanel(page);
await chooseStandardPdfScope(page);
// A custom window a year back: inside the route's span bounds, and holding
// none of this account's readings.
await page.locator("#hr-range").selectOption({ value: "custom" });
const panel = page.getByTestId("health-record-export-panel");
const dateFields = panel.locator(
'[data-slot="date-field"] input[type="text"]',
);
await expect(dateFields).toHaveCount(2);
// The field commits a clean ISO string whatever the locale's field order is.
await dateFields.first().fill(isoDayBack(EMPTY_WINDOW_START_DAYS_BACK));
await dateFields.first().press("Enter");
await dateFields
.nth(1)
.fill(isoDayBack(EMPTY_WINDOW_START_DAYS_BACK - EMPTY_WINDOW_DAYS));
await dateFields.nth(1).press("Enter");
const report = await generateReport(page);
// Still a document: the empty window is answered with a report, not with a
// truncated file and not with an error the panel swallows.
expectRealPdf(report);
expect(report.text).toContain("Reporting period");
// And it is the window that was typed. Two silent fallbacks sit under this
// line — the panel sends `{ days }` when either date field is empty, and
// the route falls back to the 90-day default when a bound fails to parse,
// neither of them a 422. Both land on a window that HOLDS the seeded
// readings, so without this the absence below would be the fixture's luck.
const emptySpan = periodSpanDays(report.text, await readDateOrder(page));
expect(emptySpan).toBeGreaterThanOrEqual(EMPTY_WINDOW_DAYS - 1);
expect(emptySpan).toBeLessThanOrEqual(EMPTY_WINDOW_DAYS + 1);
// Nothing was measured in it, so the section that needs readings is gone.
expect(report.text).not.toContain(BP_SECTION);
// The positive control for that absence: what the window does not empty
// is still in the document. The allergy is not window-scoped at all, and
// the drug's course began before the window and never ended, so it was
// being taken then. Without this, a renderer that produced a blank page
// would pass the line above.
expect(report.text).toContain(MEDICATION_NAME);
expect(report.text).toContain(ALLERGY_SUBSTANCE);
});
});
+17
View File
@@ -20,6 +20,7 @@ import type { Page } from "@playwright/test";
import { expect, test } from "./setup/test";
import { STORAGE_STATE_PATH } from "./setup/global-setup";
import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
import {
ensureVaultFixture,
ensureVaultAiFixture,
@@ -121,6 +122,13 @@ async function mockAiEnabled(
}
test.describe("document vault — AI assist + content search", () => {
// AI surfaces render from the `ai` block of `/api/auth/me`, and the suite
// has no reachable provider; every capability reads available here so the
// mocked AI routes below are what the surfaces talk to.
test.beforeEach(async ({ page }) => {
await serveAiBlock(page, aiBlockAvailable());
});
test.use({ storageState: STORAGE_STATE_PATH });
test.beforeAll(async () => {
@@ -373,6 +381,15 @@ test.describe("document vault — AI assist + content search", () => {
const sheet = page.getByRole("dialog");
await expect(sheet).toBeVisible();
// The sheet shell paints skeletons while the detail query is pending, so
// its own visibility says nothing about the body having rendered. The
// footer download action belongs to the resolved document, so waiting on
// it is what keeps the two absences below from passing against a
// skeleton that never had the line to begin with.
await expect(
sheet.locator('[data-slot="document-download"]'),
).toBeVisible();
await expect(
sheet.locator('[data-slot="document-detail-ai-read"]'),
).toHaveCount(0);
Loaded 100 of 4057 files, more files were not shown because too many files have changed in this diff. Show more