# SHC vNext QR Proof of Concept (`cycle-log` Codec) > Offline, server-free sharing of menstrual-cycle and personal health tracking spanning up to `10,000` days (~27 years), bounded naturally by QR byte capacity (~250 KB–1+ MB of FHIR R4 JSON inside a single phone-scannable QR code of 300–1,960 bytes). A sparse bleeding calendar fits 10+ years in one QR code, while a dense multi-series log trims smoothly to fit your chosen QR version. A sending app writes a compact typed JSON object (`CycleLog`, using readable built-in keywords, uniform `{ date, ... }[]` arrays, standard FHIR R4 `CodeableConcept` escapes, FHIR `dateTime`/`instant`, and natural decimals), runs one zero-import WebAssembly codec (`codecs/1.wasm`), frames the bytes with a 2-byte SHA-256 check, and renders a numeric-mode QR code. Any receiving app or the browser viewer decodes the QR completely offline back into a canonical FHIR R4 Bundle. **Full bundled specification (for large-context agents):** https://joshuamandel.com/shc2-poc/llms-full.txt --- ## Architecture at a Glance ``` [Your App State / DB] ──(direct mapping; no FHIR needed)──┐ ▼ [Existing FHIR R4 Bundle] ──(lift.ts, checks isModifier)──► CycleLog JSON (validate + normalize) │ (if > QR budget) ◄────┴────► plan.ts (omission-only; sets reduced: true) │ ▼ codecs/1.wasm :: shc_encode() │ ▼ pack({ codec: { id: 1 }, input }) ──► [0x01][payload][2B SHA-256] │ ▼ QR Code: "https://joshuamandel.com/shc2-poc/#shc2:/" + bytesToDigits(card) (7 bytes -> 17 numeric QR digits, 98.8% binary density) │ ══════════ camera scan (100% offline) ══════════ │ ▼ cardBytesFromText() -> parse() -> codecs/1.wasm :: shc_decode() │ ▼ Canonical FHIR R4 Bundle JSON ──► Viewer / EHR ``` Key design guarantees: - **Zero server dependency:** Everything after `#` stays on-device; both encoding and decoding run locally in WebAssembly. - **No FHIR required on the sender:** Native tracking apps populate `CycleLog` JSON directly; `shc_decode()` synthesizes a standards-compliant FHIR R4 Bundle on the receiver. - **Deterministic & canonical:** One exact byte sequence per dataset. `shc_decode()` verifies canonical form by re-encoding internally. - **Unsigned, patient-reported data:** Cards carry no cryptographic signature today; receivers must display them as patient-reported records. - **Strictly omission-only fitting:** When data exceeds a QR budget, never round recorded values (preserve exact `0.01°` temperatures, exact sleep minutes, exact BP readings, exact times or drop times whole). Set `reduced: true` (emitted as FHIR `Bundle.meta.tag` `SUBSETTED`). --- ## Live Published Artifacts - **Codec WASM (registry id `1`, `cycle-log`):** https://joshuamandel.com/shc2-poc/codecs/1.wasm - Size: **353,251 bytes** (zero imports, zero floats, link-time zero-panic) - SHA-256: `f2811c67a352393f632482b61756815b4d99dc574b070ebb9fb9a89b046a0f68` - Immutable URL by hash: https://joshuamandel.com/shc2-poc/codecs/sha256/f2811c67a352393f632482b61756815b4d99dc574b070ebb9fb9a89b046a0f68.wasm - **Browser / Node / Bun helper library (ES module):** https://joshuamandel.com/shc2-poc/lib/shc2.js - Exports: `bytesToDigits`, `digitsToBytes`, `cardBytesFromText`, `toLinkText`, `SCHEME`, `pack`, `parse`, `runCodec`, `CodecError`, `LIMITS`, `encodeQr`, `qrToSvg` - **Registry JSON:** https://joshuamandel.com/shc2-poc/registry.json - **Normative Input Model (TypeScript):** https://joshuamandel.com/shc2-poc/codecs/cycle-log/model.d.ts.txt - **Derived JSON Schema (2020-12):** https://joshuamandel.com/shc2-poc/codecs/cycle-log/model.schema.json - **FHIR CodeSystem:** https://joshuamandel.com/shc2-poc/CodeSystem/cycle-log.json - **Closed FHIR R4 Profiles Index:** https://joshuamandel.com/shc2-poc/codecs/cycle-log/profiles/index.json - **Source Repository (MIT):** https://github.com/jmandel/shc2-poc --- ## Implementing Offline Sharing in an Existing App ### Path A: Add "Share via QR" to an Existing App (JS / TypeScript / Web / React Native / Electron) Bundle `codecs/1.wasm` and `lib/shc2.js` locally with your app so sharing works completely offline (airplane mode). #### Step 1: Map your app's data into a `CycleLog` object ```ts // Example mapping covering readable keywords, text-only tags, offline displays on // standard escapes, BBT with exclusion, medication doses, contraception, and vitals. const LOINC = "http://loinc.org"; const RXNORM = "http://www.nlm.nih.gov/research/umls/rxnorm"; const model = { exportedAt: "2026-04-01T09:00-05:00", // optional FhirInstant -> FHIR Bundle.timestamp (Z & :00 accepted) source: { name: "MyTracker", version: "2.4" }, // optional Device patient: { family: "Testperson", given: ["Alex"], birthDate: "1994-06" }, // optional; omit for anonymous card conditions: [{ code: "endometriosis", status: "active", onset: "2021" }], intervals: [{ kind: "combined-pill", start: "2026-01-01", end: "2026-03-31" }], bleeding: [ { date: "2026-01-01", value: "heavy" }, { date: "2026-01-02", value: "moderate" }, { date: "2026-01-03", value: "light" }, { date: "2026-01-04", value: "spotting" }, { date: "2026-01-05", value: "no-bleeding" }, // explicit negative; omitted dates = not recorded ], pain: [ { date: "2026-01-01", value: 6 }, { date: "2026-01-02", value: 4 }, { date: "2026-01-03", value: 2 }, { date: "2026-01-04", value: 0 }, // 0 = explicit no pain; omitted dates = not recorded ], symptoms: [ { date: "2026-01-01", value: "menstrual-cramp" }, // built-in SymptomKind -> SNOMED CT 431416001 { date: "2026-01-01", value: "headache" }, // built-in SymptomKind -> SNOMED CT 25064002 { date: "2026-01-02", value: { text: "Brain fog" } }, // text-only CodeableConcept (no fake app URI needed) { date: "2026-01-03", value: "menstrual-cramp" }, ], bbt: { unit: "Cel", // "Cel" or "[degF]" — natural degrees, up to 2 decimal places entries: [ { date: "2026-01-01", value: 36.42 }, { date: "2026-01-02", value: 37.85, excluded: true, excludeReason: "fever" }, // excluded from thermal shift { date: "2026-01-03T06:45-05:00", value: 36.48 }, ], }, medications: [ { date: "2026-01-01", code: "ibuprofen", status: "taken", dose: { value: 400, unit: "mg" } }, { date: "2026-01-01", code: { coding: [{ system: RXNORM, code: "314076", display: "Lisinopril 10 MG Oral Tablet" }], text: "Blood pressure pill", // display & text preserved on any non-built-in escape! }, status: "taken", }, { date: "2026-01-02", code: "ibuprofen", status: "not-taken" }, ], custom: [ // Clinical fever temperature uses LOINC 8310-5 (separate from BBT basal-body-temperature) { code: { coding: [{ system: LOINC, code: "8310-5" }] }, valueType: "quantity", // -> Observation.valueQuantity unit: "Cel", entries: [{ date: "2026-01-02", value: 38.4 }], }, // Blood pressure (LOINC 85354-9) with systolic (8480-6) and diastolic (8462-4) { code: { coding: [{ system: LOINC, code: "85354-9" }] }, valueType: "components", // -> Observation.component[] components: [ { code: { coding: [{ system: LOINC, code: "8480-6" }] }, valueType: "quantity", unit: "mm[Hg]" }, { code: { coding: [{ system: LOINC, code: "8462-4" }] }, valueType: "quantity", unit: "mm[Hg]" }, ], entries: [ { date: "2026-01-01", components: [ { code: { coding: [{ system: LOINC, code: "8480-6" }] }, value: 122 }, { code: { coding: [{ system: LOINC, code: "8462-4" }] }, value: 78 }, ], }, ], }, ], }; ``` #### Step 2: Encode with `codecs/1.wasm` and render an SVG QR code ```ts import { bytesToDigits, encodeQr, pack, qrToSvg, toLinkText } from "./shc2.js"; const VIEWER_PREFIX = "https://joshuamandel.com/shc2-poc/#shc2:/"; /** Compile once at startup; instantiate fresh per encode call for bounded memory. */ export async function encodeCycleLog(wasmModule: WebAssembly.Module, model: unknown): Promise<{ card: Uint8Array; digits: string; qrSvg: string; qrVersion: number; shareLink: string; }> { const instance = await WebAssembly.instantiate(wasmModule, {}); // zero imports! const { memory, shc_alloc, shc_encode } = instance.exports as { memory: WebAssembly.Memory; shc_alloc: (n: number) => number; shc_encode: (ptr: number, len: number) => number; }; const jsonBytes = new TextEncoder().encode(JSON.stringify(model)); const inPtr = shc_alloc(jsonBytes.length); new Uint8Array(memory.buffer, inPtr, jsonBytes.length).set(jsonBytes); const recPtr = shc_encode(inPtr, jsonBytes.length); const view = new DataView(memory.buffer, recPtr, 12); const status = view.getInt32(0, true); const outPtr = view.getUint32(4, true); const outLen = view.getUint32(8, true); const payload = new Uint8Array(memory.buffer, outPtr, outLen).slice(); if (status !== 0) { // 1 = MALFORMED (invalid field), 2 = UNSUPPORTED, 3 = LIMIT (>4096 B card) const msg = new TextDecoder().decode(payload); throw new Error(`shc_encode refused (status ${status}): ${msg}`); } const card = pack({ codec: { id: 1 }, input: payload }); // [0x01][payload][2B SHA-256] const digits = bytesToDigits(card); const qr = encodeQr( [{ mode: "byte", data: VIEWER_PREFIX }, { mode: "numeric", data: digits }], { ecLevel: "L", maxVersion: 40 }, ); return { card, digits, qrSvg: qrToSvg(qr), qrVersion: qr.version, shareLink: toLinkText(card, "https://joshuamandel.com/shc2-poc/#"), // shorter base64url form for text/messaging only (never QR) }; } ``` #### Step 3: Target QR Budgets & Omission-Only Fitting | QR Target (EC Level L) | Bare `shc2:/` | With Viewer Link (`https://joshuamandel.com/shc2-poc/#shc2:/`) | Phone Scan Experience | |---|---:|---:|---| | **Version 22-L** | 983 B | 949 B | Comfortable on any phone screen | | **Version 25-L** | 1,250 B | 1,215 B | Good everyday target | | **Version 30-L** | 1,703 B | 1,669 B | Stretch limit on modern cameras | | **Version 40-L** | 2,910 B | 2,875 B | Hard QR ceiling | If `card.length` exceeds your chosen target (recommended default: **Version 22-L = 949 B** with viewer link, or **Version 25-L = 1215 B**), reduce the model using **omission-only** steps and set `model.reduced = true`: 1. Drop redundant `Coding.display` text where `display` repeats `code` (class 0 — does not require `reduced: true`). 2. Drop time-of-day parts from FHIR `DateTime` values while keeping calendar dates (class 1). 3. Drop `Coding.display` on human-readable codes (keep displays on opaque UUIDs/numeric IDs and rich multi-word free-text phrases!) and drop `flow-none` to `no-bleeding` (class 2). 4. Thin multi-entry days to one entry per day (**never use `max` on multi-component panels like BP**), drop explicit negatives, or omit lower-priority series (**keep `source` while `skinTemp` stays on the card**; never split BP systolic/diastolic) (class 5). 5. Trim oldest days in whole cycles from the earliest recorded date (class 6). - **NEVER alter recorded values:** do not round `0.01°` BBT/skinTemp, sleep minutes, blood pressure, pain scores, or timestamps. - For an automated planner (and arbitrary FHIR R4 Bundle lifting), see `codecs/cycle-log/lift/lift.ts` and `codecs/cycle-log/lift/plan.ts` in the repository. ### Path B: Receive / Decode a Scanned QR or Link Offline ```ts import { cardBytesFromText, parse, runCodec } from "./shc2.js"; export async function decodeShc2(scannedText: string, wasmBytes: Uint8Array) { // Accepts bare "shc2:/...", viewer URL "https://...#shc2:/...", or link form "shc2:/b/..." const cardBytes = cardBytesFromText(scannedText); const { codec, input } = parse(cardBytes); // verifies 2-byte SHA-256 check if (!("id" in codec) || codec.id !== 1) { throw new Error(`Unsupported codec: ${JSON.stringify(codec)}`); } const { bundle } = await runCodec(wasmBytes, input); // static audit + fresh WASM instance + JSON parse const isReduced = bundle.meta?.tag?.some((t: any) => t.code === "SUBSETTED") ?? false; return { bundle, isReduced }; } ``` Receiver checklist: - Inspect `bundle.meta.tag` for `SUBSETTED` and show a visible notice that some source data was omitted (everything present is verbatim). - Respect `reading-excluded` (`valueBoolean: true`) and `reading-exclusion-reason` components on BBT / skinTemp Observations — exclude disturbed days from thermal-shift / coverline calculations and show the reason. - Read optional medication doses from `MedicationStatement.dosage[0].doseAndRate[0].doseQuantity`. - Distinguish BBT (`…/CodeSystem/cycle-log|basal-body-temperature`) from fever / clinical body temperature (`http://loinc.org|8310-5`). - Handle multiple Observations on the same day (including disagreements) without silently collapsing them. ### Path C: Native / Non-JS Hosts (Swift, Kotlin, Rust, Python, Go) No JS library is required. Any WebAssembly MVP+bulk-memory runtime (Wasmtime, Wasmer, WAMR, Wasm3, WebView) can host `codecs/1.wasm` directly: 1. **Instantiate with zero imports** (`{}`). Static audit requires: 0 imports, 0 floats, 0 SIMD/threads, no start function, exports `memory`, `shc_alloc`, `shc_encode`, `shc_decode`. 2. **Call ABI:** - `ptr = shc_alloc(input.len)` → copy input bytes into `memory[ptr..ptr+len]`. - `rec = shc_encode(ptr, len)` (JSON → compressed payload) or `shc_decode(ptr, len)` (compressed payload → canonical FHIR Bundle JSON). - Read 12 little-endian bytes at `memory[rec..rec+12]`: `status: i32`, `out_ptr: u32`, `out_len: u32`. - `status == 0`: success; `1`: malformed input; `2`: unsupported; `3`: size/work limit exceeded. On error, `out` is a UTF-8 diagnostic message. 3. **Card framing:** `[LEB128(codec_id)][payload][SHA256(header + payload)[0..2]]`. For codec id `1`, header is the single byte `0x01`. 4. **QR numeric transport (7 bytes ↔ 17 digits):** - Split card bytes into 7-byte big-endian unsigned integers; format each full 7-byte block as 17 zero-padded decimal digits. - Final partial block of `n ∈ 1..6` bytes uses `TAIL_DIGITS[n]` digits: `1→3, 2→5, 3→8, 4→10, 5→13, 6→15`. - Encode QR as two segments: Byte segment `"https://joshuamandel.com/shc2-poc/#shc2:/"` (or bare `"shc2:/"`) + Numeric segment `digits`, Error Correction Level `L`. - Link form (for messaging/clipboard only, never QR): `"https://joshuamandel.com/shc2-poc/#shc2:/b/" + base64url(card)` (no `=` padding). --- ## Critical Data Model Rules (Common Pitfalls) 1. **Uniform `{ date, ... }[]` arrays & omission ≠ "no":** Every observation series is a flat array of dated objects (`{ date, value }`, `TempEntry`, `MedEntry`, or `CustomComponentsEntry`) — no date-string map keys, no polymorphic `T | Entry[]` unions, and no `start`, `days`, or `DayIndex`. Across all daily series, intervals and answers, earliest to latest recorded date spans at most 10,000 days. Omitting an entry or optional field always means *not recorded* (canonical JSON omits absent and empty optional fields). Use `"no-bleeding"`, `pain` value `0`, `"not-taken"`, `pill` value `"missed"` for explicit negatives. 2. **Readable keywords + FHIR R4 `CodeableConcept` (no `ConceptKey`, no root `labels`):** Built-in slots use readable string keywords (`SymptomKind` 35, `MedicationKind` 7, `ConditionKind` 15, plus `Mucus`, `Sex`, `Mood`, `Energy`, `ProcedureKind`, `IntervalKind`, `ExcludeReason`, etc.) that expand on decode to canonical SNOMED CT / LOINC / `cycle-log` codings. Escapes and `custom[]` use standard FHIR R4 `CodeableConcept` objects (`{ coding: [{ system, code, display? }], text? }` or text-only `{ text }`). For built-in concepts, `coding[0].display` is optional on input and stripped canonically, and `text` is not allowed. For *any* non-built-in escape concept (SNOMED CT, LOINC, RxNorm, ICD-10-CM, ATC, NDC, or app URIs), both `coding[0].display` and `text` (≤ 128 chars) are preserved and must agree across all occurrences of the same `(system, code)`. Text-only `{ text }` concepts carry user or app tags without synthetic code-system URIs. 3. **Standard FHIR `dateTime` / `instant`:** `DateTime` (`YYYY-MM-DD` or `YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM)`, 2000–2099), `FhirDateTime` (for `procedures[]`, year 1900–2150 including `YYYY` and `YYYY-MM`), and `FhirInstant` (for `exportedAt`) all accept `"Z"` (normalized to `"+00:00"`) and `":00"` seconds (omitted canonically); `"-00:00"` is rejected. 4. **Natural decimals & integers (no scientific notation, no `-0`):** Integer fields (`pain`, `volume`, `sleep`, numeric `answers`) use `-?(0|[1-9][0-9]*)`. Decimal fields (`bbt` and `skinTemp` up to 2 decimal places; `MedDose.value` and custom quantities up to 6 decimal places) use natural JSON decimals (`36.42`, `-0.31`, `12.5`) — no `scale` field, no `1e2`, no `-0` or `-0.0` (the WASM codec remains 100% integer-only internally). 5. **All fields optional; `exportedAt` → `Bundle.timestamp`:** `{}` is a valid `CycleLog`. There is no synthetic `tracking-window` Observation in the FHIR Bundle; optional `exportedAt` (`FhirInstant`, e.g. `"2026-04-01T09:00-05:00"`) maps to FHIR `Bundle.timestamp`. 6. **Unified procedures & answers:** `procedures[]` holds `{ date: FhirDateTime, code: ProcedureKind | CodeableConcept }` and `answers[]` holds `{ date: DateTime, question, value }` — no separate `time` property, and `intervals[]` uses `"breastfeeding"`. 7. **Multiple entries & disagreements:** Multiple entries on the same date (timed or untimed, identical or disagreeing) are simply additional elements in the array — all carried verbatim, never merged (except overlapping/touching intervals of the same state). 8. **BBT vs. fever & `custom[].valueType`:** Built-in `bbt` emits `basal-body-temperature`. Clinical body temperature / fever (`{ coding: [{ system: "http://loinc.org", code: "8310-5" }] }`) belongs in `custom[]` with `valueType: "quantity"` (automatically gets FHIR `vital-signs` category). Every `CustomSeries` declares `valueType` (`"boolean"` → `valueBoolean`, `"coded"` → `valueCodeableConcept`, `"quantity"` → `valueQuantity`, `"components"` → `component[]`), and each `CustomComponent` declares `valueType` (`"boolean"`, `"coded"`, or `"quantity"`). 9. **Reserved codes:** Built-in series codes (e.g. `menstrual-bleeding`, LOINC `72514-3`, `basal-body-temperature`, LOINC `93832-4`) may not be duplicated in `custom[]`; put them in their built-in field. 10. **R4 vital-sign units:** Profiled LOINC vital signs in `custom[]` enforce their R4 UCUM units (e.g., heart rate `8867-4` in `/min`, BP `85354-9` components `8480-6`/`8462-4` in `mm[Hg]`, weight `29463-7` in `kg`/`g`/`[lb_av]`). 11. **Unknown fields rejected:** Every object is closed; extra keys return `status = 1 (MALFORMED)`. --- ## `CycleLog` Field Cheat Sheet ### Card frame & metadata (all optional; `{}` is valid) - `exportedAt`: When the card was exported, as a FHIR instant with UTC offset (mapped to FHIR `Bundle.timestamp`). - `reduced`: The sender deliberately left out data to fit a size: a series, time of day, or display that is absent may have been tracked; recorded values are never altered. - `patient`: Who the card is about, kept deliberately small. - `source`: The source app: its name and optional version. ### Whole-record context & history - `conditions`: Conditions the person reports having (background context such as PCOS or fibroids). - `intervals`: States that last over a range of calendar dates: contraception, pregnancy, breastfeeding, or any other coded or text-only state. - `procedures`: Procedures: partial date (`YYYY`, `YYYY-MM`), full date (`YYYY-MM-DD`), or full date with time (`YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM)`), year 1900-2150. - `answers`: Screening questions the person answered, each with the date (and optional time) they answered it. ### Built-in daily series (uniform `{ date, ... }[]` arrays using FHIR `DateTime`; omitted date = not recorded) - `bleeding`: Menstrual bleeding entries. - `volume`: Collected menstrual fluid entries, whole mL (a smart or graduated cup). - `pain`: Pain entries on a 0-10 numeric rating scale (LOINC 72514-3). - `symptoms`: Symptoms present on each date: a built-in keyword (`SymptomKind`) or any FHIR `CodeableConcept` as an escape (presence only; for severity use a custom coded series). - `bbt`: Basal body temperature (waking readings). - `skinTemp`: Nightly skin or wrist temperature from a wearable (one device per card). - `mucus`: Cervical mucus entries. - `ovulationTest`: LH (ovulation) test result entries. - `progesteroneTest`: Progesterone (PdG) urine test result entries. - `pregnancyTest`: Pregnancy test result entries. - `sex`: Sexual intercourse entries. - `mood`: Mood entries on a 7-point valence scale. - `energy`: Energy entries on a 4-point scale. - `sleep`: Minutes of sleep ending on each date (attributed to the wake day). - `pill`: Contraceptive pill log entries. - `medications`: Medication entries (a dose taken twice is two entries with their timestamps). ### Extensibility - `custom`: Series without a built-in slot, each with its own Observation `CodeableConcept` and one of four `valueType` kinds (`"boolean"`, `"coded"`, `"quantity"`, or `"components"` for multi-component readings like blood pressure). ### Built-in enum values (quick reference) - **Bleeding** (bleeding[].value): `no-bleeding`, `flow-none`, `bleeding`, `spotting`, `light`, `moderate`, `heavy` - **SymptomKind** (symptoms[].value): `menstrual-cramp`, `backache`, `headache`, `migraine`, `stomach-ache`, `nausea`, `breast-tenderness`, `ovulation-pain`, `fatigue`, `bloating`, `depressed-mood`, `irritable`, `stress`, `dyspareunia`, `acne`, `pelvic-pain`, `low-back-pain`, `breast-pain`, `mood-swings`, `anxiety`, `diarrhea`, `constipation`, `dizziness`, `food-craving`, `vaginal-clots`, `hot-flash`, `night-sweats`, `insomnia`, `vaginal-dryness`, `palpitations`, `urinary-incontinence`, `memory-lapses`, `hair-loss`, `increased-libido`, `reduced-libido` - **MedicationKind** (medications[].code): `ibuprofen`, `naproxen`, `acetaminophen`, `mefenamic-acid`, `tranexamic-acid`, `iron`, `folic-acid` - **ConditionKind** (conditions[].code): `pcos`, `uterine-fibroids`, `adenomyosis`, `endometrial-polyp`, `endometriosis`, `von-willebrand-disorder`, `coagulation-disorder`, `iron-deficiency-anemia`, `hypothyroidism`, `hyperthyroidism`, `hyperprolactinemia`, `premature-ovarian-insufficiency`, `hypothalamic-amenorrhea`, `perimenopause`, `postmenopause` - **ExcludeReason** (bbt/skinTemp entries[].excludeReason): `fever`, `alcohol`, `poor-sleep`, `late-wake`, `travel`, `stress`, `medication`, `other` - **TemperatureUnit** (bbt/skinTemp unit): `Cel`, `[degF]` - **SkinTempKind** (skinTemp kind): `deviation`, `absolute` - **Mucus** (mucus[].value): `dry`, `sticky`, `creamy`, `watery`, `egg-white` - **OvulationTest** (ovulationTest[].value): `negative`, `lh-surge`, `estrogen-surge`, `indeterminate` - **TestResult** (progesteroneTest[].value / pregnancyTest[].value): `negative`, `positive`, `indeterminate` - **Sex** (sex[].value): `none`, `protected`, `unprotected`, `unspecified` - **Mood** (mood[].value): `very-unpleasant`, `unpleasant`, `slightly-unpleasant`, `neutral`, `slightly-pleasant`, `pleasant`, `very-pleasant` - **Energy** (energy[].value): `exhausted`, `low`, `high`, `energized` - **PillLog** (pill[].value): `taken`, `missed` - **MedStatus** (medications[].status): `taken`, `not-taken` - **ConditionStatus** (conditions[].status): `active`, `resolved` - **IntervalKind** (intervals[].kind): `none`, `combined-pill`, `progestin-pill`, `patch`, `ring`, `injection`, `implant`, `hormonal-iud`, `copper-iud`, `iud-unspecified`, `condom`, `fertility-awareness`, `lactational-amenorrhea`, `pregnant`, `breastfeeding` - **ProcedureKind** (procedures[].code): `iud-insertion`, `iud-removal`, `implant-insertion`, `implant-removal`, `emergency-contraception`, `hysterectomy`, `endometrial-ablation`, `oophorectomy`, `bilateral-oophorectomy`, `myomectomy`, `d-and-c`, `polypectomy`, `uterine-artery-embolization` - **Question** (answers[].question): `usual-cycle-length`, `periods-per-year`, `missed-periods-3-months`, `period-in-last-year`, `periods-stopped`, `age-periods-stopped`, `age-at-menarche` - **Escapes & `CodeableConcept`:** Every coded slot accepts either its readable built-in keyword or any FHIR R4 `CodeableConcept` (`{ coding: [{ system, code, display? }], text? }` or text-only `{ text }`). Built-in keywords expand on decode to canonical SNOMED CT / LOINC / `cycle-log` codings; for any non-built-in escape concept (including SNOMED CT, LOINC, RxNorm, ICD-10-CM, ATC, NDC, or app URIs), `display` and `text` are preserved for offline readability. - **`CustomSeries.valueType` & `CustomComponent.valueType`:** `"boolean"` (`Observation.valueBoolean`), `"coded"` (`Observation.valueCodeableConcept`), `"quantity"` (`Observation.valueQuantity` decimal in UCUM `unit`, ≤ 6 decimals), or `"components"` (`Observation.component[]`, series-level only; each component has `"boolean"`, `"coded"`, or `"quantity"`). --- ## Integration Verification Checklist (For Agents) After adding offline sharing to an app, verify all of the following: 1. **Offline check:** Disconnect network / block external fetches; confirm `codecs/1.wasm` and QR generation work from local app assets. 2. **Round-trip check:** Encode your app's exported `CycleLog` JSON → `pack()` → `bytesToDigits()` → `digitsToBytes()` → `parse()` → `shc_decode()`; verify status `0`, expected FHIR resource counts, dates, exact `0.01°` temps, doses, and exclusion flags. 3. **Refusal handling:** Confirm your UI gracefully surfaces `shc_encode` status `1` (invalid field) and status `3` (card exceeds budget) without crashing. 4. **QR density check:** Test with a realistic user dataset across your target date span (days, months, or years); verify card bytes fit your target QR version (≤ 949 B for Version 22-L or ≤ 1215 B for Version 25-L with viewer link) or trigger omission-only reduction with `reduced: true`. 5. **Scanner interoperability:** Scan a generated QR code with a standard iOS/Android camera and confirm it opens cleanly in https://joshuamandel.com/shc2-poc/view/ (or your app's own `shc2:/` handler). --- ## Measured Sample Records (All 20) | Sample | Card bytes | QR (viewer link) | FHIR JSON | Model URL | |---|---:|---|---:|---| | `power-tracker` | 1,259 B | Version 26-L | 1120 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/power-tracker.model.json | | `copper-iud` | 321 B | Version 13-L | 248 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/copper-iud.model.json | | `pcos` | 298 B | Version 12-L | 158 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/pcos.model.json | | `minimal` | 34 B | Version 4-L | 19 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/minimal.model.json | | `perimenopause` | 713 B | Version 19-L | 488 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/perimenopause.model.json | | `combined-pill` | 260 B | Version 11-L | 211 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/combined-pill.model.json | | `near-empty` | 17 B | Version 4-L | 3 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/near-empty.model.json | | `own-vocabulary` | 1,624 B | Version 30-L | 829 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/own-vocabulary.model.json | | `wellness-diary` | 1,873 B | Version 32-L | 745 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/wellness-diary.model.json | | `calendar-only` | 55 B | Version 5-L | 25 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/calendar-only.model.json | | `smart-cup-hmb` | 347 B | Version 13-L | 278 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/smart-cup-hmb.model.json | | `wearable` | 704 B | Version 19-L | 276 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/wearable.model.json | | `post-ablation` | 474 B | Version 16-L | 233 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/post-ablation.model.json | | `vitals-follow-up` | 728 B | Version 19-L | 475 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/vitals-follow-up.model.json | | `timestamped` | 1,976 B | Version 33-L | 547 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/timestamped.model.json | | `bp-twice-daily` | 1,830 B | Version 32-L | 713 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/bp-twice-daily.model.json | | `med-doses` | 1,259 B | Version 26-L | 488 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/med-doses.model.json | | `bbt-exclusions-and-fever` | 612 B | Version 18-L | 298 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/bbt-exclusions-and-fever.model.json | | `text-tags` | 1,410 B | Version 28-L | 726 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/text-tags.model.json | | `offline-displays` | 733 B | Version 19-L | 480 KB | https://joshuamandel.com/shc2-poc/codecs/cycle-log/examples/offline-displays.model.json | --- ## SHA-256 Extension Codecs (`0x00 || sha256(wasm)`) Any unregistered clinical domain can ship a zero-import WebAssembly codec addressed directly by SHA-256 (`pack({ codec: { sha256 }, input })`, 33-byte header + 2-byte SHA-256 check). Viewers fetch the module from `https://joshuamandel.com/shc2-poc/codecs/sha256/.wasm`, verify its SHA-256 digest, and run it in the same sandbox: | Codec | WASM Size | Card Size Range | SHA-256 | Hub URL | Samples | |---|---:|---:|---|---|---| | `ecg-strip` | 42,742 B | 1,406–2,128 B | `b37fa36f53a0e4818c8456be8ee7fe0532806a20fb35772607f38938e6ffb75c` | https://joshuamandel.com/shc2-poc/codecs/ecg-strip/ | `nsr`, `afib`, `bigeminy`, `lbbb`, `paced`, `vtach`, `av-block`, `stemi` | | `cgm-agp` | 43,565 B | 519–1,895 B | `f57b5d846fea9c2ad54a06b77b9c48458d88b367610b0788997e7e00a4e58dac` | https://joshuamandel.com/shc2-poc/codecs/cgm-agp/ | `libre-14d`, `libre-7d-exact`, `t1d-variable-14d`, `clinic-3d-compact` | | `ips-summary` | 243,809 B | 109–322 B | `47dbedbe2b671d9751de871f22506ebc0120da1ea798a26f113c6da61df98e74` | https://joshuamandel.com/shc2-poc/codecs/ips-summary/ | `complex-multimorbid`, `pediatric-asthma`, `prenatal-summary`, `healthy-minimal` | | `dental-chart` | 38,290 B | 147–248 B | `5068296198af4824ac326e7f50718830b2552e5456a37518d7f1d26d76947335` | https://joshuamandel.com/shc2-poc/codecs/dental-chart/ | `stage3-periodontitis`, `restorative-implants`, `caries-recall`, `healthy-adult` | | `pgx-cpic` | 44,707 B | 88–92 B | `8a0e73db854b448f7b4975d42c1917b1fa563c1055f232333b705349bdf36f3f` | https://joshuamandel.com/shc2-poc/codecs/pgx-cpic/ | `high-risk-multi`, `cardio-warfarin`, `oncology-immuno`, `all-normal-14` | | `vision-rx` | 29,823 B | 70–200 B | `7e6ae21f82b4f2bc5c9046d0416d2870bdbbf869401b90a645577e5aac3f9cd0` | https://joshuamandel.com/shc2-poc/codecs/vision-rx/ | `progressive-prism`, `toric-contacts`, `glasses-plus-contacts`, `simple-myopia` | - **`ecg-strip` (ECG Rhythm Strip)** — Lossless 1D signal codec (LPC + Golomb-Rice). WASM (42,742 B): https://joshuamandel.com/shc2-poc/codecs/sha256/b37fa36f53a0e4818c8456be8ee7fe0532806a20fb35772607f38938e6ffb75c.wasm · Hub: https://joshuamandel.com/shc2-poc/codecs/ecg-strip/ · Model: https://joshuamandel.com/shc2-poc/codecs/ecg-strip/model.d.ts.txt - **`cgm-agp` (CGM & Ambulatory Glucose Profile)** — Lossless time-series + deterministic FHIR summary synthesizer. WASM (43,565 B): https://joshuamandel.com/shc2-poc/codecs/sha256/f57b5d846fea9c2ad54a06b77b9c48458d88b367610b0788997e7e00a4e58dac.wasm · Hub: https://joshuamandel.com/shc2-poc/codecs/cgm-agp/ · Model: https://joshuamandel.com/shc2-poc/codecs/cgm-agp/model.d.ts.txt - **`ips-summary` (International Patient Summary (IPS))** — Embedded 8,207-concept SNOMED CT IPS + EDQM + LOINC dictionary. WASM (243,809 B): https://joshuamandel.com/shc2-poc/codecs/sha256/47dbedbe2b671d9751de871f22506ebc0120da1ea798a26f113c6da61df98e74.wasm · Hub: https://joshuamandel.com/shc2-poc/codecs/ips-summary/ · Model: https://joshuamandel.com/shc2-poc/codecs/ips-summary/model.d.ts.txt - **`dental-chart` (Dental & Periodontal Exam)** — 2D spatial anatomical differential coding (32 teeth × 6 sites). WASM (38,290 B): https://joshuamandel.com/shc2-poc/codecs/sha256/5068296198af4824ac326e7f50718830b2552e5456a37518d7f1d26d76947335.wasm · Hub: https://joshuamandel.com/shc2-poc/codecs/dental-chart/ · Model: https://joshuamandel.com/shc2-poc/codecs/dental-chart/model.d.ts.txt - **`pgx-cpic` (Pharmacogenomics (CPIC Panel))** — Embedded CPIC knowledge base + deterministic CDS expansion. WASM (44,707 B): https://joshuamandel.com/shc2-poc/codecs/sha256/8a0e73db854b448f7b4975d42c1917b1fa563c1055f232333b705349bdf36f3f.wasm · Hub: https://joshuamandel.com/shc2-poc/codecs/pgx-cpic/ · Model: https://joshuamandel.com/shc2-poc/codecs/pgx-cpic/model.d.ts.txt - **`vision-rx` (Vision Prescription)** — Bit-packed clinical quantizer (quarter-diopter optical fields). WASM (29,823 B): https://joshuamandel.com/shc2-poc/codecs/sha256/7e6ae21f82b4f2bc5c9046d0416d2870bdbbf869401b90a645577e5aac3f9cd0.wasm · Hub: https://joshuamandel.com/shc2-poc/codecs/vision-rx/ · Model: https://joshuamandel.com/shc2-poc/codecs/vision-rx/model.d.ts.txt --- ## Docs - [Full Bundled Spec for LLMs](https://joshuamandel.com/shc2-poc/llms-full.txt): Single-file bundle containing this guide plus verbatim `model.d.ts`, `CODEC-ABI.md`, `PRINCIPLES.md`, and `LIFT.md`. - [Architecture & Data Flow](https://joshuamandel.com/shc2-poc/reference/architecture/): Four SVG diagrams covering end-to-end flow, lifting vs. input model vs. omission-only planning, codec internals, and benchmarks. - [Input Model Reference](https://joshuamandel.com/shc2-poc/codecs/cycle-log/input-model/): Visual inventory diagram, grouped field cards, object shapes, built-in vocabularies, and validation rules. - [For Developers](https://joshuamandel.com/shc2-poc/developers/): Runnable browser/Node/Bun end-to-end example (`developers/example/`), refusal table, and receiver steps. - [Codec Directory & Registry](https://joshuamandel.com/shc2-poc/codecs/): Registered codec IDs, module SHA-256 hashes, and per-codec hubs. - [cycle-log Codec Hub](https://joshuamandel.com/shc2-poc/codecs/cycle-log/): Interactive tools (`import/`, `lab/`, `explain/`, `fit/`), sample records, and `cycle-log` CodeSystem. - [FHIR Profiles (cycle-log)](https://joshuamandel.com/shc2-poc/codecs/cycle-log/profiles/): Closed FHIR R4 StructureDefinitions and ValueSets defining the exact Bundle contract. - [Principles](https://joshuamandel.com/shc2-poc/reference/principles/): How this is meant to work: the statements the design, the model, the profiles and the pages are held to. - [Design](https://joshuamandel.com/shc2-poc/reference/design/): The design: digits in the QR, the card, the codec, what has been measured and what is still open. - [Codec interface](https://joshuamandel.com/shc2-poc/reference/codec-abi/): What a codec module must export and guarantee, and what a host does to run one. - [Build & files (README)](https://joshuamandel.com/shc2-poc/codecs/cycle-log/readme/): The cycle-log codec's source layout, build commands, tests, and measurements for each sample record. - [Model design](https://joshuamandel.com/shc2-poc/codecs/cycle-log/model/): The model's design: what it carries and why, the evidence for the built-in vocabulary, the samples and the measurements. - [FHIR mapping](https://joshuamandel.com/shc2-poc/codecs/cycle-log/mapping/): How each fact of the model becomes FHIR resources, with every code used and how it was checked. - [Wire format](https://joshuamandel.com/shc2-poc/codecs/cycle-log/format/): The bit-level format: the range coder, its probability models and the order of the walk, precise enough to reimplement. - [What the model carries](https://joshuamandel.com/shc2-poc/codecs/cycle-log/expressiveness/): What common tracking apps record, field by field, and which of it the model carries, approximates or leaves out. - [Lifting and fitting](https://joshuamandel.com/shc2-poc/codecs/cycle-log/lift/): Reading any FHIR Bundle into the model with a report on every resource, and reducing a record step by step to fit a QR code (experimental). - [Reductions measured](https://joshuamandel.com/shc2-poc/codecs/cycle-log/reductions/): Each kind of reduction step measured on the samples: the bytes it saves and what it changes or leaves out. ## Raw Machine-Readable Files - [codecs/1.wasm](https://joshuamandel.com/shc2-poc/codecs/1.wasm): Production `cycle-log` WebAssembly codec (353,251 bytes, SHA-256 `f2811c67a352393f632482b61756815b4d99dc574b070ebb9fb9a89b046a0f68`). - [lib/shc2.js](https://joshuamandel.com/shc2-poc/lib/shc2.js): Zero-dependency ES module for QR digits, card framing, codec host, and SVG QR rendering. - [codecs/cycle-log/model.d.ts.txt](https://joshuamandel.com/shc2-poc/codecs/cycle-log/model.d.ts.txt): Normative TypeScript type definitions (1000 lines). - [codecs/cycle-log/model.schema.json](https://joshuamandel.com/shc2-poc/codecs/cycle-log/model.schema.json): Derived JSON Schema 2020-12. - [CodeSystem/cycle-log.json](https://joshuamandel.com/shc2-poc/CodeSystem/cycle-log.json): FHIR R4 CodeSystem for `cycle-log` concepts. - [registry.json](https://joshuamandel.com/shc2-poc/registry.json): Machine-readable codec registry. - [GitHub Repository](https://github.com/jmandel/shc2-poc): Full Rust codec source, TypeScript lifter/planner, profiles generator, and test suites (MIT license). --- ================================================================================ APPENDIX A: NORMATIVE TYPE DEFINITIONS (codecs/cycle-log/model.d.ts) ================================================================================ ```ts /** * cycle-log model: the input of the cycle-log codec. * * This file is the NORMATIVE definition of the model JSON that an app exports and * the codec encodes into one QR code: consumer menstrual-cycle tracking spanning * up to 10,000 days. It contains only types and their documentation. * `model.schema.json` (JSON Schema 2020-12) is derived from it; where the two * differ, this file and `validate()` in `model.ts` win. * Published at https://joshuamandel.com/shc2-poc/codecs/cycle-log/model.d.ts * * Conventions * - Per-day series are flat arrays of `{ date, ... }` entries, where `date` is a * FHIR `DateTime` (`YYYY-MM-DD` or `YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM)` in * 2000-01-01..2099-12-31). Across all daily series, intervals and answers, the * earliest to latest recorded date spans at most 10,000 days. * - NOT RECORDED is an omitted entry or an absent / empty / `null` optional field. * Absence never means "no". Canonical form omits absent and empty optional fields. * - An EXPLICIT NEGATIVE is always its own value ("no-bleeding", pain 0, * sex "none", a medication "not-taken", a boolean `false`, ...). * - Concepts use readable built-in keywords in built-in slots (`SymptomKind`, * `MedicationKind`, `ConditionKind`, `Mucus`, `Sex`, `Mood`, `Energy`, * `ProcedureKind`, `IntervalKind`, `ExcludeReason`, coded `Answer` values), and * standard FHIR R4 `CodeableConcept` objects (`{ coding: [Coding]; text?: string }` * or text-only `{ text: string }`) everywhere else and as escapes. * For built-in concepts, `coding[0].display` is optional on input and stripped in * canonical form, and `text` is not allowed. For any non-built-in escape coding * (whether SNOMED CT, LOINC, RxNorm, ICD-10-CM, ATC, NDC, or an app URI), both * `coding[0].display` and `text` are preserved and must agree across all * occurrences of the same `(system, code)`. Text-only `{ text }` concepts carry * user or app tags without requiring a synthetic code-system URI. * - Integer fields (`pain`, `volume`, `sleep`, numeric `answers`) are integers, * written in JSON as -?(0|[1-9][0-9]*). Decimal fields (`bbt` and `skinTemp` * to 2 decimal places; medication doses and custom quantities to 6 decimal * places) are natural decimals -?(0|[1-9][0-9]*)(\.[0-9]+)? (no scientific * notation, no "-0"). * - Order inside arrays is free; the codec sorts canonically. * - Identical entries and entries that disagree on the same date or time are all * carried, each its own fact, never merged (except overlapping/touching * intervals of the same state). * - Objects carry only the fields listed here; any other field is an error. * * Tags: `@minimum` / `@maximum` bound a number; `@maxLength` bounds a string in * Unicode code points; `@maxItems` bounds an array; `@code` is the concept a * built-in keyword stands for. */ /* ======================================================================== */ /* The model */ /* ======================================================================== */ /** One card: consumer cycle tracking as uniform dated arrays. An empty object `{}` is valid. */ export interface CycleLog { /** * Who the card is about, kept deliberately small. Not recorded: absent or empty; * the card then carries no identity at all. */ patient?: PatientInfo; /** The source app: its name and optional version. Not recorded: absent. */ source?: Source; /** * When the card was exported, as a FHIR instant with UTC offset (mapped to * FHIR `Bundle.timestamp`). Not recorded: absent. */ exportedAt?: FhirInstant; /** * The sender deliberately left out data to fit a size: a series, time of day, or * display that is absent may have been tracked; recorded values are never altered. * It says nothing about what was left out. Not reduced: false or absent (omitted * canonically). Written as the Bundle tag SUBSETTED. */ reduced?: boolean; /** * Conditions the person reports having (background context such as PCOS or * fibroids). Not recorded: [] or absent. Explicit negative: status "resolved". * A condition stated more than once (even differently) is carried as stated. */ conditions?: ConditionEntry[]; /** * Menstrual bleeding entries. Omitted dates: not recorded. Explicit negative: * "no-bleeding" (or "flow-none"). */ bleeding?: ObservationEntry[]; /** * Collected menstrual fluid entries, whole mL (a smart or graduated cup). Fluid, * not blood: the blood fraction varies widely between people, so a fluid volume * does not establish a blood loss. Independent of `bleeding`: neither implies * the other. Omitted dates: not recorded. Explicit negative: 0. * @minimum 0 * @maximum 500 */ volume?: ObservationEntry[]; /** * Pain entries on a 0-10 numeric rating scale (LOINC 72514-3). Omitted dates: * not recorded. Explicit negative: 0 ("no pain"). Another scale goes in a custom * series. * @minimum 0 * @maximum 10 */ pain?: ObservationEntry[]; /** * Symptoms present on each date: a built-in keyword (`SymptomKind`) or any FHIR * `CodeableConcept` as an escape (presence only; for severity use a custom coded * series). Omitted dates: not recorded. There is no explicit "symptom absent". */ symptoms?: ObservationEntry[]; /** Basal body temperature (waking readings). Not recorded: absent. */ bbt?: Bbt; /** * Nightly skin or wrist temperature from a wearable (one device per card). * Never pooled with BBT. Not recorded: absent. */ skinTemp?: SkinTemp; /** Cervical mucus entries. Omitted dates: not recorded. "dry" is a value. */ mucus?: ObservationEntry[]; /** LH (ovulation) test result entries. Omitted dates: not recorded. Explicit negative: "negative". */ ovulationTest?: ObservationEntry[]; /** Progesterone (PdG) urine test result entries. Omitted dates: not recorded. Explicit negative: "negative". */ progesteroneTest?: ObservationEntry[]; /** Pregnancy test result entries. Omitted dates: not recorded. Explicit negative: "negative". */ pregnancyTest?: ObservationEntry[]; /** Sexual intercourse entries. Omitted dates: not recorded. Explicit negative: "none". */ sex?: ObservationEntry[]; /** Mood entries on a 7-point valence scale. Omitted dates: not recorded. Other mood scales or multi-select moods go in a custom series. */ mood?: ObservationEntry[]; /** Energy entries on a 4-point scale. Omitted dates: not recorded. */ energy?: ObservationEntry[]; /** * Minutes of sleep ending on each date (attributed to the wake day). Omitted * dates: not recorded. 0 is a value (no sleep). * @minimum 0 * @maximum 1440 */ sleep?: ObservationEntry[]; /** * Contraceptive pill log entries. Which pill is named by the contraception * interval covering the date. Omitted dates: not recorded. Explicit negative: * "missed". */ pill?: ObservationEntry[]; /** * Medication entries (a dose taken twice is two entries with their timestamps). * Built-in keywords: `MedicationKind`; any other product (RxNorm, SNOMED CT, * text-only, ...) is an escape `CodeableConcept`. Omitted dates: not recorded. * Explicit negative: status "not-taken" (a missed dose). */ medications?: MedEntry[]; /** * States that last over a range of calendar dates: contraception, pregnancy, * breastfeeding, or any other coded or text-only state. Not recorded: [] or absent. * Explicit negative for contraception: kind "none". Intervals of one state that * overlap or touch are one interval: normalize merges them. * @maxItems 256 */ intervals?: Interval[]; /** * Procedures: partial date (`YYYY`, `YYYY-MM`), full date (`YYYY-MM-DD`), or full * date with time (`YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM)`), year 1900-2150. Not * recorded: [] or absent. A procedure listed twice is two procedures. * @maxItems 512 */ procedures?: Procedure[]; /** * Screening questions the person answered, each with the date (and optional time) * they answered it. What they said, never a value computed from the log. Not * recorded: [] or absent. A question answered more than once (even differently, * at one time) is carried as answered. */ answers?: Answer[]; /** * Series without a built-in slot, each with its own Observation `CodeableConcept` * and one of four `valueType` kinds (`"boolean"`, `"coded"`, `"quantity"`, or * `"components"` for multi-component readings like blood pressure). Not recorded: * [] or absent. One series per distinct `code`. * @maxItems 32 */ custom?: CustomSeries[]; } /* ======================================================================== */ /* Shared shapes */ /* ======================================================================== */ /** * A standard FHIR Coding from any code system. For built-in concepts, `display` is * optional on input and stripped in canonical form. For any non-built-in escape * concept (including SNOMED CT, LOINC, RxNorm, ICD-10-CM, ATC, NDC, or app URIs), * `display` is carried and all occurrences of the same `(system, code)` must agree * on the same display text. */ export interface Coding { /** * Code system URI: absolute URI of printable ASCII without spaces or "|", 1-255 characters. * @maxLength 255 * @example "http://snomed.info/sct" * @example "http://www.nlm.nih.gov/research/umls/rxnorm" */ system: string; /** * Concept code within `system`: 1-128 characters, no control characters, no * leading/trailing/repeated spaces. SNOMED CT codes must be valid 6-18 digit * concept ids (Verhoeff check digit, partition 00 or 10). * @maxLength 128 * @example "25064002" * @example "314076" */ code: string; /** * Optional human-readable display text (1-128 characters, no control characters * or leading/trailing whitespace). Carried for any non-built-in escape concept; * optional on input and stripped in canonical form for built-in concepts. * @maxLength 128 * @example "Essential hypertension" */ display?: string; } /** * A FHIR R4 CodeableConcept: either a single `Coding` with optional plain-text * `text`, or a text-only concept `{ text }` with no `coding` (no synthetic URI * required). For built-in concepts, `coding[0].display` is optional on input and * stripped in canonical form, and `text` is not allowed. For any non-built-in * escape coding, both `coding[0].display` and `text` are preserved and must agree * across all occurrences of the same `(system, code)`. */ export type CodeableConcept = | { coding: [Coding]; text?: string } | { text: string }; /** * A calendar date YYYY-MM-DD from 2000-01-01 to 2099-12-31 (real Gregorian date). * Used for interval start and end bounds. * @example "2026-01-05" */ export type CalendarDate = string; /** * A FHIR dateTime on the daily tracking timeline (2000-01-01 to 2099-12-31): * either a calendar date `YYYY-MM-DD` (day precision) or a date with local time * and quarter-hour UTC offset `YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM)`. `"Z"` is * accepted and normalized to `"+00:00"`; `":00"` seconds are accepted and omitted * canonically; `"-00:00"` is rejected. * @example "2026-01-05" * @example "2026-01-05T07:30-05:00" * @example "2026-01-05T22:15:42+01:00" */ export type DateTime = string; /** * A FHIR date of year, month or day precision: YYYY, YYYY-MM or YYYY-MM-DD, from * 1900 to 2150. Used for patient birth date and condition onset. * @example "2019" * @example "2023-05" * @example "2021-11-30" */ export type FhirDate = string; /** * A FHIR dateTime for procedures (year 1900 to 2150): `YYYY`, `YYYY-MM`, * `YYYY-MM-DD`, or `YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM)`. `"Z"` is accepted and * normalized to `"+00:00"`; `":00"` seconds are omitted canonically; `"-00:00"` is * rejected. * @example "2021-04" * @example "2026-01-29T10:30-05:00" */ export type FhirDateTime = string; /** * A FHIR instant with calendar date (2000-01-01 to 2099-12-31), time of day, * optional seconds and quarter-hour UTC offset: `YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM)`. * `"Z"` is accepted and normalized to `"+00:00"`; `":00"` seconds are omitted * canonically; `"-00:00"` is rejected. FHIR `Bundle.timestamp` always emits seconds. * @example "2026-12-04T14:30-06:00" * @example "2026-12-04T14:30:15+00:00" */ export type FhirInstant = string; /** * One observation entry in a flat series array: a `DateTime` (day or timestamp) * and its value. Identical entries and entries that disagree on the same date or * time are all carried, each its own fact, never merged. */ export interface ObservationEntry { /** When the observation was recorded: calendar date or date with time and UTC offset. */ date: DateTime; /** The recorded value. */ value: T; } /** A built-in keyword shortcut or, as an escape, any FHIR `CodeableConcept`. */ export type Coded = T | CodeableConcept; /** Optional identity: deliberately small. An empty object means no identity. */ export interface PatientInfo { /** * Family name. Not recorded: absent. * @maxLength 64 */ family?: string; /** * Given names, in order. Not recorded: absent or []. * Each 1-64 characters. * @maxItems 3 */ given?: string[]; /** * Birth date, from 1900 to 2150. A year alone is enough to give age without * identity. Not recorded: absent. */ birthDate?: FhirDate; } /** The exporting app, shown as the source device of every observation. */ export interface Source { /** * The app's name as users know it, 1-64 characters. * @maxLength 64 * @example "FertilityApp" */ name: string; /** * The app's version, 1-32 characters. Not recorded: absent. * @maxLength 32 */ version?: string; } /** A condition the person reports. */ export interface ConditionEntry { /** The condition: a built-in keyword (`ConditionKind`) or any FHIR `CodeableConcept` as an escape. */ code: ConditionKind | CodeableConcept; /** What the person says about it now. Not stated: absent. */ status?: ConditionStatus; /** When it started, as precisely as the person says (1900-2150). Not stated: absent. */ onset?: FhirDate; } /** Built-in disturbance/exclusion reason on a BBT or skinTemp reading. */ export type ExcludeReason = /** Fever or acute febrile illness. */ | "fever" /** Alcohol consumption the previous evening. */ | "alcohol" /** Poor, broken, or unusually short sleep. */ | "poor-sleep" /** Woke significantly later (or earlier) than usual. */ | "late-wake" /** Travel or time-zone shift. */ | "travel" /** Acute stress. */ | "stress" /** Medication affecting basal temperature. */ | "medication" /** Other unspecified disturbance. */ | "other"; /** One temperature reading with date/time and optional disturbance/exclusion flag. */ export interface TempEntry { /** When the reading was taken: calendar date or date with time and UTC offset. */ date: DateTime; /** Temperature in natural degrees of the series unit, at most 2 decimal places (e.g. 36.52). */ value: number; /** True when the user or app marked this reading disturbed/excluded from thermal-shift interpretation. */ excluded?: boolean; /** Optional coded or text-only reason for exclusion (only allowed when `excluded` is true). */ excludeReason?: ExcludeReason | CodeableConcept; } /** Basal body temperature readings (0.01 °C / 0.01 °F precision, distinct from LOINC 8310-5 general body temperature). */ export interface Bbt { /** Unit of every reading. */ unit: TemperatureUnit; /** * Readings in natural degrees of `unit` (at most 2 decimal places, e.g. 36.52). * Cel 34-42, [degF] 93-107.6. */ entries: TempEntry[]; } /** Wearable nightly temperature from one device. */ export interface SkinTemp { /** Whether values are deviations from the device's baseline or absolute temperatures. */ kind: SkinTempKind; /** Unit of every value. For a deviation, a temperature difference in this unit. */ unit: TemperatureUnit; /** * Readings by wake date, in natural degrees of `unit` (at most 2 decimal places, * e.g. -0.31). Deviation: Cel -5..5, [degF] -9..9. Absolute: Cel 25..40, * [degF] 77..104. */ entries: TempEntry[]; } /** Exact positive decimal medication dose in a UCUM unit. */ export interface MedDose { /** * Strictly positive decimal dose below 1,000,000,000, with at most 6 decimal * places (e.g. 400, 12.5). * @minimum 0.000001 * @maximum 999999999.999999 */ value: number; /** * UCUM unit code (printable ASCII, no spaces, e.g. "mg", "ug", "mL", "[iU]"). * @maxLength 64 * @example "mg" */ unit: string; } /** One medication entry on a date or timestamp. */ export interface MedEntry { /** When the medication was taken (or missed): calendar date or date with time and UTC offset. */ date: DateTime; /** The product: a built-in keyword (`MedicationKind`) or any FHIR `CodeableConcept` as an escape. */ code: MedicationKind | CodeableConcept; /** Whether it was taken. */ status: MedStatus; /** Optional exact dose taken (maps to MedicationStatement.dosage[0].doseAndRate[0].doseQuantity). */ dose?: MedDose; } /** A state over a range of calendar dates. */ export type Interval = BuiltinInterval | CodedInterval; /** A built-in state over a range of calendar dates. */ export interface BuiltinInterval { /** Which state. */ kind: IntervalKind; /** First calendar date. */ start: CalendarDate; /** Last calendar date (inclusive), not before `start`. */ end: CalendarDate; } /** Any other state: an observation code and a coded or text-only value, over a range of calendar dates. */ export interface CodedInterval { /** * What is observed (an Observation `CodeableConcept`), e.g. LOINC 8659-5 "Birth * control method". Not a built-in per-day series code and not an R4 vital-sign code. */ code: CodeableConcept; /** The state, e.g. LOINC LA27913-5 (diaphragm or cervical cap) or a text-only concept. */ value: CodeableConcept; /** First calendar date. */ start: CalendarDate; /** Last calendar date (inclusive), not before `start`. */ end: CalendarDate; } /** A completed procedure on a date or dateTime. */ export interface Procedure { /** When: YYYY, YYYY-MM, YYYY-MM-DD, or YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM) (year 1900-2150). */ date: FhirDateTime; /** Which procedure: a built-in keyword (`ProcedureKind`) or any FHIR `CodeableConcept`. */ code: ProcedureKind | CodeableConcept; } /** A screening question answered on a date or timestamp. */ export interface Answer { /** When the person answered: calendar date or date with time and UTC offset. */ date: DateTime; /** Which question. */ question: Question; /** * The answer: for a coded question its built-in answer name or any FHIR * `CodeableConcept` as an escape; for a numeric question an integer in the * question's range. See `Question`. */ value: string | number | CodeableConcept; } /** A series without a built-in slot. */ export type CustomSeries = CustomBooleanSeries | CustomCodedSeries | CustomQuantitySeries | CustomComponentsSeries; /** Yes / no entries (also events: only `true`). */ export interface CustomBooleanSeries { /** * The Observation `CodeableConcept`. Not a built-in series code. An R4 vital-sign * code makes the series a vital sign (category vital-signs); a code with its own * R4 profile needs that profile's valueType and unit (`VITAL_SIGN_PROFILES`). */ code: CodeableConcept; /** FHIR Observation value type: boolean (`Observation.valueBoolean`). */ valueType: "boolean"; /** Entries with boolean values (false is an explicit negative). */ entries: ObservationEntry[]; } /** Coded or text-only entries: categorical, ordinal or multi-select alike (each entry is one fact). */ export interface CustomCodedSeries { /** * The Observation `CodeableConcept`. Not a built-in series code. An R4 vital-sign * code makes the series a vital sign (category vital-signs); a code with its own * R4 profile needs that profile's valueType and unit (`VITAL_SIGN_PROFILES`). */ code: CodeableConcept; /** FHIR Observation value type: coded or text-only (`Observation.valueCodeableConcept`). */ valueType: "coded"; /** * Entries with FHIR `CodeableConcept` values (each one fact). Level order is not * carried, so displays or text should state the rank ("3 of 5"). */ entries: ObservationEntry[]; } /** Natural decimal quantity entries in a UCUM unit (at most 6 decimal places). */ export interface CustomQuantitySeries { /** * The Observation `CodeableConcept`. Not a built-in series code. An R4 vital-sign * code makes the series a vital sign (category vital-signs); a code with its own * R4 profile needs that profile's valueType and unit (`VITAL_SIGN_PROFILES`). */ code: CodeableConcept; /** FHIR Observation value type: decimal quantity in UCUM `unit` (`Observation.valueQuantity`). */ valueType: "quantity"; /** * UCUM unit code (printable ASCII, no spaces). * @maxLength 64 * @example "mg" * @example "{steps}" */ unit: string; /** * Entries with natural decimal numbers below 1,000,000,000 in magnitude and at * most 6 decimal places. 0 is a value. * @minimum -999999999.999999 * @maximum 999999999.999999 */ entries: ObservationEntry[]; } /** * A reading of several components, written as one Observation with a `component` * per recorded value and no top-level value (blood pressure: LOINC 85354-9 with * 8480-6 and 8462-4 in mm[Hg]). Nothing here is specific to blood pressure: any * code may have components. */ export interface CustomComponentsSeries { /** * The Observation `CodeableConcept`. Not a built-in series code. An R4 vital-sign * code makes the series a vital sign (category vital-signs); 85354-9 must be a * components series whose 8480-6 and 8462-4 components are quantities in mm[Hg]. */ code: CodeableConcept; /** FHIR Observation value type: multi-component reading with no top-level value (`Observation.component[]`). */ valueType: "components"; /** * The declared components, each with its own code and `valueType`. Codes differ. * Canonical order is the concepts' canonical order; a component never recorded * in any entry is dropped. * @maxItems 16 */ components: CustomComponent[]; /** The readings, each carrying its date/time and at least one recorded component value. */ entries: CustomComponentsEntry[]; } /** One component of a `CustomComponentsSeries`: one value per reading (`boolean`, `coded`, or `quantity`). */ export type CustomComponent = CustomBooleanComponent | CustomCodedComponent | CustomQuantityComponent; /** A yes / no component (`component.valueBoolean`). */ export interface CustomBooleanComponent { /** The component `CodeableConcept`. */ code: CodeableConcept; /** FHIR Observation component value type: boolean (`component.valueBoolean`). */ valueType: "boolean"; } /** A coded or text-only component: one `CodeableConcept` per reading (`component.valueCodeableConcept`). */ export interface CustomCodedComponent { /** The component `CodeableConcept`. */ code: CodeableConcept; /** FHIR Observation component value type: coded or text-only (`component.valueCodeableConcept`). */ valueType: "coded"; } /** A decimal quantity component in a UCUM unit (`component.valueQuantity`, at most 6 decimal places). */ export interface CustomQuantityComponent { /** The component `CodeableConcept`. */ code: CodeableConcept; /** FHIR Observation component value type: decimal quantity in UCUM `unit` (`component.valueQuantity`). */ valueType: "quantity"; /** * UCUM unit code (printable ASCII, no spaces). In a vital-sign series, one of the * units the R4 vital-signs profile allows for components (`UCUM_VITALS_COMMON`). * @maxLength 64 * @example "mm[Hg]" */ unit: string; } /** One multi-component reading entry on a date or timestamp. */ export interface CustomComponentsEntry { /** When the reading was taken: calendar date or date with time and UTC offset. */ date: DateTime; /** * Recorded component values (1..16). Each `code` must match a declared component * of the series, with no duplicate component code in one entry. * @maxItems 16 */ components: CustomComponentValue[]; } /** One recorded component value inside a `CustomComponentsEntry`. */ export interface CustomComponentValue { /** The component `CodeableConcept` (must match one of `series.components`). */ code: CodeableConcept; /** The component's value: boolean, `CodeableConcept`, or decimal number matching the component's `valueType`. */ value: boolean | CodeableConcept | number; } /* ======================================================================== */ /* Enumerations */ /* ======================================================================== */ /** Menstrual bleeding on one day: the legal combinations of bleeding and flow. */ export type Bleeding = /** Explicitly no bleeding. */ | "no-bleeding" /** Explicitly no bleeding, logged on a flow scale's "none" option. */ | "flow-none" /** Bleeding, amount not recorded. */ | "bleeding" /** Bleeding, flow category spotting (also bleeding between periods with no amount). */ | "spotting" /** Bleeding, flow category light. */ | "light" /** Bleeding, flow category moderate (medium). */ | "moderate" /** Bleeding, flow category heavy. */ | "heavy"; /** Cervical mucus, as self-observed. */ export type Mucus = /** No mucus; feels dry. */ | "dry" /** Sticky, tacky or crumbly. */ | "sticky" /** Creamy, lotion-like. */ | "creamy" /** Watery, wet. */ | "watery" /** Clear and stretchy, like raw egg white. */ | "egg-white"; /** LH (ovulation) urine test result. */ export type OvulationTest = /** No surge detected. */ | "negative" /** LH surge detected (a positive test). */ | "lh-surge" /** Estrogen rise detected (high fertility on two-hormone tests). */ | "estrogen-surge" /** The result could not be read. */ | "indeterminate"; /** A urine test result (progesterone or pregnancy). */ export type TestResult = /** Negative. */ | "negative" /** Positive. */ | "positive" /** The result could not be read. */ | "indeterminate"; /** Sexual intercourse on one day. */ export type Sex = /** Explicitly no intercourse. */ | "none" /** Intercourse with protection (e.g. a condom). */ | "protected" /** Intercourse without protection. */ | "unprotected" /** Intercourse, protection not recorded. */ | "unspecified"; /** Mood valence, 7 points (Apple HealthKit State of Mind). */ export type Mood = /** 1 of 7. */ | "very-unpleasant" /** 2 of 7. */ | "unpleasant" /** 3 of 7. */ | "slightly-unpleasant" /** 4 of 7, neither pleasant nor unpleasant. */ | "neutral" /** 5 of 7. */ | "slightly-pleasant" /** 6 of 7. */ | "pleasant" /** 7 of 7. */ | "very-pleasant"; /** Energy, 4 points (Clue). */ export type Energy = /** 1 of 4. */ | "exhausted" /** 2 of 4. */ | "low" /** 3 of 4. */ | "high" /** 4 of 4. */ | "energized"; /** Contraceptive pill log for one day. */ export type PillLog = /** The pill was taken. */ | "taken" /** The pill was missed (explicit negative). */ | "missed"; /** Whether a medication was taken on a day. */ export type MedStatus = /** Taken. */ | "taken" /** Explicitly not taken (a missed dose). */ | "not-taken"; /** Temperature unit (UCUM). */ export type TemperatureUnit = /** Degrees Celsius. */ | "Cel" /** Degrees Fahrenheit. */ | "[degF]"; /** What a wearable temperature value means. */ export type SkinTempKind = /** Difference from the device's own baseline (Oura, Fitbit, Garmin); signed. */ | "deviation" /** Absolute nightly skin or wrist temperature (Apple Watch, Google, Whoop). */ | "absolute"; /** Built-in states over a range of days. Contraception values are LOINC answers to 8659-5. */ export type IntervalKind = /** Not using contraception (explicit negative). @code http://loinc.org|LA137-2 */ | "none" /** Combined oral contraceptive pill. @code http://loinc.org|LA27908-5 */ | "combined-pill" /** Progestin-only pill. @code http://loinc.org|LA27909-3 */ | "progestin-pill" /** Contraceptive patch. @code http://loinc.org|LA16581-3 */ | "patch" /** Vaginal ring. @code http://loinc.org|LA27911-9 */ | "ring" /** Injectable contraceptive. @code http://loinc.org|LA27907-7 */ | "injection" /** Contraceptive implant. @code http://loinc.org|LA27901-0 */ | "implant" /** Hormonal (progestin) IUD. @code http://loinc.org|LA27902-8 */ | "hormonal-iud" /** Copper IUD. @code http://loinc.org|LA27903-6 */ | "copper-iud" /** IUD, type not recorded. @code http://loinc.org|LA27904-4 */ | "iud-unspecified" /** Male condom. @code http://loinc.org|LA27912-7 */ | "condom" /** Fertility awareness-based method. @code http://loinc.org|LA27918-4 */ | "fertility-awareness" /** Lactational amenorrhea method. @code http://loinc.org|LA27919-2 */ | "lactational-amenorrhea" /** Pregnant (LOINC 82810-3). @code http://loinc.org|LA15173-0 */ | "pregnant" /** Breastfeeding (LOINC 63895-7). @code http://loinc.org|LA29252-6 */ | "breastfeeding"; /** Built-in procedures (SNOMED CT). */ export type ProcedureKind = /** Insertion of an intrauterine device. @code 65200003 */ | "iud-insertion" /** Removal of an intrauterine device. @code 1263416007 */ | "iud-removal" /** Insertion of a contraceptive implant. @code 169553002 */ | "implant-insertion" /** Removal of a contraceptive implant. @code 301807007 */ | "implant-removal" /** Emergency contraception taken. @code 1372819003 */ | "emergency-contraception" /** Hysterectomy: afterwards absent bleeding is not amenorrhea or menopause. @code 236886002 */ | "hysterectomy" /** Endometrial ablation: afterwards little or no bleeding is expected. @code 265060005 */ | "endometrial-ablation" /** Oophorectomy (one ovary or unspecified). @code 83152002 */ | "oophorectomy" /** Bilateral oophorectomy: surgical menopause. @code 76876009 */ | "bilateral-oophorectomy" /** Myomectomy (fibroid removal). @code 42010004 */ | "myomectomy" /** Dilation and curettage. @code 11401008 */ | "d-and-c" /** Endometrial polypectomy. @code 236884004 */ | "polypectomy" /** Uterine artery embolization. @code 312138002 */ | "uterine-artery-embolization"; /** A reported condition's status, as the person states it. */ export type ConditionStatus = /** The person has it now. */ | "active" /** The person had it and it is over (explicit negative for now). */ | "resolved"; /* ======================================================================== */ /* Screening questions */ /* ======================================================================== */ /** * Screening questions (LOINC). A coded question's `value` is one of its answer * names (or any `CodeableConcept` as an escape); a numeric question's `value` is an integer. */ export type Question = /** Usual cycle length over the last year. Answer: `UsualCycleLength`. @code http://loinc.org|64700-8 */ | "usual-cycle-length" /** Number of periods per year. Answer: integer 0-100 (unit /a). @code http://loinc.org|92656-8 @minimum 0 @maximum 100 */ | "periods-per-year" /** Periods missed over the past 3 months. Answer: integer 0-3. @code http://loinc.org|65930-0 @minimum 0 @maximum 3 */ | "missed-periods-3-months" /** Had a period within the last year. Answer: `YesNo`. @code http://loinc.org|63889-0 */ | "period-in-last-year" /** Periods stopped permanently. Answer: `PeriodsStopped`. @code http://loinc.org|64701-6 */ | "periods-stopped" /** Age in years when periods stopped. Answer: integer 0-100. @code http://loinc.org|64702-4 @minimum 0 @maximum 100 */ | "age-periods-stopped" /** Age in years at the first period. Answer: integer 0-100. @code http://loinc.org|63888-2 @minimum 0 @maximum 100 */ | "age-at-menarche"; /** Answers to "usual-cycle-length". */ export type UsualCycleLength = /** Less than 21 days. @code http://loinc.org|LA14649-0 */ | "<21" /** 21-25 days. @code http://loinc.org|LA14650-8 */ | "21-25" /** 26-32 days. @code http://loinc.org|LA14651-6 */ | "26-32" /** 33-35 days. @code http://loinc.org|LA14652-4 */ | "33-35" /** 36-90 days. @code http://loinc.org|LA14653-2 */ | "36-90" /** More than 90 days. @code http://loinc.org|LA14654-0 */ | ">90" /** Too variable to say. @code http://loinc.org|LA14655-7 */ | "too-variable" /** Don't know. @code http://loinc.org|LA12688-0 */ | "dont-know"; /** Answers to "period-in-last-year". */ export type YesNo = /** Yes. @code http://loinc.org|LA33-6 */ | "yes" /** No (explicit negative). @code http://loinc.org|LA32-8 */ | "no"; /** Answers to "periods-stopped". */ export type PeriodsStopped = /** Yes, no menstrual periods. @code http://loinc.org|LA14656-5 */ | "yes-no-periods" /** Yes, but has periods now due to female hormones. @code http://loinc.org|LA14657-3 */ | "yes-hormones" /** No. @code http://loinc.org|LA32-8 */ | "no" /** Not sure. @code http://loinc.org|LA12693-0 */ | "not-sure"; /* ======================================================================== */ /* Built-in concept enums (readable keywords expanding to SNOMED / cycle-log) */ /* ======================================================================== */ /** * Built-in symptom keywords (SNOMED CT, plus `hot-flash` in `cycle-log`). * The first 14 are the starter set of the Period Tracking guide the design started from. * Any other symptom is passed as a FHIR `CodeableConcept`. */ export type SymptomKind = /** Menstrual cramp. @code 431416001 */ | "menstrual-cramp" /** Backache. @code 161891005 */ | "backache" /** Headache. @code 25064002 */ | "headache" /** Migraine. @code 37796009 */ | "migraine" /** Stomach ache. @code 271681002 */ | "stomach-ache" /** Nausea. @code 422587007 */ | "nausea" /** Breast tenderness. @code 55222007 */ | "breast-tenderness" /** Ovulation pain. @code 43548008 */ | "ovulation-pain" /** Fatigue. @code 84229001 */ | "fatigue" /** Abdominal bloating. @code 116289008 */ | "bloating" /** Depressed mood. @code 366979004 */ | "depressed-mood" /** Feeling irritable. @code 55929007 */ | "irritable" /** Stress. @code 73595000 */ | "stress" /** Dyspareunia. @code 71315007 */ | "dyspareunia" /** Acne. @code 11381005 */ | "acne" /** Pain in pelvis. @code 30473006 */ | "pelvic-pain" /** Low back pain. @code 279039007 */ | "low-back-pain" /** Pain of breast. @code 53430007 */ | "breast-pain" /** Mood swings. @code 18963009 */ | "mood-swings" /** Anxiety. @code 48694002 */ | "anxiety" /** Diarrhea. @code 62315008 */ | "diarrhea" /** Constipation. @code 14760008 */ | "constipation" /** Dizziness. @code 404640003 */ | "dizziness" /** Craving for food or drink. @code 248132003 */ | "food-craving" /** Passing clots vaginally. @code 289532003 */ | "vaginal-clots" /** Hot flash (cause not stated); a proposed code. @code https://joshuamandel.com/shc2-poc/CodeSystem/cycle-log|hot-flash */ | "hot-flash" /** Night sweats. @code 42984000 */ | "night-sweats" /** Insomnia. @code 193462001 */ | "insomnia" /** Vaginal dryness. @code 31908003 */ | "vaginal-dryness" /** Palpitations. @code 80313002 */ | "palpitations" /** Urinary incontinence. @code 165232002 */ | "urinary-incontinence" /** Memory lapses. @code 225038006 */ | "memory-lapses" /** Alopecia (hair loss). @code 56317004 */ | "hair-loss" /** Increased libido. @code 58436003 */ | "increased-libido" /** Reduced libido. @code 8357008 */ | "reduced-libido"; /** * Built-in medication keywords (SNOMED CT medicinal products). Any other product * (RxNorm, SNOMED CT, text-only, ...) is passed as a FHIR `CodeableConcept`. */ export type MedicationKind = /** Ibuprofen-containing product. @code 38268001 */ | "ibuprofen" /** Naproxen-containing product. @code 11847009 */ | "naproxen" /** Acetaminophen-containing product. @code 90332006 */ | "acetaminophen" /** Mefenamic acid-containing product. @code 34364009 */ | "mefenamic-acid" /** Tranexamic acid-containing product. @code 109006003 */ | "tranexamic-acid" /** Iron-containing product. @code 30729008 */ | "iron" /** Folic acid-containing product. @code 6247001 */ | "folic-acid"; /** * Built-in condition keywords (SNOMED CT), pending clinical review: the main * explanations of a bleeding pattern. Any other condition is passed as a FHIR * `CodeableConcept`. */ export type ConditionKind = /** Polycystic ovary syndrome. @code 237055002 */ | "pcos" /** Uterine leiomyoma (fibroids). @code 95315005 */ | "uterine-fibroids" /** Uterine adenomyosis. @code 784314006 */ | "adenomyosis" /** Endometrial polyp. @code 1237359009 */ | "endometrial-polyp" /** Endometriosis. @code 129103003 */ | "endometriosis" /** von Willebrand disorder. @code 128105004 */ | "von-willebrand-disorder" /** Blood coagulation disorder. @code 64779008 */ | "coagulation-disorder" /** Iron deficiency anemia. @code 87522002 */ | "iron-deficiency-anemia" /** Hypothyroidism. @code 40930008 */ | "hypothyroidism" /** Hyperthyroidism. @code 34486009 */ | "hyperthyroidism" /** Hyperprolactinemia. @code 237662005 */ | "hyperprolactinemia" /** Premature ovarian insufficiency. @code 237788002 */ | "premature-ovarian-insufficiency" /** Hypothalamic amenorrhea. @code 237120002 */ | "hypothalamic-amenorrhea" /** Perimenopausal state. @code 161541000119104 */ | "perimenopause" /** Postmenopausal state. @code 76498008 */ | "postmenopause"; ``` --- ================================================================================ APPENDIX B: WEBASSEMBLY CODEC INTERFACE (CODEC-ABI.md) ================================================================================ # Codec interface, version 0.1 A codec turns the compact bytes carried in a dense QR code into a FHIR Bundle. It is a WebAssembly module that can compute and do nothing else. ## What a codec is - One WebAssembly module. - **No imports** of any kind, and no start function. A host refuses a module that has either. - Three exports: | Export | Signature | Meaning | |---|---|---| | `memory` | linear memory | Has a declared maximum. | | `shc_alloc` | `(len: i32) -> i32` | Returns a pointer to `len` writable bytes, or 0 if it cannot. | | `shc_decode` | `(ptr: i32, len: i32) -> i32` | Decodes the input at `ptr`. Returns a pointer to a result record. | The result record is 12 bytes, little-endian: `status: i32`, `out_ptr: u32`, `out_len: u32`. | Status | Name | Meaning | Output | |---|---|---|---| | 0 | OK | Decoded. | The Bundle, as UTF-8 JSON. | | 1 | MALFORMED | Not a valid encoding for this codec. | A short message for logs. | | 2 | UNSUPPORTED | This codec's format, in a version or with a feature this module does not implement. | A short message. | | 3 | LIMIT | Valid, but would exceed the codec's or this interface's limits. | A short message. | Hosts act on the status, never on the message. ## What a host does 1. Checks the module: size, no imports, no start function, the three exports. 2. Creates a new instance for each card. Nothing carries over from one card to the next. 3. Calls `shc_alloc(len)`, copies the input in, calls `shc_decode`. 4. Reads the record and checks that the output lies inside memory. 5. On status 0, parses the JSON and checks it is a Bundle. A host never passes more than 4,096 bytes; no QR code holds more. An encoder never produces more: a dataset that would need more is not representable in that codec. A host lets memory grow up to the module's declared maximum. A host that refused growth earlier would reject cards that other hosts accept. If the module traps, exhausts its stack, or runs past the host's time limit, the host treats the card as MALFORMED. `shc_alloc` and `shc_decode` are each called once per instance. `shc_alloc(0)` returns a valid, non-zero pointer. ## Rules for every codec - **Total.** For every input, including random bytes, the codec returns a status. It never traps, never reads or writes outside its memory, and never loops without bound. - **Bounded.** For every input the codec finishes, and its work, memory and output are bounded by limits that follow from its own model (so many days, so many series). The codec documents those worst cases. - **Deterministic.** The same bytes always give the same output bytes. To make this checkable, a module contains no floating-point instructions, and uses only WebAssembly 1.0 plus mutable-globals, sign-extension, multi-value, and the memory instructions of bulk-memory (`memory.copy`, `memory.fill`, `memory.init`, `data.drop`). No tables beyond what function calls need, no reference types, no threads, no SIMD. - **Bounded stack.** A codec's own stack lives in its linear memory and can overflow silently. Recursion depth and stack use are bounded for every input. - **Canonical.** Each dataset has exactly one encoding: if the codec accepts a byte string, encoding its output again gives the same bytes. - **No artificial ceilings.** This interface sets no budget for instructions, time, memory or output, and a codec does not refuse a dataset because decoding it would be slow. What a host applies are safety rails set one or two orders of magnitude beyond anything a real card needs, to stop a broken or hostile module: this project's host allows an 8 MiB module, 1 GiB of memory and 256 MiB of output, and suggests stopping a decode only after tens of seconds. Tools that make cards warn when a card is unusually costly to decode or too dense to scan comfortably; they do not forbid it. ## Output - Minified UTF-8 JSON with a fixed key order, so that two implementations of a codec can be compared byte for byte. - A FHIR R4 Bundle of type `collection`. Entries have `fullUrl` values `resource:0`, `resource:1`, and so on, and refer to one another by those values. - `resource:0` is the subject of the record, a Patient, and facts refer to it. A codec whose model has no identity, or whose user chose not to include any, emits the smallest Patient that is valid FHIR (a completely empty resource is not). A host that knows who the card belongs to may replace it. ## The developer's side: a constrained input model The registry accepts only constrained codecs. General-purpose compression of arbitrary Bundles is not registered: it has no input model to write against and cannot give one encoding per dataset. Data with no codec goes in a SMART Health Link. A codec publishes three things: an input model (a JSON Schema for exactly the facts it can carry), the wire format, and the mapping from model to Bundle. Developers write against the model and never construct FHIR. - A codec module may export `shc_encode(ptr, len) -> rec`, with the same record as `shc_decode`. Its input is the model as UTF-8 JSON; its output on status 0 is the card's codec input. - An encoder refuses a model it cannot represent exactly, with status MALFORMED and a message naming the problem. It never drops or approximates. - A change to the model is a new codec, with a new id. ## Naming a codec A card begins with a codec reference: - a registry id, written as a LEB128 unsigned integer (ids 1 to 127 take one byte, ids up to 16,383 take two); or - the byte 0 followed by the 32-byte SHA-256 of the module, for a codec that is not registered. A registry id always names the same module bytes; a changed codec gets a new id. A host that meets a hash it does not have fetches the module from wherever it is offered and checks the hash before running it. ## The card around the codec input A card is the codec reference, the codec input, and a 2-byte check: the first 2 bytes of the SHA-256 of everything before it. The host verifies the check and refuses a card that fails it; the codec sees only its input. A codec's input need not detect truncation or damage on its own. ## Not decided - How a host finds the module for a hash that is not published at `https://joshuamandel.com/shc2-poc/codecs/sha256/.wasm`. - Where the safety rails should sit, once there is experience with real hosts. --- ================================================================================ APPENDIX C: DESIGN PRINCIPLES (PRINCIPLES.md) ================================================================================ # Principles for codecs and lifting How a codec, its model, and the path from an existing FHIR Bundle to a card should behave. Some of this is built; the last section says what is not yet. ## The card 1. **FHIR out, never FHIR in the QR.** A card holds a compact encoding of a narrow model. A sandboxed codec turns it into an ordinary FHIR Bundle on the receiving device. No server is involved. 2. **Developers target the model.** Each codec publishes a small, typed input model. An app fills it in and never constructs FHIR. 3. **One encoding per dataset.** The same facts always give the same bytes, and a decoder accepts only those bytes. 4. **Expected content is cheap; everything else is possible.** Built-in tables make common data small. Escapes (any code from any system, card-declared series, components) mean the tables never limit what can be said. 5. **No artificial limits.** A card is refused only when it is invalid or does not fit. Size and time get warnings at real outliers, with wide margins. ## The FHIR contract 6. **Closed profiles, derived from the model.** Each codec publishes FHIR profiles that allow exactly what its model can say and nothing else: every other element, and every extension, is constrained to zero. The profiles are generated from the model, so the two cannot drift. 7. **Conformant means it fits.** A Bundle that conforms to the codec's profiles lifts into the model exactly, and the codec's output always conforms. Differences that carry no meaning (order, ids, how a reference is spelled) are written down as a list, and only those are ignored. 8. **Modifier elements are fixed or forbidden.** Inside the profiles, every element that changes a resource's meaning has a fixed value or is not allowed, so none can be lost. Outside them, a resource with a modifier the model cannot hold is left out whole, never carried without it. 9. **Everything else is a reduction.** A Bundle that goes beyond the profiles can still be lifted, by leaving out what does not fit. That is a loss, it is reported item by item, and it marks the card. ## Reducing to fit 10. **A recorded value is changed only where that is defensible.** Rounding a clinical measurement by an amount that matters clinically is never offered. Whether any coarsening is offered, for which measure and by how much, is decided measure by measure by the project owner, from the measurement's accuracy, the differences that matter clinically, and the bytes it saves. Until a kind is approved it is not offered. 11. **Leaving things out is the default way to fit.** Named omissions: times of day, display text, explicit negatives, extra entries on a day, whole series, the oldest days. Omissions are losses too, and each kind is likewise approved by the owner. 12. **Loss is the sender's explicit choice.** Nothing is left out silently. Each step states what a reader will no longer see. 13. **A plan, not a black box.** The default takes the mildest omissions first. The result is a replayable list of steps, a frontier of alternatives, and hints a caller can set: never omit this, omit these first. When a record does not fit without omitting something central, the answer is that it does not fit. 14. **Sizes are measured.** Every candidate is encoded to see what it saves. Nothing is estimated. ## What the receiver can rely on 15. **Reduced is reduced.** Any loss, at lifting or at fitting, marks the card. 16. **An absence must be interpretable.** "Not recorded" and "explicitly none" are different and stay different. On a reduced card, an absence may also mean "not carried"; the card says only that it was reduced, not how. 17. **A reader never says more than the card does.** Retracted, provisional or negated data is shown as such or not at all. Anything computed is labelled as computed. 18. **Damage is refused.** A card that was cut or altered fails its check before any codec runs. ## Not yet true - Principles 10 and 11: the owner has not yet reviewed the kinds of reduction. Until then the planner takes no step that changes a value, and the omission steps are provisional. The deployed site still offers value-changing steps, including one that rounds blood pressure, which is being withdrawn. --- ================================================================================ APPENDIX D: LIFTING FHIR BUNDLES & OMISSION-ONLY PLANNING (codecs/cycle-log/lift/LIFT.md) ================================================================================ # cycle-log: lifting Bundles and fitting cards to a size Two tools around the cycle-log model, both experimental: - **The lifter** (`lift.ts`) reads any FHIR R4 Bundle that says things the model can say and returns a model plus a report on every input resource. `fromBundle` in `to-bundle.ts` accepts only the exact shape `toBundle` emits; the lifter accepts the shapes real exporters produce. - **The planner** (`plan.ts`, `steps.ts`) fits a model into a target size by named, ordered reductions, the way a query planner produces an explainable plan. It uses only the options the owner has approved (`APPROVED_STEPS`). It returns the plan, the reduced model (marked `reduced`), and the frontier from the untouched card down to the smallest reachable one. The plan is the sender's record; the card itself says only that it was reduced. All data used here is synthetic. ## Files | file | what | |---|---| | `lift.ts` | `lift(bundle, options)` → `{ok, model, report}`; `formatReport`; the reason table `REASONS`, the allow groups `ALLOW_GROUPS`, and `MODIFIER_HANDLING` (how each R4 isModifier element is treated) | | `equiv.ts` | `CONFORMANT` and `SPELLING` (the three-outcome table below) and `equivalentBundles(a, b)`, which compares two Bundles modulo exactly those | | `steps.ts` | the step catalogue: `candidates(model, hints)`, `applyStep(model, step)`, the `PRIORITY` table, the verified `PARENTS` merges | | `plan.ts` | `plan(model, target, hints, run)`, `apply(model, steps)`, `explain(result)` and `explainRows(result)`, `pointModel`, QR capacity for any version, level and form, the codec as a dependency (`Codec`, `moduleEncoder`, `cardBytes`) | | `reductions.ts` | `bun codecs/cycle-log/lift/reductions.ts` measures every option, approved or not, on every persona; writes `REDUCTIONS.md` and `reductions/*.json` | | `cli.ts` | `bun codecs/cycle-log/lift/cli.ts --target v22-L --viewer` prints the lift report, the plan and the frontier | | `variants.ts` | reshaped and degraded copies of a Bundle, for the tests | | `lift.test.ts`, `plan.test.ts` | the guarantees below | Tests: `bun test codecs/cycle-log/lift`. One optional input; the tests that need it skip when it is unset: - `R4_DEFINITIONS`: a directory holding `profiles-resources.json` and `profiles-types.json` from the R4 definitions (the same variable `r4-structure.ts` uses). ## Lifting a Bundle ### What is accepted The boundary is the model (`model.d.ts`), not the shapes `toBundle` happens to write. A resource is accepted when what it says has a place in the model: | input | becomes | |---|---| | a collection Bundle, a Bundle of another type (named change), or a single resource (read as a one-entry collection) | the card | | any `fullUrl` and `id`, any entry order, references as the exact fullUrl, `Type/id` against a RESTful base, `#id` for contained resources | resolved; ids are not carried (conformant) | | `Type/id` from a urn:uuid or resource:N entry, `Type/id/_history/n`, an absolute URL that is no entry's fullUrl, when one entry has that type and id | resolved (`reference-spelling`, a spelling change: R4 does not resolve these in a Bundle) | | a Patient as an entry or contained in each fact (identical copies are one person) | `patient`: one name without a `use` (a name with a use is never carried: the use is a modifier; see below), at most three given names, the birth date | | the one Device the facts name in `Observation.device`, without a `status` | `source` (user-friendly name, first version) | | `Bundle.timestamp` (an ISO instant with seconds and quarter-hour UTC offset in 2000–2099) | `exportedAt` (`Z` and zero fractional seconds are spelling changes `time-spelling`; non-zero fractions drop with `time-fraction`; missing seconds or unsupported offsets drop with `time-dropped`) | | built-in codes, under the project's code system (bleeding, flow, pain, symptom, BBT, the proposed series codes, LOINC questions, contraception / pregnancy / lactation) | the built-in date-keyed sparse series, answers and intervals (built-in symptoms, medications, conditions, procedures, intervals and coded levels fold to readable keywords; natural decimals for temperatures, doses and custom quantities; capped to the latest 10,000 days or `options.window`) | | several codings | the one the model knows (a built-in series code, a built-in value), else the first valid one; the others are a named change | | any other Observation code (coded or text-only `{ text }`) with `valueBoolean`, `valueCodeableConcept`, `valueQuantity` (a UCUM unit) or `valueInteger` (unit `1`, named change) on one day | a custom series of that `valueType` (one per code; the most common `valueType` wins; at most 32, the largest kept) | | any Observation with a coded or text-only value and a Period over several days | a custom interval (a built-in interval when the code and value are one) | | `Coding.display` and `CodeableConcept.text` on any non-built-in escape concept (SNOMED CT, LOINC, RxNorm, ICD-10-CM, ATC, NDC, or app URI) | carried verbatim on the escape `CodeableConcept` (most frequent wins on conflict; absent on some occurrences is propagated as `label-added`). Text-only `{ text }` concepts lift cleanly as `{ text }` with no synthetic URI required. | | `MedicationStatement` (`medicationCodeableConcept`, or `medicationReference` to a Medication with a code; optional `dosage[0].doseAndRate[0].doseQuantity` in a UCUM unit) on one day | `medications` (including exact natural decimal `dose` when recorded) | | `Procedure` with a code and any `HistoryDate` (`YYYY`, `YYYY-MM`, or `YYYY-MM-DD`, 1900–2150; optional `time` on full dates) | `procedures` | | `Condition` with a code | `conditions` with the stated status and `HistoryDate` onset (1900–2150) | | a custom quantity | magnitude below 10^9 and at most 6 decimals (MODEL.md `quantity-magnitude`); otherwise left out (`out-of-range`, `precision`) | | units that convert exactly: `h`, `s`, `d` to `min`; `L`, `cL`, `dL`, `cm3` to `mL`; `Cel` and `[degF]` BBT readings when the conversion is exact in hundredths | carried exactly | | an R4 vital-sign code (heart rate, respiratory rate, SpO2, height, head circumference, weight, BMI, oral or other site temperatures, and the validator's other related codes), with or without the vital-signs category | a custom series (the model writes the category). A code with its own R4 profile takes that profile's unit: as given, or converted exactly (`{beats}/min`, `/s`, `/h` → `/min`; a fraction `1` → `%`; `m`, `mm` → `cm`; `[ft_i]` → `[in_i]`; `mg` → `kg` or `g`; `[oz_av]` → `[lb_av]`; `kg.m-2` → `kg/m2`) | | an Observation with `component[]` and no value of its own (blood pressure 85354-9, a vitals panel 85353-1 with components, an app's multi-part check-in) | a components series: each component a boolean, a concept or a quantity (`valueInteger` as unit `1`); one shape and one unit per component code on the whole card, across every components series (the most common; others convert exactly, a spelling change, or are dropped from their reading, a loss); every reading is an entry, repeats and several at one time or without a time included; a reading with no component left is left out (`component-dropped`); a component quantity holds magnitudes below 10^9 with at most 6 decimals (others are dropped from the reading); in a vital-sign series the quantity components take the R4 vitals units, and 85354-9's 8480-6 / 8462-4 take `mm[Hg]` (`cm[Hg]` converts) | | a reading that lacks one blood-pressure component | carried as it is (the model allows it; MAPPING.md §1 notes it then does not conform to the bp profile) | | Bundle.meta.tag SUBSETTED (v3-ObservationValue) | `reduced: true`, exact (any loss in the lift also sets it, below) | | SUBSETTED on one resource | `reduced: true`, a named change (the model's flag is card-wide) | | proposed `basal-body-temperature` | BBT (`bbt`), including optional `reading-excluded` and `reading-exclusion-reason` components; several readings on one day are several BBT entries. LOINC 8310-5 (clinical body temperature / fever) lifts as a separate vital-sign custom series so fever readings never mix into fertility BBT. | | `effectiveDateTime` with a time, `effectiveInstant`, a Period within one day | that day (the date as written, in the offset given); the time is a named change, except BBT readings that all share one time and offset, which the model carries | | a time of day on a fact (`effectiveDateTime` / `performedDateTime` with a time) | the entry's `time` (one entry per fact; MODEL.md wave 5), `answers[].time`, `procedures[].time` (whenever `date` is full `YYYY-MM-DD`). `Z` and zero fractional seconds are a spelling change (`time-spelling`). A loss: a non-zero fraction (`time-fraction`), no seconds (not an R4 dateTime), no UTC offset, an offset the model cannot hold, an interval or a Period (`time-dropped`, the detail says which) | | several facts of one series on one day, procedures, answers, conditions | every fact is carried (MODEL.md §8, §14): one entry each, with its time; identical facts are two entries, and disagreeing ones (two bleeding states at one time, an untimed state beside a timed one, a medication taken and not taken at one time, two readings at one time, a question answered differently, a condition stated twice differently) are all carried as recorded. Bleeding and flow facts at one day and time are a multiset (MAPPING.md): each flow-none fact pairs with a false bleeding fact and each flow level with a true one; a flow fact with none left to pair with implies its own bleeding fact (`layer0-added`, a spelling change). There is no limit per day; over 20,000 facts on the card the lift is refused (`limit`): which facts to leave out would be a choice the lifter does not make | | a flow fact without the bleeding fact | the flow state (the model writes the bleeding fact; named change) | ### What is left out or refused Every input resource ends in exactly one outcome: **exact** (carried, and `toBundle` says the same modulo the equivalence list), **changed** (carried with named changes), or **left out** (with the reason). The reason codes and their texts are `REASONS` in `lift.ts`; `formatReport` prints them with counts and examples. Left out, with a reason: resource types with no place in the model (Practitioner, Encounter, Organization, Composition, ...); value types the model lacks (string, Range, Ratio, SampledData, time, dateTime, Period); facts without a date or value; per-day facts over several days; values outside a field's range; units that do not convert exactly; a second Patient; Devices no fact names, or several Devices (the model has one source); facts outside the window or before the latest 10,000 days; contradicting bleeding and flow facts; over a model limit. Vital signs and components, left out: | input | reason | |---|---| | a code with its own profile in a unit that is neither allowed nor converts exactly (weight in `[stone_av]`, BP components in `kPa`) | `unit`, or `profile-component` for a blood-pressure component | | a profiled code in the wrong shape (heart rate as a coded value, blood pressure as a single quantity, weight as components) | `vital-sign-profile` | | blood pressure with a value of its own beside its components | `value-and-components` | | a blood-pressure component the model cannot carry (unsupported value type, no value, a unit that does not convert) | `profile-component`: the whole reading, since a lone systolic or diastolic carried from a damaged reading would mislead | | another reading's component of an unsupported type or unit | `component-dropped`: that component only; the rest of the reading is carried (named change) | | more than 16 components in a reading, or the same component twice | `limit`, `malformed` | | a vitals panel 85353-1 with only `hasMember` | `no-value` (the members are carried as their own series) | | a vital-sign code as a state over days | `vital-sign-code` (the model's intervals may not use them) | Named changes on carried resources: elements with no place (identifier, issued, performer, note, interpretation, method, bodySite, references between resources, gender, telecom, ...), extensions, CodeableConcept.text and narrative that is not generated, extra codings, categories other than vital-signs on BBT, times of day, Periods within a day, statuses read as the nearest model value, labels in conflict, a Condition's asserter set to the person. ### When the lifted card is reduced Reduced is reduced: `lift` sets `reduced: true` on the model (Bundle tag SUBSETTED) whenever the report holds anything that loses information, besides when the input carries the tag. `LOSES` in `lift.ts` classifies every reason code as losing or not, in one table; the report sets `loss` on every note and every resource, `report.loses` for the whole lift, and `report.losing` counts the losing resources, Bundle-level items and reasons, so a caller can show exactly which items caused the flag. `formatReport` and the CLI print the line `reduced: yes, because the lift lost information: …` with those counts. - **Not losing:** what the profiles allow is not reported at all (below). The spelling changes are reported, lose nothing, and do not flag the card; strict mode still refuses them. Their reasons: `time-spelling`, `unit-converted`, `unit-assumed`, `period-to-day`, `value-as-quantity`, `contained-patient`, `subject-added`, `patient-added`, `category-added`, `fixed-display-added`, `wrapped`, `state-merged`, `label-added`, `medication-inlined`, `medication-resource`, `reference-spelling`, `layer0-added`, `device-attributed`, `asserter-added`, plus `window-inferred` (a caller's window) and the opt-in `guide-code`. - **Losing:** every exclusion, every blocking reason the caller allowed (the item, or for a name with a use that name, is then left out), and every other named change: times of day, elements, extensions, text, extra codings, categories, rounding, clipped periods, labels, names, birth dates, onsets, Bundle elements, a Bundle of another type, components, and SUBSETTED on one resource. - **Nearly any Bundle this project's decoder did not write will be reported as changed, and most will be flagged reduced.** An app's Bundle nearly always carries something the model has no place for: an identifier, a timestamp, a narrative, a time of day. That is the intended meaning: the card is not everything the sender had. - No option hides a loss. A caller that has told the receiver by other means may clear `reduced` on the returned model itself. - `lift(toBundle(m))` loses nothing, so an unreduced model stays unreduced. Lifting the returned card again sees the tag, keeps `reduced`, and reports no further loss (idempotence). Strict mode refuses on any change, as before; it never returns a flagged model. ### Modifier elements are always preserved Some elements change what the rest of a resource means: the R4 StructureDefinitions mark them `isModifier`, and a few others act the same way. The rule: a resource is never carried with a modifier element stripped or rewritten. When the model cannot hold the modifier's value, the lift refuses by default, naming the element and the value (for example `Device.status = active`). When the caller allows the item's group, the whole resource is left out and reported, and the card is flagged reduced. It is never carried without the modifier. | allow group | what | when allowed | |---|---|---| | `retracted` | status `entered-in-error` on any resource; Condition.verificationStatus refuted / entered-in-error; a Medication entered-in-error used by a MedicationStatement | left out | | `not-final` | Observation status other than final (amended and corrected included); MedicationStatement active / intended / stopped / on-hold / unknown; Procedure other than completed | left out | | `negated` | Procedure status not-done | left out | | `data-absent` | Observation.dataAbsentReason, or a component's | left out | | `modifier` | modifierExtension anywhere (every backbone element, a Medication a statement uses, Bundle.link, a Bundle entry and its search / request / response), implicitRules, Patient.active (true or false), Patient.deceased[x], Patient.link, HumanName.use, Device.status, Medication.status, Condition.clinicalStatus inactive / remission / recurrence / relapse, Condition.verificationStatus confirmed | left out; for HumanName.use, that name is left out | | `other-subject` | a subject that is not the person, Observation.focus | left out | | `qualified` | Quantity.comparator, on a value or on a component | left out | | `uncertain` | Condition.verificationStatus unconfirmed / provisional / differential | left out | - **The Patient.** Every fact refers to the Patient, so leaving the person's Patient out (for `active`, `deceased[x]`, `link` or a modifierExtension) does not leave the facts out: the card carries the identity-free Patient, and the name and birth date are not carried either. A name and birth date for a person the source marks inactive, deceased or merged, without saying so, would mislead. The report gives the Patient the reason `identity-left-out`. - **A name with a use** (official, usual, nickname, old, ...) is left out on its own, since the use belongs to that name; the Patient is carried with a name that has no use, if there is one, and with its birth date. - **The source Device** left out for its status: the card names no source, and every fact that named the Device is carried without it (`element-dropped`, so flagged). - **Datatype modifiers whose parent is never carried** (Identifier.use, ContactPoint.use, Address.use) go with that parent: the identifier, telecom or address is dropped whole (`element-dropped`) and nothing blocks. Without `options.allow` naming the group, `lift` refuses (`ok: false`, no model). The refusal names every element and value, and `report.blocked` lists them with their groups. `MODIFIER_HANDLING` in `lift.ts` states the handling of every R4 isModifier element of the types the lifter reads. Two tests derive from the R4 definitions: one checks that every isModifier element has a handling, and one states the rule directly. For every isModifier element of Bundle, Patient, Device, Observation, MedicationStatement, Procedure, Condition and Medication (51 elements, 105 cases: every modifierExtension path, and every value the model does not hold of each coded modifier), the lift either refuses, or, when allowed, does not carry the resource. Identifier, ContactPoint and Address uses are the exception: there the Patient is carried and the element is dropped whole. **Strict mode** (`options.strict`) refuses if anything would be changed or left out at all, Bundle-level elements included. ## Three outcomes: conformant, spelling change, loss The closed profiles (`../profiles`) are the contract: a lift is exact exactly when the Bundle conforms. Every difference between an input Bundle and what the decoder would write is one of three things, and `equiv.ts` (`CONFORMANT`, `SPELLING`) implements exactly the first two, so its "equal modulo" is the relation the report uses. | outcome | what | report | card | |---|---|---|---| | **conformant** | repeated facts (two identical facts are two entries); entry order, key order, whitespace, trailing decimal zeros; any distinct fullUrl and Resource.id, and a reference R4 resolves inside the Bundle (the entry's exact fullUrl, a relative Type/id against the referring entry's RESTful fullUrl base, `#id` for a contained resource); Bundle.meta.tag SUBSETTED with or without its display; meta.profile naming the resource's own profile (`PROFILE_URL(profileNameOf(resource))` from `to-bundle.ts`; `cycle-log-bundle` on the Bundle), once; a display identical to the one the decoder writes | nothing | as is | | **spelling change** | `Z` for +00:00 and zero fractional seconds on times or `Bundle.timestamp` (`time-spelling`); an exact unit conversion (`unit-converted`) or a unit string read as its UCUM code (`unit-assumed`); a one-day Period of dates on a per-day fact (`period-to-day`); valueInteger for a quantity with unit 1 (`value-as-quantity`); a contained Patient (`contained-patient`); no subject with one Patient (`subject-added`); no Patient, or an empty one (`patient-added`); the vital-signs category absent (`category-added`); a fixed display absent (`fixed-display-added`); a single resource (`wrapped`); a state as daily facts or as Periods that overlap or touch (`state-merged`); a label on some codings of a concept only (`label-added`); a Medication with only a code (`medication-inlined`, `medication-resource`); a reference R4 does not resolve but that names exactly one entry by type and id: Type/id from a urn:uuid or resource:N entry, Type/id/_history/n, an absolute URL that is no entry's fullUrl (`reference-spelling`; one that names no entry, or several, stays unresolved); and three additions that lose nothing: the bleeding fact a flow fact implies (`layer0-added`), the one source Device on a fact that named none (`device-attributed`), the person as asserter (`asserter-added`) | a named change, `loss: false` | not flagged; strict mode refuses | | **loss** | anything the card will not carry, however small: meta.versionId, lastUpdated, source, security, other tags; narrative of any kind; Bundle.id, total, identifier, link; entry.search and request; a display or `CodeableConcept.text` on a built-in code that differs from the decoder's; Coding.version, userSelected, id; unit text other than the code; Reference.display, type, identifier; element ids anywhere; extensions anywhere; and every exclusion | a named change or exclusion, `loss: true` | flagged reduced | **Nearly any Bundle not written by this project's decoder is therefore reported as changed, and most as reduced.** That is the intended meaning: a reader of the card should know when the card is not everything the sender had, however minor the missing part. **Every key is accounted for.** The lifter records the JSON paths it carries (`taken`); the paths under a note are accounted by the note. Every other key of every input resource is reported generically as `element-dropped` with its path (a loss), so a key the lifter never looked at can no longer pass silently. The test of this is the profiles' mechanical generator below. **SNOMED CT in another letter case** (`HTTP://SNOMED.INFO/SCT`) is another code system for the lifter and `equiv.ts`, as it is for `model.ts`: `validate` accepts it as an escape (only the exact `http://snomed.info/sct` folds to a bare id), and the profiles treat it as a different system. ## Guarantees and tests - `lift(toBundle(m))` equals `normalize(m)` in strict mode, every resource exact, for the 14 personas, 120 random models and 6 random models at the limits (`randomModel` from `codec-fixtures.ts`; they include `reduced`, blood pressure and app readings with every component shape). - 23 variants on 16 base Bundles (10 personas, vitals-follow-up among them, and 6 random models), from `variants.ts`: - Reshapings that keep the model (shuffled entries; `urn:uuid` fullUrls; RESTful fullUrls with relative references and each resource's own profile; the same with `_history` references, a spelling change; the Patient contained in every fact; no subjects; displays added to standard codes, guide displays removed, unit text; sleep in hours and volume in L; contraception as daily facts). States split into overlapping Periods are a spelling change. Each lifts to the same model and the Bundles are equivalent. Facts repeated: each repeat is a further entry, conformant, as `fromBundle` reads it. - 5 changes that keep the model (fractional seconds on times; extensions, issued, note; alternate codings; unrelated resources and performers; flow without the bleeding fact). Each lifts to the same model, the report names the change, the Bundles are not equivalent, and strict mode refuses. - 5 blocking cases (entered-in-error rows; preliminary and cancelled facts; dataAbsentReason; a modifierExtension and a comparator; a second patient's fact). Each is refused, and with the matching `allow` lifts to the same model with the items left out. - 4 vital-sign cases: blood pressure with the diastolic missing on some readings (carried as it is, exact), heart rate in `{beats}/min` and height in `m` (converted, exact), a vitals panel 85353-1 pointing at the readings (left out, model unchanged), blood pressure with a value of its own and one in kPa (both left out, model unchanged). - Idempotence on every variant: `lift(toBundle(lift(b).model))` is the same model, all exact, in strict mode. - Variants are `same` (conformant), `spelling` (named changes, no loss, equivalent, refused by strict mode), `changed` (a loss) or `blocked`. - **One agreement test with the profiles.** The profiles' generator of mechanical additions (`../profiles/agreement.ts`: every closed path, every removed choice type, every modifier value; 3,535 cases), their 34 rule mutations and the lift variants are run with the predicate *conforms ⇔ lifted exactly with no note*. Against the profiles in the tree today: 0 mechanical disagreements, 0 rule disagreements (from 1,001 and 15), and every variant agrees: a conforming base lifts exactly, and a base that does not conform is reported as changed. - Boundary tests: the SUBSETTED tag (Bundle and resource), vital signs exact, converted and left out, components (partial readings, unsupported components, a comparator in a component, a panel with components), 8310-5 one a day and several, unknown codes of every value shape, valueString, same-day conflicts with and without times, bleeding/flow contradictions, times of day (per series and day, Z, :00 seconds, no offset, an offset the model cannot hold, different times on one day, answers and procedures), the guide-codes option, unit conversions, Periods within a day and over days, over 10,000 days, statuses of Observation, Procedure, MedicationStatement and Condition, two Devices. ## Relation to the Period Tracking guide The project is self-contained: its built-in concepts, bleeding and flow included, are in its own code system (`https://joshuamandel.com/shc2-poc/CodeSystem/cycle-log`), and nothing here needs the Period Tracking guide (cycle.fhir.me). Bundles written to that guide are outside this project's contract today; reconciling the two is future work. By default its eight concepts (`https://cycle.fhir.me/CodeSystem/cycle`: menstrual-bleeding, menstrual-flow, symptom, flow-none … flow-heavy) are codes the model does not know as built-ins, so they lift as custom series, exactly, without bleeding semantics. The opt-in `guideCodes` option (CLI `--guide-codes`) reads them as the project's own concepts, which they mirror one for one, and reports every recoding as `guide-code`, a change that loses nothing and so does not flag the card. ## The planner ### Targets A target is a card byte budget, or a QR symbol: version, error-correction level, and form (bare `shc2:/`, or with the viewer link in front). A card is the codec input plus 3 bytes: the 1-byte codec reference and the 2-byte check (`src/card.ts` `pack()`). Capacity is computed from `src/qr.ts` for any level (the site's `qrfit.ts` covers level L only). Version 22-L holds 983 card bytes bare and 949 with the viewer link. ### The owner's decisions (strictly omission-only) `APPROVED_STEPS` in `steps.ts` records them; the planner uses approved options only, and `apply()` refuses any other (`experimental: true` is for `reductions.ts` measurement only). **Every approved reduction is strictly omission-only**: no step ever alters a recorded value, rounds a temperature (`0.01 °C` / `0.01 °F` preserved verbatim), rounds sleep duration, rounds times of day, collapses a scale, or coarsens a date. Every fact remaining on a reduced card is verbatim as recorded. | measure | approved | rejected | |---|---|---| | times of day | dropped (facts keep their dates) | every rounding rung (1, 5, 15, 60 minutes) | | basal temperature, wearable skin temperature (absolute and deviation), body-temperature vital signs | as recorded (`0.01°` preserved) | every grid rung (0.05, 0.1, coarser) | | sleep duration | as recorded (exact minutes) | every grid rung (5, 15, 30, 60 minutes) | | blood pressure | as recorded (dropped only whole, never split or `max`-thinned) | every rung, component drop, `thin(max)` | | other measurements and custom quantities (heart rate, respiratory rate, SpO2, weight, height, BMI, menstrual volume, step count, ...) | as recorded | every rung | | numeric and ordinal scales (pain, mood, energy, flow level), codes | as recorded | bands, shorter scales, flow levels as "bleeding", parent codes | | history dates | as recorded | month, year | | omissions: display text (with opaque-code and rich free-text guard), the flow scale's "none" fact, explicit negatives, one entry a day, a component (not BP), a series (keeping `source` above `skinTemp`), the oldest days | approved | | Three clinical guardrails apply on top of the omission ladder: - **No `max`-thinning on multi-component readings**: blood pressure and other component panels cannot be thinned with `max` (which has no single scalar maximum); only `first` or `last` whole readings are allowed, and BP components are never split. - **Wearable device attribution preserved**: while `skinTemp` remains on the card, `omit(source)` is weighted above `skinTemp` so the wearable device name is not stripped before its temperature series. - **Opaque-code and rich free-text label guard**: labels whose codes are opaque identifiers (UUIDs, numeric IDs, hashes) or whose display text carries multi-word free-text meaning beyond the code are moved from presentation (class 2) to omission (class 5) so meaningful text is not silently stripped early. | kind | effect | |---|---| | `times` with `drop`; `labels`; `flow-none`; `negatives`; `thin`; `omit`; `window` | omits | | `times` with a rung; `grid`; `history`; `points`; `parent`; `bands`; `flow` | alters (all rejected) | ### Loss classes | class | name | approved options | |---|---|---| | 0 | none | a label that only repeats its code | | 1 | time of day | times dropped; per series, for answers and procedures, or card-wide | | 2 | presentation | display text of human-readable app codes; the flow scale's "none" fact | | 3 | precision | none (all value-altering precision rungs rejected) | | 4 | scale | none (all scale collapses rejected) | | 5 | omission | several entries a day thinned to one, explicit negatives, opaque/rich labels, one component of a reading (not blood pressure), a whole series, least important first | | 6 | window | the oldest days, in whole cycles (to the next bleeding onset; 30 days when there is none) | Within classes 0–4 the loss of a step is its rung on its ladder times the weight of its part (its position in the drop order); a time rung's loss is log2 of its grid in minutes (the minute rung, which only drops seconds, 0.1; dropping 10.5). Within class 5 a step's loss is the part's position, so omission follows the order strictly; a card-wide time step weighs the sum of the timed parts' weights; thinning comes three quarters of a place before the part, its explicit negatives half a place, one component a quarter place. A step is taken only when it makes the card smaller. ### Default priority order `PRIORITY` in `steps.ts`, one table; least clinically important first (dropped first). `PARTS` lists the part names; `partOf(scope)` maps a step's scope to its part. | # | part | why | |---|---|---| | 1 | source | provenance (the exporting app); the data do not depend on it | | 2 | energy | a 4-point self-rating with no clinical threshold | | 3 | mood | a 7-point valence; useful for premenstrual patterns, rarely decisive | | 4 | sleep | wellness context; large and noisy, little cycle information | | 5 | skinTemp | a wearable's nightly temperature; overlaps BBT where both exist, device-specific | | 6 | custom | app- or person-specific series; their meaning rests on labels a receiver may not know | | 7 | sex | fertility context; sensitive, and rarely needed by a receiver | | 8 | mucus | fertility-awareness sign; meaningful mainly to the person's own method | | 9 | symptoms | premenstrual and dysmenorrhea pattern; often summarized by pain | | 10 | ovulationTest | ovulation timing; partly recoverable from BBT | | 11 | progesteroneTest | confirms ovulation; rare | | 12 | bbt | biphasic pattern: ovulation and luteal length | | 13 | vitals | custom series on R4 vital-sign codes (blood pressure, heart rate, weight, ...): measured clinical signs a receiver may act on, but the card is a cycle record and a clinic usually measures these itself | | 14 | medications | analgesics, tranexamic acid, iron: treatment context | | 15 | pill | adherence explains breakthrough bleeding on the pill | | 16 | volume | the only calibrated amount for heavy menstrual bleeding | | 17 | pain | dysmenorrhea severity, a common reason to see a clinician | | 18 | answers | the person's own summary answers; a few bytes | | 19 | conditions | explain a bleeding pattern (PCOS, fibroids, ...); a few bytes | | 20 | procedures | change what bleeding means (ablation, hysterectomy, IUD); a few bytes | | 21 | intervals | contraception, pregnancy, breastfeeding change what bleeding means | | 22 | pregnancyTest | a positive test changes everything; a few bytes | | 23 | bleeding | the core fact; without it the card is not a period-tracking record | `hints.priority` is a drop order, first dropped first. Its entries are part names and `custom:` for one custom series. Listed entries come first, in the order given; every part not listed follows in the default order. A custom series not listed by its own code takes the place of its part (`custom`, or `vitals` for an R4 vital-sign code). So a complete list fixes the whole order, and a short one moves the named parts to the front. The patient's identity is never dropped. ### Step catalogue A step is `{kind, scope, component?, param?}`; `component` names one component of a components series. | kind | scope | parameters | class | status | what the card no longer carries, or what it changes | |---|---|---|---|---|---| | `labels` | `redundant` | – | 0 | approved | `Coding.display` / `CodeableConcept.text` strings on coded escapes equal to their code (never strips `text` on text-only `{ text }` concepts) | | `times` | a series name, `custom:`, `events` (answers and procedures), `all` | `drop` | 1 | approved | times of day (strips `T…` from `date`); the facts keep their day | | `times` | same | 1, 5, 15, 60 (minutes) | 1 | rejected | times rounded | | `labels` | `custom:`, `other` | – | 2 (or 5 if protected) | approved | optional `Coding.display` and `CodeableConcept.text` of coded escapes in a custom series or outside custom series; never strips `text` on text-only `{ text }` concepts | | `flow-none` | bleeding | – | 2 | approved | the flow fact "none" beside an explicit no-bleeding | | `grid` | bbt, skinTemp, body-temperature vital signs, sleep, volume, `custom:`, or one quantity component | the grid | 3 | rejected | values rounded | | `history` | history | month, year | 3 | rejected | day, then month, of procedure dates, condition onsets, the birth date | | `points` | mood (5, 3), energy (2) | the scale | 4 | rejected | levels collapsed | | `parent` | symptoms, sex | the parent | 4 | rejected | codes replaced by a verified parent | | `bands` | pain | – | 4 | rejected | scores replaced by bands | | `flow` | bleeding | – | 4 | rejected | flow levels replaced by "bleeding" | | `negatives` | bleeding, pain, sex, `custom:` (boolean) | – | 5 | approved | explicit negatives | | `thin` | a series name or `custom:` | `first`, `last`, `max`; a set series: `first` | 5 | approved | all but one entry a day (a set: each item once); a reading is kept or left out whole | | `omit` | `custom:` with `component` | – | 5 | approved | one component of every reading; never for a code whose R4 profile fixes its components (blood pressure) | | `omit` | any part on the card | – | 5 | approved | the whole part | | `window` | window | days cut | 6 | approved | the oldest days | What each option buys, and what each altering option would change, is measured in `REDUCTIONS.md` (generated by `reductions.ts`, data in `reductions/`). ### Default heuristic Every candidate is measured by encoding the reduced model with the codec. Among candidates that save bytes, the chooser takes the lowest loss class; within it the most bytes per loss unit (class 5: the drop order). It never takes a higher class while a lower one that saves bytes is available, unless `preferWindowOverSeries` puts the window (class 6) before omission. A test checks the class rule on every round of the search. Measuring is lazy. After a step on one part, a candidate on another part keeps the saving measured in the previous round; a candidate is measured again before it is taken, and so is every lower-class candidate whose carried saving says it does not help, so the class rule holds on fresh values. Steps that change the whole card (window, history, the shared labels) clear every carried saving. `run.exhaustive` measures every candidate on every round (the reference behaviour; a caller's `choose` always gets fresh values). Encoded sizes are cached by codec and model across calls, so a page that replans after a change of hints encodes only what is new. The plan is the shortest prefix of the search that meets the target. The search continues past the target to the smallest reachable card; the **frontier** is every point of that path smaller than all points before it: (bytes, QR version, highest class, loss units, steps). When the target is out of reach the result says `UNREACHABLE` with the smallest card reachable under the hints. Hints (rules; JSON): `pin` (parts that stay exact: a part name, `custom:`, `labels`, `window`), `forbid` (step ids, id prefixes, kinds or loss classes), `priority`, `maxLossClass`, `preferWindowOverSeries`, `frontier: false` (stop at the target), `steps` (execute an explicit plan as given), `choose(candidates, context)` (the caller's chooser). `apply(model, steps)` is deterministic: the plan's step list alone replays the reduced model (tested), and the CLI prints it as `--steps '…'`. Run options (`plan(model, target, hints, run)`), not rules: | option | what | |---|---| | `codec` | a compiled `WebAssembly.Module` (its `shc_encode` is called as CODEC-ABI.md describes) or an encode function `(modelJson) => codec input bytes`; default: `cycle-log.wasm` loaded through `codec-host.ts` (Bun), imported only when no codec is given | | `onProgress(p)` | after every round: round, bytes, whether a point meets the target, the new frontier point, encodes and cache hits | | `signal` | an AbortSignal; aborting rejects with its reason | | `shouldStop()` | returning true ends the search; the result has `stopped: true` and the frontier found so far | | `pointModels` | each frontier point carries its reduced model (else `pointModel(result, i)` applies its steps to `result.original`) | | `compact` | leave `rounds` out | | `exhaustive` | see above | With `onProgress`, `signal` or `shouldStop` the search yields to the event loop between rounds, so a worker sees an abort and a page sees progress. `explain(result)` prints the plan and the frontier as text; `explainRows(result)` returns the same as data (`steps`: n, id, step, class, what is lost, bytes before and after, QR; `frontier`: point, bytes, QR, highest class, loss units, steps added, whether it is the plan). ### Timings Measured on the wave-4 model (14 personas) at Version 22-L with the viewer link, in one process, before (the committed prototype, with its marker) and after (lazy measuring and the cache, cold cache): | persona | before ms, full frontier | after ms, full frontier | after: encodes | after ms, stopping at the target | |---|---:|---:|---:|---:| | power-tracker | 2425 | 492 | 110 | 198 | | copper-iud | 566 | 221 | 78 | 1 | | pcos | 681 | 157 | 59 | 3 | | minimal | 23 | 11 | 6 | 1 | | perimenopause | 570 | 155 | 48 | 4 | | combined-pill | 344 | 115 | 43 | 3 | | near-empty | 23 | 14 | 9 | 1 | | own-vocabulary | 2705 | 1075 | 180 | 912 | | wellness-diary | 1643 | 565 | 106 | 481 | | calendar-only | 39 | 24 | 13 | 3 | | smart-cup-hmb | 510 | 185 | 64 | 4 | | wearable | 218 | 103 | 37 | 4 | | post-ablation | 350 | 186 | 60 | 1 | | vitals-follow-up | 656 | 295 | 77 | 5 | | total | 10752 | 3597 | | 1620 | An encode takes 3–6 ms and is most of the remaining time. Replanning the same card after a change of hints (here, forbidding one step) took 1.4 s for all 14, with most sizes from the cache (power-tracker: 40 of 108). ### What the receiver learns The model's `reduced` flag, written as the Bundle tag SUBSETTED. `apply` sets it as soon as any step of class 1 or higher is applied; class 0 steps alone do not set it, since they lose nothing. A model that was already reduced (the lift lost something, or the input carried the tag) stays reduced, and `explain` says the flag predates planning. The flag costs about one bit, and every measurement includes it. That flag is all the card carries. The step list, the frontier and the "what is lost" texts are the sender's record of what was done; they do not travel with the card, and `explain` and the plan report say so. ## Frontiers to Version 22-L with the viewer link 949 card bytes; approved options only. ◀ marks the plan. Step ids shorten app systems to `custom:` and LOINC to `LOINC `. **power-tracker**, 1154 bytes untouched (25-L); plan: 5 steps → 890 bytes (22-L); 499 ms | point | card bytes | QR | highest class | steps added | |---|---:|---|---|---| | 0 | 1154 | 25-L | – | (untouched) | | 1 | 1131 | 25-L | 2 | flow-none(bleeding) | | 2 | 1040 | 24-L | 3 | grid(bbt, 5) | | 3 | 1003 | 23-L | 3 | grid(bbt, 10) | | 4 | 982 | 23-L | 5 | omit(source) | | 5 ◀ | 890 | 22-L | 5 | omit(energy) | | 6 | 782 | 20-L | 5 | omit(mood) | | 7 | 602 | 18-L | 5 | omit(sleep) | | 8 | 597 | 18-L | 5 | negatives(sex) | | 9 | 556 | 17-L | 5 | omit(sex) | | 10 | 484 | 16-L | 5 | omit(mucus) | | 11 | 308 | 12-L | 5 | omit(symptoms) | | 12 | 276 | 12-L | 5 | omit(ovulationTest) | | 13 | 263 | 11-L | 5 | omit(progesteroneTest) | | 14 | 139 | 8-L | 5 | omit(bbt) | | 15 | 113 | 8-L | 5 | omit(medications) | | 16 | 91 | 7-L | 5 | negatives(pain) | | 17 | 61 | 5-L | 5 | omit(pain) | | 18 | 52 | 5-L | 5 | omit(intervals) | | 19 | 45 | 5-L | 5 | omit(pregnancyTest) | | 20 | 35 | 4-L | 5 | negatives(bleeding) | | 21 | 8 | 3-L | 5 | omit(bleeding) | **own-vocabulary**, 1573 bytes untouched (30-L); plan: 10 steps → 949 bytes (22-L); 1108 ms | point | card bytes | QR | highest class | steps added | |---|---:|---|---|---| | 0 | 1573 | 30-L | – | (untouched) | | 1 | 1554 | 29-L | 0 | labels(redundant) | | 2 | 1538 | 29-L | 2 | labels(other) | | 3 | 1491 | 29-L | 2 | labels(custom:flowly|energy) | | 4 | 1449 | 28-L | 2 | labels(custom:flowly|emotions) | | 5 | 1438 | 28-L | 2 | labels(custom:flowly|cervix-position) | | 6 | 1437 | 28-L | 2 | flow-none(bleeding) | | 7 | 1331 | 27-L | 3 | grid(sleep, 5) | | 8 | 1232 | 26-L | 3 | grid(skinTemp, 5) | | 9 | 1195 | 25-L | 3 | grid(skinTemp, 10) | | 10 ◀ | 949 | 22-L | 5 | omit(sleep) | | 11 | 806 | 21-L | 5 | omit(skinTemp) | | 12 | 537 | 17-L | 5 | omit(custom:flowly|emotions) | | 13 | 413 | 15-L | 5 | omit(custom:flowly|energy) | | 14 | 326 | 13-L | 5 | omit(custom:flowly|cervix-position) | | 15 | 307 | 12-L | 5 | omit(custom:431416001) | | 16 | 286 | 12-L | 5 | omit(custom:25064002) | | 17 | 252 | 11-L | 5 | omit(sex) | | 18 | 134 | 8-L | 5 | omit(symptoms) | | 19 | 106 | 7-L | 5 | omit(medications) | | 20 | 94 | 7-L | 5 | omit(intervals) | | 21 | 53 | 5-L | 5 | negatives(bleeding) | | 22 | 25 | 4-L | 5 | omit(bleeding) | **wellness-diary**, 1862 bytes untouched (32-L); plan: 7 steps → 769 bytes (20-L); 581 ms | point | card bytes | QR | highest class | steps added | |---|---:|---|---|---| | 0 | 1862 | 32-L | – | (untouched) | | 1 | 1852 | 32-L | 0 | labels(redundant) | | 2 | 1795 | 32-L | 2 | labels(custom:codes|migraine-triggers) | | 3 | 1784 | 32-L | 2 | labels(custom:codes|caffeine) | | 4 | 1674 | 31-L | 3 | grid(sleep, 5) | | 5 | 1418 | 28-L | 5 | omit(sleep) | | 6 | 1384 | 27-L | 5 | negatives(custom:37796009) | | 7 ◀ | 769 | 20-L | 5 | omit(custom:LOINC 41950-7) | | 8 | 487 | 16-L | 5 | omit(custom:codes|caffeine) | | 9 | 313 | 12-L | 5 | omit(custom:codes|resting-heart-rate) | | 10 | 194 | 10-L | 5 | omit(custom:codes|migraine-triggers) | | 11 | 181 | 9-L | 5 | omit(custom:37796009) | | 12 | 73 | 6-L | 5 | omit(medications) | | 13 | 24 | 4-L | 5 | omit(pain) | | 14 | 8 | 3-L | 5 | omit(bleeding) | **timestamped**, 1937 bytes untouched (33-L); plan: 8 steps → 866 bytes (21-L); 1203 ms | point | card bytes | QR | highest class | steps added | |---|---:|---|---|---| | 0 | 1937 | 33-L | – | (untouched) | | 1 | 1785 | 32-L | 1 | times(mood, drop) | | 2 | 1486 | 29-L | 1 | times(bbt, drop) | | 3 | 1295 | 26-L | 1 | times(symptoms, drop) | | 4 | 1118 | 25-L | 1 | times(energy, drop) | | 5 | 1032 | 23-L | 1 | times(ovulationTest, drop) | | 6 | 963 | 23-L | 1 | times(sex, drop) | | 7 | 962 | 23-L | 1 | times(pregnancyTest, 1) | | 8 ◀ | 866 | 21-L | 1 | times(bleeding, drop) | | 9 | 784 | 20-L | 1 | times(pain, drop) | | 10 | 740 | 19-L | 1 | times(medications, drop) | | 11 | 739 | 19-L | 1 | times(events, 5) | | 12 | 734 | 19-L | 1 | times(events, drop) | | 13 | 730 | 19-L | 1 | times(pregnancyTest, drop) | | 14 | 641 | 18-L | 3 | grid(bbt, 5) | | 15 | 608 | 18-L | 3 | grid(bbt, 10) | | 16 | 591 | 17-L | 5 | omit(source) | | 17 | 510 | 16-L | 5 | omit(energy) | | 18 | 404 | 14-L | 5 | omit(mood) | | 19 | 365 | 13-L | 5 | omit(sex) | | 20 | 361 | 13-L | 5 | thin(symptoms, first) | | 21 | 278 | 12-L | 5 | omit(symptoms) | | 22 | 248 | 11-L | 5 | omit(ovulationTest) | | 23 | 113 | 8-L | 5 | omit(bbt) | | 24 | 109 | 7-L | 5 | thin(medications, first) | | 25 | 101 | 7-L | 5 | omit(medications) | | 26 | 87 | 6-L | 5 | thin(pain, first) | | 27 | 86 | 6-L | 5 | negatives(pain) | | 28 | 65 | 6-L | 5 | omit(pain) | | 29 | 61 | 5-L | 5 | omit(answers) | | 30 | 58 | 5-L | 5 | omit(procedures) | | 31 | 55 | 5-L | 5 | omit(intervals) | | 32 | 52 | 5-L | 5 | omit(pregnancyTest) | | 33 | 38 | 5-L | 5 | thin(bleeding, last) | | 34 | 8 | 3-L | 5 | omit(bleeding) | **bp-twice-daily**, 1801 bytes untouched (32-L); plan: 7 steps → 679 bytes (19-L); 561 ms | point | card bytes | QR | highest class | steps added | |---|---:|---|---|---| | 0 | 1801 | 32-L | – | (untouched) | | 1 | 1563 | 29-L | 1 | times(all, 5) | | 2 | 1358 | 27-L | 1 | times(custom:LOINC 85354-9, drop) | | 3 | 1180 | 25-L | 1 | times(medications, drop) | | 4 | 1024 | 23-L | 1 | times(custom:LOINC 8867-4, drop) | | 5 | 1003 | 23-L | 5 | omit(source) | | 6 | 994 | 23-L | 5 | omit(symptoms) | | 7 ◀ | 679 | 19-L | 5 | thin(custom:LOINC 85354-9, max) | | 8 | 267 | 11-L | 5 | omit(custom:LOINC 85354-9) | | 9 | 76 | 6-L | 5 | omit(custom:LOINC 8867-4) | | 10 | 43 | 5-L | 5 | omit(medications) | | 11 | 37 | 5-L | 5 | omit(conditions) | | 12 | 8 | 3-L | 5 | omit(bleeding) | ## What was decided about marking a reduced card The prototype proposed a model field listing the steps. The owner chose a single flag instead: - **Model.** `reduced?: boolean | null` at the top level (canonical `false`): the sender deliberately coarsened or left out data to fit a size. It says nothing about which. - **FHIR.** `Bundle.meta.tag` = `http://terminology.hl7.org/CodeSystem/v3-ObservationValue#SUBSETTED` (display "subsetted"), the tag FHIR uses for any view from which information has been removed. - **Here.** `apply` sets the flag for any step of class 1 or higher; the lifter sets it for any loss in the lift ("reduced is reduced", `LOSES`) and reads the tag back as `reduced: true` (exact, equivalence E15). The prototype's interim interval marker (about 55 bytes) and its unpublished code system are gone, with the `marker` option: a caller that wants no flag must clear the field itself, and nothing here offers a switch that would hide a reduction. - **Consequence.** A receiver can no longer tell which steps were taken. Every value on a reduced card is verbatim as recorded; an absent series or day may have been left out, so absence is never read as a negative. ## Judgment calls for review 1. **Loss class order** among approved options: time of day (1), presentation (2), precision (3), omission (5), window (6). 2. **The priority table**: custom series at position 6 as one group (a migraine diary's own series are its point, yet they go before symptoms; `priority: ["custom:", ...]` now ranks one series apart), and vital signs at 13, after BBT and before medications. 3. **Blood pressure is dropped only whole.** One component of a reading may be dropped only when no R4 profile fixes the code's components; for 85354-9 a lone systolic would no longer conform and would read as a complete measurement. 4. **8310-5 stays BBT, several readings included.** MODEL.md §5 defines 8310-5 as the built-in BBT (waking readings) and puts other temperatures under other codes; with wave 5 several readings a day are BBT entries with their times. A fever log coded 8310-5 is therefore carried as BBT entries; recoding it would invent a code the source did not use. 5. **A damaged blood-pressure reading is left out whole** (a component in kPa, a missing value beside a value of its own); a reading that simply lacks one component in the input is carried as it is, as the model allows. 6. **Unit conversions into a vital sign's profile unit are spelling changes**, like hours to minutes. Pounds are an allowed weight unit and stay pounds; ounces convert to pounds. 7. **Altering options** are those in the owner's decisions table above. 8. **SUBSETTED on one resource** marks the whole card reduced and is a named change; there is no per-resource flag. 9. **Entered-in-error rows block by default**, as asked, although leaving out a retracted row is what a receiver should do anyway. `allow: ["retracted"]` is the expected setting for real exports. 10. **Observation amended / corrected** are blocking (`not-final`) and, when allowed, left out (the rule: a status is never rewritten), although their values are the current ones. 11. **The lifter never decides between facts**: repeats and disagreements are all carried (wave 8). What is still chosen is listed under judgment call 27. 12. **The window from facts** is the span of the dated facts, capped to the latest 10,000 days. A caller who knows the export's range should pass `options.window`, since leading and trailing unrecorded days cannot be recovered from facts. 13. **Condition.asserter** is set to the person on every lifted condition (the model's conditions are what the person reports); a clinician-asserted condition is carried with a named change, not left out. 14. **Two Devices**: no source is carried, rather than attributing every fact to one of them. 15. **Intervals**: same-state Periods that overlap or touch, or a state given as daily facts, become their union (`state-merged`, a spelling change; the profiles' `cy-b-interval-merge` rejects such a Bundle, although `fromBundle` reads it). 16. **Lazy measuring** can, in principle, pick a different step than measuring every candidate when a step on one part shifts another part's saving by a byte; on the 14 personas the plans reach the same targets, and `run.exhaustive` restores the reference behaviour. 17. **What counts as a loss in the lift** (`LOSES`). Not losing: `layer0-added` (the bleeding fact a flow fact implies is added), `device-attributed` (a fact is attributed to the card's only source), `asserter-added` (the person named as asserter where none was given), `value-as-quantity`, `unit-assumed`, `period-to-day` for dates only, `medication-inlined`, `medication-resource`, `window-inferred`. The first three add an assertion rather than drop one; if adding counts as changing what the card says, they should flag too. Losing, though small: `element-dropped` for `Patient.active` true or `deceasedBoolean` false, `Condition.verificationStatus` confirmed, and `bundle-type` (a searchset read as a collection). 18. **Modifier values that could be fixed values in the model's output** (for the model owner; `to-bundle.ts` is unchanged, and until a decision these block like the others): - `Patient.active = true`: R4's `meaningWhenMissing` for Patient.active is "generally assumed to be active if no value is provided". So `true` means exactly what absence means. It could be declared an equivalence (no change to the output), or emitted always. MAPPING.md §1 chose `id` over `active: true` for the identity-free Patient because `active` asserts more; that choice stands if it is an equivalence. - `HumanName.use = usual` ("the name normally used"): the model's name is the name the person goes by, so `toBundle` could always emit `use: "usual"` on the name. R4 also says a name without a use can be assumed current, but that is not the same as `usual`. `official` would claim a legal name the model does not know, and is not a candidate. - `Device.status = active`: the source application was in use when it exported. `toBundle` could always emit it on the Device. R4 gives no meaning when missing. - Not candidates: `Condition.verificationStatus = confirmed` (MAPPING.md §1 already decided against it: it claims more than a self-report can); `Medication.status = active` (the output has no Medication resource; medications are codes on MedicationStatements). 19. **The Patient left out for a modifier still carries the facts**, as the identity-free Patient. The facts are about the person whatever the Patient resource says. Leaving every fact out for a Patient.link or deceased flag would empty the card. 20. **A Device left out for its status** leaves every Observation that named it without its device; the alternative, leaving those Observations out, would empty the card for a provenance detail. 21. **Guide codes** are not recognised by default (they lift exactly, as custom series, without bleeding semantics); the opt-in `guideCodes` recodes them as a reported change that loses nothing. Default-off keeps the project self-contained and never reinterprets an outside code silently; opt-in keeps real guide Bundles usable. 22. **Times of day on entries (wave 5).** The lifter writes one entry per fact. Time steps apply to every entry; entries that become alike stay separate (wave 8). 23. **Spelling changes that add rather than respell** (`layer0-added`, `device-attributed`, `asserter-added`) are in the spelling class: they lose nothing, but they do assert something the input did not say. 24. **meta.profile** is conformant only when it names the resource's own profile, as `fromBundle` accepts it; a sibling profile of this project, any other URL, or a repeat is an element the card does not carry (`element-dropped`, a loss). 25. **A time without seconds** is not an R4 dateTime: its time is dropped (`time-dropped`, a loss) and the fact is carried on its day, rather than the whole fact being left out as malformed. 26. **One unit per component code on the card** (wave 6): the most common shape and unit over every components series, so a component shared by two series converts (exactly) or drops in the series that differs. 27. **Where the lifter still chooses one of several**, each because the model holds one: the window (a second tracking-window Observation is left out, `window-duplicate`); the person (the Patient most facts are about; facts about another are `other-subject`); one shape per custom series code and one unit per series or component code (the most common; others convert exactly or are left out); one kind of skin temperature per card (the most common; the other kind is `conflict`); one label per concept (the most frequent display; `label-conflict`). ## Findings outside this directory No defects found in `model.ts`, `to-bundle.ts` or `coarsen.ts` while building on them. Gaps that set the lifter's boundaries: - Free text (`valueString`, notes) has no place, so an app's diary entries are left out. - 8310-5 can only be BBT, so a fever log coded 8310-5 is carried as BBT entries rather than as a temperature series of its own (judgment call 4). - `site/shared/qrfit.ts` computes capacity at level L only; `plan.ts` has its own capacity for every level (same method).