SHC vNext QR proof of concept

Prompt: find histories the cycle-log codec handles badly

Rendered from research/adversarial-histories-prompt.md in the repository.

Give everything below the line to an agent with a shell on this machine. It assumes no prior knowledge of the project.


You are stress-testing a data format. Your job is to invent realistic health-tracking histories, and deliberately awkward ones, that the format either cannot carry or can carry only at a high byte cost, and to report what you find with evidence. You change nothing in the project.

Background

The project is a proof of concept called shc2-poc. A QR code carries a compact "card". On the receiving phone, a sandboxed WebAssembly program (a "codec") expands the card into an ordinary FHIR R4 Bundle. No server is involved, so everything has to fit in one QR code: about 1,000 bytes is comfortable to scan from a phone screen, about 1,700 is a stretch, and 2,900 is the absolute ceiling.

There is one codec so far, cycle-log. It carries up to 400 days of menstrual-cycle tracking for one person: bleeding and flow, pain, symptoms, basal and skin temperature, cervical mucus, ovulation/progesterone/pregnancy tests, sexual activity, mood, energy, sleep, a pill log, medications, contraception/pregnancy/breastfeeding intervals, procedures, conditions, screening answers, statements about how completely something was logged, vital signs, and "custom series" declared by the card for anything else (any code from any code system; boolean, coded, numeric, or readings with components such as blood pressure). Any series may have any number of entries on a day, each with an optional time of day. Repeated and mutually disagreeing entries are allowed; the card carries what was recorded.

Three layers matter to you:

  1. The input model. A small typed JSON structure that an app fills in. This is what the codec encodes. Anything the model cannot express cannot go on a card.
  2. The codec. It compresses a model using predictions tuned for cycle data (cycle phase, the previous day, habitual times). Data that looks like what it expects is very cheap; data that does not is expensive.
  3. The lifter. It reads an arbitrary FHIR Bundle into the model and reports, item by item, what was carried as written, what was carried but written differently, and what was not carried. A separate planner can then shrink a model to a target size by named steps (drop times of day, coarsen values, drop a series, shorten the window).

The project's stated principles include: nothing is dropped or approximated silently; built-in tables make expected content cheap but must never limit what can be said; no artificial limits. Your findings test those claims.

Where things are

The repository is at <repository root>. Treat it as read-only. Run git -C <repository root> log --oneline -3 and git status --short first; the tree may contain uncommitted work in progress, and if a tool you need fails for that reason, say so in your report and carry on with what works.

Read these before generating anything:

Tools you can run (Bun is installed; run from the repository root):

  • Validate and encode a model, getting its card size. Write a small script that imports validate and normalize from codecs/cycle-log/model.ts and load and encodeModel from codecs/cycle-log/codec-host.ts; codecs/cycle-log/sizes.ts and demo.ts show the calls. The card is the codec's output plus 3 bytes.
  • See where the bytes went: codecs/cycle-log/sizes.ts prints a per-category breakdown for the samples, using the tools module's trace; adapt it for your own models.
  • Turn a model into a Bundle: toBundle in codecs/cycle-log/to-bundle.ts.
  • Lift a FHIR Bundle: bun codecs/cycle-log/lift/cli.ts <bundle.json> prints the report; add --target v22-L --viewer to also plan a reduction to QR Version 22 at error-correction level L with the viewer link in front (949 bytes of card). Run it with --help or read cli.ts for options, including the groups that must be explicitly allowed before blocked items are left out.
  • QR capacity for a card size: site/shared/qrfit.ts.
  • Some tests need R4_DEFINITIONS=<directory holding the FHIR R4 definitions>. You should not need to run the test suites.

Put every file you create under <a scratch directory outside the repository>/ (create it). Do not write inside the repository and do not use /tmp. The disk is nearly full: keep your output small, in the low megabytes, and delete intermediate files. The machine has no swap; do not run many heavy processes at once.

What to produce

