SHC vNext QR proof of concept

Architecture & data flow

How menstrual-cycle and health tracking (days, months, or years — up to 10,000 days, bounded naturally by QR capacity; typically 250 KB–1 MB+ of FHIR JSON) fits inside a single offline phone-scannable QR code (300–1,960 bytes), what each component does, and where every clinical safety boundary sits.

Six core pieces

1. Input model

A small, typed JSON structure (CycleLog) representing only the clinical facts—days, bleeding, pain, BBT, medication doses, exclusions, custom series—stripped of FHIR boilerplate.

2. Lifting (FHIR → model)

Translates an arbitrary real-world FHIR R4 Bundle (EHR, wearable, portal export) into the input model while reporting every item kept, reshaped, dropped, or blocked on safety modifiers (lift.ts).

3. Planning (fit to QR budget)

When a model is too big for a target QR size (e.g. Version 22-L = 949 B with viewer link), tries named omission-only steps (drop times, thin repeats, omit low-priority series, trim oldest cycles) without ever altering a recorded value.

4. Codec (model ↔ bytes)

Compresses the normalized input model into a minimal canonical binary stream in a zero-import, zero-float, zero-panic 345 KB Rust WebAssembly module (cycle-log.wasm), and expands bytes back into a standard FHIR R4 Bundle on the receiver.

5. Transport (bytes ↔ QR)

Wraps payload bytes as [codec id][payload][2B SHA-256 check], then packs every 7 bytes into 17 decimal digits so the QR uses high-density Numeric Mode (98.8% of raw binary capacity).

6. Reduced flag (SUBSETTED)

A 1-bit flag on the card (emitted as FHIR Bundle tag SUBSETTED) telling receivers that something from the original source was omitted during lifting or planning; everything present is still verbatim.

Diagram 1: End-to-end architecture & data flow

There are two ways onto a card: an app can fill in the input model directly (never constructing FHIR), or an existing FHIR R4 Bundle can be lifted into the input model. On the receiving phone, no server is contacted—the codec deterministically reconstructs a standard FHIR R4 Bundle locally.

SENDER DEVICE (APP / EXPORT TOOL) RECEIVER DEVICE (OFFLINE, NO SERVER) Tracking App Writes model directly (never builds FHIR) Existing FHIR R4 EHR / Portal / Wearable ~250 KB – 1.2 MB JSON LIFTER Checks isModifier 8310-5 ≠ BBT Emits Lift Report INPUT MODEL CycleLog JSON validate() + normalize() Explicit negatives Doses & exclusions Custom series / escapes PLANNER Omission-Only Loop Only if card > target Never alters values Sets reduced=true too big? reduced model CODEC shc_encode() Range coder + dominant grids measures exact bytes QR CODE (shc2:/00599451...) [1B codec id 1] [payload] [2B SHA-256] 7 bytes → 17 digits • ~300–1,960 B pack() camera scan CODEC shc_decode() 1. Verify 2B SHA-256 2. Decode & validate 3. Re-encode check (canonical bytes only) FHIR R4 Bundle toBundle(model) Standard Observations, Meds, Procs, Conditions Viewer / EHR Charts & cycles Flags SUBSETTED Shows exclusions Key Guarantee FHIR out, never FHIR in the QR. 100% deterministic.

Diagram 2: Deep dive — lifting, input model, and omission-only planning

These three stages all touch clinical meaning, so each has a strict, separate boundary: Lifting safely ingests messy FHIR without dropping modifiers, the Input model defines the exact clinical vocabulary, and Planning shrinks a valid model to fit a QR budget using omissions only.

A. LIFTING (lift/lift.ts) Job: Messy FHIR R4 → Clean Input Model 1. Strict isModifier Safety Gate • entered-in-error / refuted → BLOCK (retracted) • Quantity.comparator (<, >) → BLOCK (qualified) • dataAbsentReason, modifierExtension → BLOCK • HumanName.use, Patient.deceased → BLOCK Never strips a modifier; caller must allow omission. 2. Clinical Routing & Exact Conversions • LOINC 8310-5 (fever) → vital-sign custom series • basal-body-temperature → built-in bbt • reading-excluded component → TempEntry.excluded • dosage.doseQuantity → MedEntry.dose • Exact UCUM only (h→min, L→mL, cm[Hg]→mm[Hg]) 3. Item-by-Item Accounting Every input resource gets one outcome: exact | changed | left-out | blocked Any loss sets reduced=true (SUBSETTED). Strict mode accepts conformant Bundles losslessly. B. INPUT MODEL (model.ts) Job: Canonical Truth of What a Card Can Say Uniform { date, ... }[] & Absence • Omitted entry / [] / absent = "Not recorded" (never "no") • Explicit negative = "no-bleeding", pain 0, "not-taken" Repeats & same-day disagreements kept verbatim; all fields optional ({} valid); no root labels or window. Keywords, CodeableConcept & Decimals • FHIR DateTime (≤10,000d span; Z & :00 accepted) • Readable keywords + FHIR CodeableConcept ({text} ok) • Natural decimals (36.52 °C, 12.5 mg); 0 floats in WASM • Unified procedures, meds w/ dose, opt Patient/Source • Up to 32 custom series (valueType: bool/coded/qty/comp) Canonical Normalization • Canonical keyword, CodeableConcept & date order • Touching/overlapping identical intervals merged • Entries sorted: date-only first, then UTC instant Guarantees: same clinical facts ⇒ identical bytes. C. PLANNING (lift/plan.ts) Job: Fit Model Into QR Budget (Omission-Only) Ordered Loss Classes (Mildest First) Class 0: Drop redundant display (code == display) Class 1: Drop times of day (dateTime → date) Class 2: Readable-code displays & flow-none Class 5: Thin days / negatives / omit series Class 6: Trim oldest cycles from record Clinical Safety Guardrails • No value alteration: exact 0.01° temps, exact sleep, no time rounding, no pain banding. • BP & multi-component safety: never split BP or max-thin multi-component panels. • source coupled to skinTemp: keeps device name while wearable temp stays on card. • Opaque & rich-display guard: keeps display on IDs & free-text phrases; supports pin hints.

