SHC vNext QR proof of concept

cycle-log: lifting Bundles and fitting cards to a size

Rendered from codecs/cycle-log/lift/LIFT.md in the repository.

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

filewhat
lift.tslift(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.tsCONFORMANT and SPELLING (the three-outcome table below) and equivalentBundles(a, b), which compares two Bundles modulo exactly those
steps.tsthe step catalogue: candidates(model, hints), applyStep(model, step), the PRIORITY table, the verified PARENTS merges
plan.tsplan(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.tsbun codecs/cycle-log/lift/reductions.ts measures every option, approved or not, on every persona; writes REDUCTIONS.md and reductions/*.json
cli.tsbun codecs/cycle-log/lift/cli.ts <bundle.json or model.json> --target v22-L --viewer prints the lift report, the plan and the frontier
variants.tsreshaped and degraded copies of a Bundle, for the tests
lift.test.ts, plan.test.tsthe 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:

inputbecomes
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 resourcesresolved; 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 idresolved (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 statussource (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 codingsthe 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 daya 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 daysa 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 daymedications (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 codeconditions with the stated status and HistoryDate onset (1900–2150)
a custom quantitymagnitude 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 hundredthscarried 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 categorya 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 componentcarried 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 resourcereduced: true, a named change (the model's flag is card-wide)
proposed basal-body-temperatureBBT (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 daythat 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, conditionsevery 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 factthe 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:

inputreason
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 componentsvalue-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 unitcomponent-dropped: that component only; the rest of the reading is carried (named change)
more than 16 components in a reading, or the same component twicelimit, malformed
a vitals panel 85353-1 with only hasMemberno-value (the members are carried as their own series)
a vital-sign code as a state over daysvital-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 groupwhatwhen allowed
retractedstatus entered-in-error on any resource; Condition.verificationStatus refuted / entered-in-error; a Medication entered-in-error used by a MedicationStatementleft out
not-finalObservation status other than final (amended and corrected included); MedicationStatement active / intended / stopped / on-hold / unknown; Procedure other than completedleft out
negatedProcedure status not-doneleft out
data-absentObservation.dataAbsentReason, or a component'sleft out
modifiermodifierExtension 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 confirmedleft out; for HumanName.use, that name is left out
other-subjecta subject that is not the person, Observation.focusleft out
qualifiedQuantity.comparator, on a value or on a componentleft out
uncertainCondition.verificationStatus unconfirmed / provisional / differentialleft 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.

outcomewhatreportcard
conformantrepeated 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 writesnothingas is
spelling changeZ 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: falsenot flagged; strict mode refuses
lossanything 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 exclusiona named change or exclusion, loss: trueflagged 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.

measureapprovedrejected
times of daydropped (facts keep their dates)every rounding rung (1, 5, 15, 60 minutes)
basal temperature, wearable skin temperature (absolute and deviation), body-temperature vital signsas recorded (0.01° preserved)every grid rung (0.05, 0.1, coarser)
sleep durationas recorded (exact minutes)every grid rung (5, 15, 30, 60 minutes)
blood pressureas 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 recordedevery rung
numeric and ordinal scales (pain, mood, energy, flow level), codesas recordedbands, shorter scales, flow levels as "bleeding", parent codes
history datesas recordedmonth, 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 daysapproved

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.
kindeffect
times with drop; labels; flow-none; negatives; thin; omit; windowomits
times with a rung; grid; history; points; parent; bands; flowalters (all rejected)

Loss classes

classnameapproved options
0nonea label that only repeats its code
1time of daytimes dropped; per series, for answers and procedures, or card-wide
2presentationdisplay text of human-readable app codes; the flow scale's "none" fact
3precisionnone (all value-altering precision rungs rejected)
4scalenone (all scale collapses rejected)
5omissionseveral 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
6windowthe 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.

#partwhy
1sourceprovenance (the exporting app); the data do not depend on it
2energya 4-point self-rating with no clinical threshold
3mooda 7-point valence; useful for premenstrual patterns, rarely decisive
4sleepwellness context; large and noisy, little cycle information
5skinTempa wearable's nightly temperature; overlaps BBT where both exist, device-specific
6customapp- or person-specific series; their meaning rests on labels a receiver may not know
7sexfertility context; sensitive, and rarely needed by a receiver
8mucusfertility-awareness sign; meaningful mainly to the person's own method
9symptomspremenstrual and dysmenorrhea pattern; often summarized by pain
10ovulationTestovulation timing; partly recoverable from BBT
11progesteroneTestconfirms ovulation; rare
12bbtbiphasic pattern: ovulation and luteal length
13vitalscustom 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
14medicationsanalgesics, tranexamic acid, iron: treatment context
15pilladherence explains breakthrough bleeding on the pill
16volumethe only calibrated amount for heavy menstrual bleeding
17paindysmenorrhea severity, a common reason to see a clinician
18answersthe person's own summary answers; a few bytes
19conditionsexplain a bleeding pattern (PCOS, fibroids, ...); a few bytes
20procedureschange what bleeding means (ablation, hysterectomy, IUD); a few bytes
21intervalscontraception, pregnancy, breastfeeding change what bleeding means
22pregnancyTesta positive test changes everything; a few bytes
23bleedingthe 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:<code> 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.

kindscopeparametersclassstatuswhat the card no longer carries, or what it changes
labelsredundant–0approvedCoding.display / CodeableConcept.text strings on coded escapes equal to their code (never strips text on text-only { text } concepts)
timesa series name, custom:<code>, events (answers and procedures), alldrop1approvedtimes of day (strips T… from date); the facts keep their day
timessame1, 5, 15, 60 (minutes)1rejectedtimes rounded
labelscustom:<code>, other–2 (or 5 if protected)approvedoptional 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-nonebleeding–2approvedthe flow fact "none" beside an explicit no-bleeding
gridbbt, skinTemp, body-temperature vital signs, sleep, volume, custom:<code>, or one quantity componentthe grid3rejectedvalues rounded
historyhistorymonth, year3rejectedday, then month, of procedure dates, condition onsets, the birth date
pointsmood (5, 3), energy (2)the scale4rejectedlevels collapsed
parentsymptoms, sexthe parent4rejectedcodes replaced by a verified parent
bandspain–4rejectedscores replaced by bands
flowbleeding–4rejectedflow levels replaced by "bleeding"
negativesbleeding, pain, sex, custom:<code> (boolean)–5approvedexplicit negatives
thina series name or custom:<code>first, last, max; a set series: first5approvedall but one entry a day (a set: each item once); a reading is kept or left out whole
omitcustom:<code> with component–5approvedone component of every reading; never for a code whose R4 profile fixes its components (blood pressure)
omitany part on the card–5approvedthe whole part
windowwindowdays cut6approvedthe 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:<code>, 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:

optionwhat
codeca 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
signalan AbortSignal; aborting rejects with its reason
shouldStop()returning true ends the search; the result has stopped: true and the frontier found so far
pointModelseach frontier point carries its reduced model (else pointModel(result, i) applies its steps to result.original)
compactleave rounds out
exhaustivesee 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):

personabefore ms, full frontierafter ms, full frontierafter: encodesafter ms, stopping at the target
power-tracker2425492110198
copper-iud566221781
pcos681157593
minimal231161
perimenopause570155484
combined-pill344115433
near-empty231491
own-vocabulary27051075180912
wellness-diary1643565106481
calendar-only3924133
smart-cup-hmb510185644
wearable218103374
post-ablation350186601
vitals-follow-up656295775
total1075235971620

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.

949 card bytes; approved options only. ◀ marks the plan. Step ids shorten app systems to custom:<code> and LOINC to LOINC <code>.

power-tracker, 1154 bytes untouched (25-L); plan: 5 steps → 890 bytes (22-L); 499 ms

pointcard bytesQRhighest classsteps added
0115425-L–(untouched)
1113125-L2flow-none(bleeding)
2104024-L3grid(bbt, 5)
3100323-L3grid(bbt, 10)
498223-L5omit(source)
5 ◀89022-L5omit(energy)
678220-L5omit(mood)
760218-L5omit(sleep)
859718-L5negatives(sex)
955617-L5omit(sex)
1048416-L5omit(mucus)
1130812-L5omit(symptoms)
1227612-L5omit(ovulationTest)
1326311-L5omit(progesteroneTest)
141398-L5omit(bbt)
151138-L5omit(medications)
16917-L5negatives(pain)
17615-L5omit(pain)
18525-L5omit(intervals)
19455-L5omit(pregnancyTest)
20354-L5negatives(bleeding)
2183-L5omit(bleeding)

own-vocabulary, 1573 bytes untouched (30-L); plan: 10 steps → 949 bytes (22-L); 1108 ms

pointcard bytesQRhighest classsteps added
0157330-L–(untouched)
1155429-L0labels(redundant)
2153829-L2labels(other)
3149129-L2labels(custom:flowly
4144928-L2labels(custom:flowly
5143828-L2labels(custom:flowly
6143728-L2flow-none(bleeding)
7133127-L3grid(sleep, 5)
8123226-L3grid(skinTemp, 5)
9119525-L3grid(skinTemp, 10)
10 ◀94922-L5omit(sleep)
1180621-L5omit(skinTemp)
1253717-L5omit(custom:flowly
1341315-L5omit(custom:flowly
1432613-L5omit(custom:flowly
1530712-L5omit(custom:431416001)
1628612-L5omit(custom:25064002)
1725211-L5omit(sex)
181348-L5omit(symptoms)
191067-L5omit(medications)
20947-L5omit(intervals)
21535-L5negatives(bleeding)
22254-L5omit(bleeding)

wellness-diary, 1862 bytes untouched (32-L); plan: 7 steps → 769 bytes (20-L); 581 ms

pointcard bytesQRhighest classsteps added
0186232-L–(untouched)
1185232-L0labels(redundant)
2179532-L2labels(custom:codes
3178432-L2labels(custom:codes
4167431-L3grid(sleep, 5)
5141828-L5omit(sleep)
6138427-L5negatives(custom:37796009)
7 ◀76920-L5omit(custom:LOINC 41950-7)
848716-L5omit(custom:codes
931312-L5omit(custom:codes
1019410-L5omit(custom:codes
111819-L5omit(custom:37796009)
12736-L5omit(medications)
13244-L5omit(pain)
1483-L5omit(bleeding)

timestamped, 1937 bytes untouched (33-L); plan: 8 steps → 866 bytes (21-L); 1203 ms

pointcard bytesQRhighest classsteps added
0193733-L–(untouched)
1178532-L1times(mood, drop)
2148629-L1times(bbt, drop)
3129526-L1times(symptoms, drop)
4111825-L1times(energy, drop)
5103223-L1times(ovulationTest, drop)
696323-L1times(sex, drop)
796223-L1times(pregnancyTest, 1)
8 ◀86621-L1times(bleeding, drop)
978420-L1times(pain, drop)
1074019-L1times(medications, drop)
1173919-L1times(events, 5)
1273419-L1times(events, drop)
1373019-L1times(pregnancyTest, drop)
1464118-L3grid(bbt, 5)
1560818-L3grid(bbt, 10)
1659117-L5omit(source)
1751016-L5omit(energy)
1840414-L5omit(mood)
1936513-L5omit(sex)
2036113-L5thin(symptoms, first)
2127812-L5omit(symptoms)
2224811-L5omit(ovulationTest)
231138-L5omit(bbt)
241097-L5thin(medications, first)
251017-L5omit(medications)
26876-L5thin(pain, first)
27866-L5negatives(pain)
28656-L5omit(pain)
29615-L5omit(answers)
30585-L5omit(procedures)
31555-L5omit(intervals)
32525-L5omit(pregnancyTest)
33385-L5thin(bleeding, last)
3483-L5omit(bleeding)

bp-twice-daily, 1801 bytes untouched (32-L); plan: 7 steps → 679 bytes (19-L); 561 ms

pointcard bytesQRhighest classsteps added
0180132-L–(untouched)
1156329-L1times(all, 5)
2135827-L1times(custom:LOINC 85354-9, drop)
3118025-L1times(medications, drop)
4102423-L1times(custom:LOINC 8867-4, drop)
5100323-L5omit(source)
699423-L5omit(symptoms)
7 ◀67919-L5thin(custom:LOINC 85354-9, max)
826711-L5omit(custom:LOINC 85354-9)
9766-L5omit(custom:LOINC 8867-4)
10435-L5omit(medications)
11375-L5omit(conditions)
1283-L5omit(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:<code>", ...] 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).