Commit Graph
6301 Commits
Author SHA1 Message Date
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
v1.38.13
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
v1.38.12
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