Diagram 3: Inside the codec — outlier-resilient & simple by design

The codec replaces multi-level Bayesian mixtures and cycle-phase prediction with three small integer primitives (2-level KT probability chains, Elias-style signed/unsigned integer coding, and script-neutral LZ77 UTF-8 text coding) plus four structural fixes that eliminate single-entry outlier cliffs.

1. Dominant Grid + Per-Value onGrid Bit (Fixes Numeric & Time Cliffs) Pure GCD: 364 sleep values on 15-min steps + 1 value of 421 ⇒ gcd = 1 (all 365 pay 15× residuals) Dominant ≥75%: picks g = 15; 364 on-grid pay ~0.04b flag + tiny step; 1 outlier pays exact residual Measured stress test: num-grid-outlier 716 B → 424 B (-292 B / -40.8%) 2. Per-Entry Seconds Flag (Fixes Mixed Manual + Device Exports) Series flag: 1 timestamp at :17 among 364 at :00 forces uni(60) (~5.9b) on all 365 readings Adaptive bit: each reading codes hasNonZeroSec (~0.04b when rare), then uni(59) only on :17 Measured stress test: seconds-outlier 806 B → 534 B (-272 B / -33.7%) 3. Circular Midnight-Safe Clock (mod 1440) Linear clock: 23:50 and 00:05 are 1,425 min apart; habit EMA averages them to ~12:00 noon Modular clock: wrapDelta(m, habit) ∈ [−720, +719]; 23:50 → 00:05 is +15 min; habit stays at midnight Measured stress test: midnight-shift 1,046 B → 676 B (-370 B / -35.4%) 4. 2-Level KT + LZ77 Shared UTF-8 History + 345 KB Zero-Panic WASM • Script-neutral LZ77 back-references over shared UTF-8 history compress free-text labels & non-Latin names. • Zero-import, integer-only Rust WASM (345 KB vs ~599 KB earlier; 0 traps in 35,000 fuzz inputs). Result: -38% WASM size • 9–56 ms decode • -12% to -41% on outlier stress cases

Diagram 4: Measured card sizes across sample records & stress tests

Exact card bytes (codec output + 1B codec id + 2B SHA-256 check). Vertical dashed lines mark the comfortable phone-scan threshold (Version 22-L, 983 B bare) and stretch line (Version 30-L, 1,703 B bare).

cycle-log WASM (345 KB, zero-panic, LZ77 + dominant grids) Earlier pure-GCD / linear-clock baseline (stress tests) 0 B 500 B 983 B (Version 22-L) 1,500 B 1,703 B (Version 30-L) 2,000 B REPRESENTATIVE SAMPLE RECORDS (OUT OF 20 MEASURED) copper-iud (365d) 320 B (Version 12-L) bbt-exclusions-and-fever 600 B (Version 17-L, BBT + fever vital sign + exclusions) vitals-follow-up (HR, wt, BP) 713 B (Version 19-L) power-tracker (365d) 1,242 B (Version 25-L) med-doses (with RxNorm doses) 1,246 B (Version 25-L, +4 B over power-tracker) own-vocabulary (custom labels) 1,619 B (Version 30-L, LZ77) bp-twice-daily (2×/day BP) 1,815 B (Version 32-L) timestamped (every fact timed) 1,960 B ADVERSARIAL OUTLIER & SHIFT STRESS TESTS (DOMINANT GRIDS + MOD-1440 CLOCK) seconds-outlier (1 :17) 806 → 534 B (-33.7%) time-grid-outlier (1 07:01) 629 → 513 B (-18.4%) num-grid-outlier (sleep/BBT) 716 → 424 B (-40.8%) midnight-shift (23:35–00:25) 1,046 → 676 B (-35.4%) gridded-multi-bp (2×/day) 610 → 535 B (-12.3%)