Aim for 40 to 60 histories. Each is one person's record over up to a year, written the way a real source would produce it. Split them roughly evenly between two kinds of input:

  • Models (JSON in the input model's shape), to probe what the model can say and what it costs.
  • FHIR Bundles as a real app, wearable platform or patient portal export would write them, to probe the lifter. Vary the style: server-style with UUIDs, meta, narrative and identifiers; app-style with local times and custom extensions; hand-assembled; merged from two sources.

Cover both of these aims, and label each history with which it serves:

A. Plausible. Histories that real people and real apps produce, which the designers may not have pictured. Think about who actually tracks and why, and about what the data looks like when it is not tidy. Starting points, to be extended with your own:

  • Life stages and situations: adolescence with very irregular first cycles; postpartum and breastfeeding with no bleeding for months; perimenopause with flooding and long gaps; menopause on hormone therapy; pregnancy loss; fertility treatment with injections, monitoring and procedures on a dense schedule; gender-affirming testosterone with bleeding stopping; continuous or extended-cycle pill use; a hormonal IUD with months of unpredictable spotting; endometriosis or adenomyosis with daily pain independent of cycle; PMDD mood tracking; bleeding disorders; a person tracking for a clinician's question that is not about cycles at all.
  • How people really log: several times a day in bursts, then nothing for weeks; back-filling a month from memory with approximate dates; editing and correcting; logging the same thing in two apps; shift work and travel across time zones and the date line; a phone clock that was wrong; free-text notes carrying most of the meaning; photos; one-word custom tags invented by the person.
  • What apps and devices really export: continuous or high-frequency series (temperature every minute overnight, heart rate, HRV, respiratory rate, sleep stages); values in unusual units or precisions; ranges and "greater than" values; predicted values alongside recorded ones (predicted period, predicted ovulation, fertile window); app-computed scores; questionnaires with many items; things with durations (a headache from 14:00 to 19:30, sleep intervals, exercise sessions); quantities per event (number of pads or tampons, clot size, pill dose); attachments; data about a partner or a baby in the same export; more than a year, or several disjoint periods of tracking.

B. Adversarial. Histories built on purpose to hit the model's edges or defeat the compressor, each aimed at a specific rule, limit or prediction you found in the documents. For example: the highest-entropy data that is still valid; many custom series with long codes and long labels; values that sit just inside and just outside every numeric range and precision; windows of exactly 400 and 401 days; the largest number of facts; time-of-day patterns chosen to defeat the "habitual time" prediction; cycles engineered to defeat the cycle-phase prediction; a tiny dataset whose card is far larger than its information content; data that is valid in the model but that you believe the FHIR profiles, the lifter or the decoder's inverse would treat inconsistently. If you find an input where two parts of the project disagree (for example a model that validates but whose Bundle the lifter does not read back as the same model, or a Bundle the lifter calls carried-as-written that changes when the card is decoded), that is the most valuable kind of finding: reduce it to the smallest example you can.

Do not invent clinical facts you are unsure of to make a history look authoritative; plausibility of the data shape matters, not medical detail. All data is synthetic. Refer to the person a record is about as "the person" or "they"; never assume gender. Use no real names, and no real identifiers.

What to measure for each history

  1. Does it map? For a model: does it validate? If not, the exact error. For a Bundle: the lifter's counts of carried as written, written differently, not carried, and blocked, with the reasons that occurred. Then say in one or two plain sentences what a receiving clinician would be missing, if anything.
  2. What does it cost? Card bytes and the QR version at level L with the viewer link. Compare with a baseline you compute: the size of the same content written naively (for instance the minified model JSON after DEFLATE), and the per-category breakdown. Say which part of the data is responsible for the cost and why the compressor does poorly on it, citing the FORMAT.md section.
  3. Can it be made to fit? Run the planner to Version 22-L with the viewer link. Record the steps it took and judge them: is what it gave up the right thing to give up for this person's situation, or did it throw away the point of the record (for example dropping the pain series for a person tracking endometriosis pain)? Note where a better step obviously exists that the planner does not have.
  4. Is anything silently wrong? Decode the card back to a Bundle and check, for a handful of facts you pick, that what comes out is what went in. Any silent change is a defect; report it with the exact input.

Report

Write <a scratch directory outside the repository>/REPORT.md, and give the same content as your final message in case the file cannot be read. Keep each history's input beside it as NN-short-name.model.json or NN-short-name.bundle.json, with any script you used to generate it, so every number can be reproduced. If you cannot write the report file, say so and put the full report in your final message.

Structure:

  1. Summary. The ten most important findings in order, each one sentence, each naming the history that shows it.
  2. Gaps in what can be said. Things real histories contain that the model has no place for, grouped by kind (for example durations, free text, predictions, high-frequency series, quantities per event, more than one subject), each with how common you judge it to be in real exports, how you know, and what the lifter does with it today.
  3. Things that can be said but cost too much. A table: history, card bytes, QR version, the naive baseline, the dominant cost, and what would make it cheaper (a model change, a codec prediction, or a planner step).
  4. Disagreements and defects. Any place two parts of the project disagree, or data changes silently, with the smallest reproducing input and the exact commands.
  5. Planner judgment. Where the reduction it chose was wrong for the person's situation, and what a better choice would be.
  6. The histories. One short entry each: who the person is and why they track, what kind of source produced the data, which aim it serves, and the measurements above.
  7. What you did not get to, and anything you could not run and why.

Separate what you measured from what you infer. A finding without a reproducing file and command is a suggestion, not a finding; label it as such. Do not pad: a history that maps cleanly and cheaply gets one line saying so.