# 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).