A content-addressed (0x00 || sha256(wasm)) WebAssembly codec conforming to CODEC-ABI v0.1 that packs 100% lossless Continuous Glucose Monitoring (CGM) histories into a single dense QR code and decodes directly into an HL7 FHIR R4 CGM Implementation Guide Bundle — including deterministically computed CGM Summary / Ambulatory Glucose Profile (AGP) metrics at zero extra QR bytes.
Module Identity & Audit
- Binary:
cgm-agp.wasm— 43,565 bytes (42.5 KiB) - SHA-256:
f57b5d846fea9c2ad54a06b77b9c48458d88b367610b0788997e7e00a4e58dac - Exports:
memory,shc_alloc,shc_decode,shc_encode - Imports:
0(link-time zero-panic guarantee — any reachable panic turns into an unresolved import) - Static Audit (
auditWasm): 0 violations —#![no_std],#![forbid(unsafe_code)]incore, zero floating-point opcodes, zero SIMD/threads/reference-types, declared memory max 1 GiB.
Benchmarks (Real FreeStyle Libre & T1D Showcase Samples)
All SHA-256 cards include the full 33-byte content-addressed header (0x00 || sha256(wasm)) plus the 2-byte SHA-256 card check (35 B envelope overhead), measured at QR Error Correction Level L using numeric-mode packing (bytesToDigits).
| Sample | Readings | Precision | FHIR JSON B | DEFLATE B | Codec Input B | SHA-256 Card B | QR Version-L | Ratio vs FHIR | Ratio vs DEFLATE | Decode |
|---|---|---|---|---|---|---|---|---|---|---|
libre-14d | 4,019 | minute | 2,321,772 | 48,724 | 1,860 | 1,895 | V32 | 1,225× | 25.7× | ~9 ms |
libre-7d-exact | 2,016 | second | 1,172,854 | 26,730 | 1,556 | 1,591 | V29 | 737× | 16.8× | ~7 ms |
t1d-variable-14d | 3,792 | minute | 2,191,891 | 50,354 | 1,546 | 1,581 | V29 | 1,386× | 31.8× | ~8 ms |
clinic-3d-compact | 864 | minute | 502,720 | 11,746 | 484 | 519 | V16 | 969× | 22.6× | ~5 ms |
Showcase Samples (examples/)
libre-14d.json— Real 14-day FreeStyle Libre dataset (4,019 readings,2024-08-07to2024-08-21, minute grid, mean104.9 mg/dL, GMI5.8%, CV13.8%, 99.2% TIR, 100.0% active wear).libre-7d-exact.json— Last 7 days of the real FreeStyle Libre dataset (2,016 readings, preserving exact 1-second timestamps and exact integer mg/dL values).t1d-variable-14d.json— Synthetic 14-day Type 1 Diabetes trace (3,792 readings across 4,032 slots, 94.0% active wear) with post-prandial spikes (220–290+ mg/dL), nocturnal hypoglycemia (<70and<54mg/dL), Dawn phenomenon, all 5 TIR bands non-zero (<54: 2.3%,54–69: 1.9%,70–180: 58.8%,181–250: 23.1%,>250: 14.0%), GMI7.4%, and CV36.7%.clinic-3d-compact.json— Last 3 days of the real FreeStyle Libre dataset (864 readings, minute grid) fitting a compact Version 16 QR code.
All showcase records use fictional patient identities. Source data script: scripts/fetch-cgm.ts.
Input Model (CgmRecord)
Defined in model.d.ts and validated in model.ts:
export interface CgmRecord {
patient?: { family?: string; given?: string[]; birthDate?: string };
device?: { name: string; serialNumber?: string };
utcOffset: string; // e.g. "-05:00", "+00:00" (-12:00..+14:00, no "-00:00")
timePrecision: "minute" | "second";
nominalIntervalMin: number; // integer 1..60 (typically 5 or 15)
readings: {
time: string; // strict chronological ISO timestamp matching timePrecision & utcOffset
mgdl: number; // exact integer 20..600 mg/dL
}[];
}
FHIR R4 Output (HL7 CGM IG)
shc_decode emits canonical minified UTF-8 JSON for a FHIR R4 Bundle (type: "collection"):
Patient(id: "0",fullUrl: "resource:0")- Optional
Device(id: "1",fullUrl: "resource:1") - 7 Deterministic HL7 CGM IG Summary Observations (computed purely in 64/128-bit integer arithmetic inside WASM — zero floats, zero QR bytes):
Observation/cgm-summary(cgm-summary) witheffectivePeriodandhasMemberreferences to the 6 metrics belowObservation/mean-glucose-mass-per-volume(LOINC97507-8, 1-decimalmg/dL)Observation/times-in-ranges(times-in-ranges, all 5 disjoint components:<54,54–69,70–180+ LOINC97510-2,181–250,>250, 1-decimal%)Observation/gmi(LOINC97506-0, Bergenstal formula3.31 + 0.02392 * mean_mg_dlin exact 64-bit integer fixed-point math to 1 decimal%)Observation/cv(LOINC104638-2,100 * SD / meanvia shift-and-subtractisqrt_u128to 1 decimal%)Observation/days-of-wear(distinct local calendar days with readings, unitd)Observation/sensor-active-percentage(readings.length / expected_slots_in_span, 1-decimal%clamped to100.0%)
- Every individual glucose reading (
id: "g-0","g-1", …) as a FHIR R4Observationwith LOINC99504-3(Glucose [Mass/volume] in Interstitial fluid), exacteffectiveDateTime, exact integervalueQuantity(mg/dL),subject: Patient/0, and optionaldevice: Device/1.
Wire Format & Compression
- Header: version byte (
0x01), flags (timePrecision,predictor,has_patient,has_device,all_nominal_dt),nominal_interval_min, encodedutcOffset, LEB128 reading count (1..16384), initial local timestampt0(u32) and glucoseg0(u16), plus optional length-prefixed Patient/Device metadata. - Timestamps: When every step equals
nominal_interval,all_nominal_dt = 1codes timestamps in 0 bits. Otherwise,dt - nominal_stepis zigzag-coded through a 2-context adaptive 4-bit binary tree (BitTree16) + bounded Exp-Golomb escape. - Glucose Values: The encoder evaluates both 1st-order (
x[n-1]) and damped 2nd-order (x[n-1] + ((x[n-1] - x[n-2]) >> 1), clamped to20..600, falling back to 1st-order across sensor gapsdt > 2 * nominal) and selects the strictly shorter stream (1-bit header flag). Zigzag residuals are coded with a 5-context activity-adaptive range coder keyed by|x[n-1] - x[n-2]|(0,1,2–3,4–7,8+or gap) using count-basedBitTree16models + bounded Exp-Golomb escape. - Strict Canonicality:
decodeverifies that re-encoding the decoded record reproduces the input bytes identically, guaranteeing every dataset has exactly one valid encoding.
Building & Testing
# Build cgm-agp.wasm
bash codecs/cgm-agp/rust/build.sh
# Run full audit, round-trip, canonicality, fuzz, and benchmark suite
bun test codecs/cgm-agp/cgm-agp.test.ts