SHC vNext QR proof of concept

cycle-log: model design

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

The goal is a whole year of rich menstrual-cycle tracking in one small QR code. This directory defines what such a card can say (model.ts, vocab.ts) and the FHIR Bundle it stands for (to-bundle.ts, MAPPING.md). It also provides fourteen synthetic years (sample.ts), their sizes with an entropy target (report.ts), an audit of what real apps store against what the card can carry (EXPRESSIVENESS.md), and the tests (bun test). A codec (Rust → WebAssembly) and a viewer build on this contract.

Design rule. Built-in series, tables and scales are shortcuts that make expected content cheap. They never limit what can be said:

  • every coded value accepts any concept from any code system as an escape;
  • concepts outside the built-ins may carry a label;
  • anything without a built-in slot goes into one of three custom-series shapes, or a custom interval or procedure.

What remains unrepresentable is listed, with the reason, in EXPRESSIVENESS.md §3.

Files

filewhat
vocab.tscode systems, the concept-key syntax and its limits, all built-in tables and codes
model.d.tsthe normative definition of the model: TypeScript types only, every field documented, the built-in tables as documented literal unions
model.tsvalidate, validateJson, normalize and the limits (with vocab.ts, the source of truth for what is accepted); its types come from model.d.ts
model.schema.jsonJSON Schema 2020-12 derived from model.d.ts and the constants (written by make-schema.ts, with the generated sections of this file)
examples/every persona's normalized model (<persona>.model.json, generated) and the hand-written minimal-teaching.model.json with its line-by-line explanation
make-schema.tsderives model.schema.json, examples/<persona>.model.json and the generated sections of this file from model.d.ts and the constants (bun make-schema.ts --write)
json-schema-lite.tstest support: a validator for the JSON Schema keywords the schema uses
to-bundle.tstoBundle, stringify (canonical bytes), fromBundle
MAPPING.mdFHIR representation, entry order, canonical form, code evidence, validation status
EXPRESSIVENESS.mdfield-by-field audit of HealthKit, Clue, Flo, Natural Cycles, Fitbit, Samsung and drip; the "not representable" list
CodeSystem-cycle-log.jsonthe proposed concepts, https://joshuamandel.com/shc2-poc/CodeSystem/cycle-log (CYCLE_LOG_CS in vocab.ts), with definitions (written by make-codesystem.ts)
codes-verified.jsontx.fhir.org $lookup evidence for every standard code (bun verify-codes.ts)
sample.tsgenerate(options), SAMPLES (14 personas); re-exports coarsen
coarsen.tscoarsen(model, options): a coarser grid for sleep, mood, BBT, skin temperature and volume
import-ics.tsimportIcs(text, options): bleeding days from an iCalendar export (tested in import-ics.test.ts, fixtures in fixtures/ics/)
calendar-sample.tsthe synthetic year-long calendar persona (j) is imported from (also fixtures/ics/calendar-year.ics)
report.tsmeasurement tables (bun report.ts)
golden.jsonSHA-256 of every sample's model and canonical Bundle (bun golden.ts --write)
r4-structure.ts, hl7-validate/offline R4 structural checker; HL7 validator runner
cycle-log.test.ts, model-schema.test.ts, import-ics.test.tsthe model, schema and importer tests

1. Writing an exporter: the smallest valid model

The model is one JSON object. The smallest valid model is a window and nothing in it:

{"start": "2026-01-05", "days": 90}

It is valid but says nothing. The smallest useful model adds one per-day series. examples/minimal-teaching.model.json is three months of bleeding days and nothing else, explained line by line in examples/minimal-teaching.model.md. Every persona in §12 is published as a full example in examples/<persona>.model.json.

To write an exporter:

  1. Pick the window: start is the first day, days its length (at most 10,000). Day i is start + i.
  2. For each thing the app logged, find its field in §2. Write per-day values at their day index, null where nothing was logged. A day with several entries, or entries with times of day, is written as entries (§8).
  3. Write only what the person logged. Leave out what they did not; never fill in a negative (§3).
  4. For a value without a built-in name, write a concept (§4). For a whole kind of data without a field, add a custom series (§5).
  5. Check the result with validateJson (or the codec's encoder, which refuses exactly what it rejects). The JSON Schema catches shape errors in any language; the rules in §6 need validate.

2. Field reference

Generated from model.schema.json, which is derived from model.d.ts; the types file has the same text as TSDoc. "Required" means the field must be present; every other field may be absent or null. A per-day array has one entry per day from day 0; a type such as array (≤ 10000) of Bleeding | null means the entries are Bleeding values or null.

Shared shapes

nametypemeaning
CalendarDatestring (pattern)A calendar date YYYY-MM-DD from 2000-01-01 to 2099-12-31 (real Gregorian date). Used for interval start and end bounds.
DateTimestring (pattern)A FHIR dateTime on the daily tracking timeline (2000-01-01 to 2099-12-31): either a calendar date YYYY-MM-DD (day precision) or a date with local time and quarter-hour UTC offset YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM). "Z" is accepted and normalized to "+00:00"; ":00" seconds are accepted and omitted canonically; "-00:00" is rejected.
FhirDatestring (pattern)A FHIR date of year, month or day precision: YYYY, YYYY-MM or YYYY-MM-DD, from 1900 to 2150. Used for patient birth date and condition onset.
FhirDateTimestring (pattern)A FHIR dateTime for procedures (year 1900 to 2150): YYYY, YYYY-MM, YYYY-MM-DD, or YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM). "Z" is accepted and normalized to "+00:00"; ":00" seconds are omitted canonically; "-00:00" is rejected.
FhirInstantstring (pattern)A FHIR instant with calendar date (2000-01-01 to 2099-12-31), time of day, optional seconds and quarter-hour UTC offset: YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM). "Z" is accepted and normalized to "+00:00"; ":00" seconds are omitted canonically; "-00:00" is rejected. FHIR Bundle.timestamp always emits seconds.

The model object

One card: consumer cycle tracking as uniform dated arrays. An empty object {} is valid.

fieldrequiredtypemeaning
patientPatientInfo, or nullWho the card is about, kept deliberately small. Not recorded: absent or empty; the card then carries no identity at all.
sourceSource, or nullThe source app: its name and optional version. Not recorded: absent.
exportedAtFhirInstant, or nullWhen the card was exported, as a FHIR instant with UTC offset (mapped to FHIR Bundle.timestamp). Not recorded: absent.
reducedboolean, or nullThe sender deliberately left out data to fit a size: a series, time of day, or display that is absent may have been tracked; recorded values are never altered. It says nothing about what was left out. Not reduced: false or absent (omitted canonically). Written as the Bundle tag SUBSETTED.
conditionsarray of ConditionEntry, or nullConditions the person reports having (background context such as PCOS or fibroids). Not recorded: [] or absent. Explicit negative: status "resolved". A condition stated more than once (even differently) is carried as stated.
bleedingarray of {date: DateTime, value: Bleeding}, or nullMenstrual bleeding entries. Omitted dates: not recorded. Explicit negative: "no-bleeding" (or "flow-none").
volumearray of {date: DateTime, value: integer 0..500}, or nullCollected menstrual fluid entries, whole mL (a smart or graduated cup). Fluid, not blood: the blood fraction varies widely between people, so a fluid volume does not establish a blood loss. Independent of bleeding: neither implies the other. Omitted dates: not recorded. Explicit negative: 0.
painarray of {date: DateTime, value: integer 0..10}, or nullPain entries on a 0-10 numeric rating scale (LOINC 72514-3). Omitted dates: not recorded. Explicit negative: 0 ("no pain"). Another scale goes in a custom series.
symptomsarray of ({date: DateTime, value: SymptomKind | CodeableConcept}), or nullSymptoms present on each date: a built-in keyword (SymptomKind) or any FHIR CodeableConcept as an escape (presence only; for severity use a custom coded series). Omitted dates: not recorded. There is no explicit "symptom absent".
bbtBbt, or nullBasal body temperature (waking readings). Not recorded: absent.
skinTempSkinTemp, or nullNightly skin or wrist temperature from a wearable (one device per card). Never pooled with BBT. Not recorded: absent.
mucusarray of ({date: DateTime, value: Mucus | CodeableConcept}), or nullCervical mucus entries. Omitted dates: not recorded. "dry" is a value.
ovulationTestarray of ({date: DateTime, value: OvulationTest | CodeableConcept}), or nullLH (ovulation) test result entries. Omitted dates: not recorded. Explicit negative: "negative".
progesteroneTestarray of ({date: DateTime, value: TestResult | CodeableConcept}), or nullProgesterone (PdG) urine test result entries. Omitted dates: not recorded. Explicit negative: "negative".
pregnancyTestarray of ({date: DateTime, value: TestResult | CodeableConcept}), or nullPregnancy test result entries. Omitted dates: not recorded. Explicit negative: "negative".
sexarray of ({date: DateTime, value: Sex | CodeableConcept}), or nullSexual intercourse entries. Omitted dates: not recorded. Explicit negative: "none".
moodarray of ({date: DateTime, value: Mood | CodeableConcept}), or nullMood entries on a 7-point valence scale. Omitted dates: not recorded. Other mood scales or multi-select moods go in a custom series.
energyarray of ({date: DateTime, value: Energy | CodeableConcept}), or nullEnergy entries on a 4-point scale. Omitted dates: not recorded.
sleeparray of {date: DateTime, value: integer 0..1440}, or nullMinutes of sleep ending on each date (attributed to the wake day). Omitted dates: not recorded. 0 is a value (no sleep).
pillarray of {date: DateTime, value: PillLog}, or nullContraceptive pill log entries. Which pill is named by the contraception interval covering the date. Omitted dates: not recorded. Explicit negative: "missed".
medicationsarray of MedEntry, or nullMedication entries (a dose taken twice is two entries with their timestamps). Built-in keywords: MedicationKind; any other product (RxNorm, SNOMED CT, text-only, ...) is an escape CodeableConcept. Omitted dates: not recorded. Explicit negative: status "not-taken" (a missed dose).
intervalsarray (≤ 256) of (BuiltinInterval | CodedInterval), or nullStates that last over a range of calendar dates: contraception, pregnancy, breastfeeding, or any other coded or text-only state. Not recorded: [] or absent. Explicit negative for contraception: kind "none". Intervals of one state that overlap or touch are one interval: normalize merges them.
proceduresarray (≤ 512) of Procedure, or nullProcedures: partial date (YYYY, YYYY-MM), full date (YYYY-MM-DD), or full date with time (YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM)), year 1900-2150. Not recorded: [] or absent. A procedure listed twice is two procedures.
answersarray of Answer, or nullScreening questions the person answered, each with the date (and optional time) they answered it. What they said, never a value computed from the log. Not recorded: [] or absent. A question answered more than once (even differently, at one time) is carried as answered.
customarray (≤ 32) of (CustomBooleanSeries | CustomCodedSeries | CustomQuantitySeries | CustomComponentsSeries), or nullSeries without a built-in slot, each with its own Observation CodeableConcept and one of four valueType kinds ("boolean", "coded", "quantity", or "components" for multi-component readings like blood pressure). Not recorded: [] or absent. One series per distinct code.

Answer

A screening question answered on a date or timestamp.

fieldrequiredtypemeaning
dateyesDateTimeWhen the person answered: calendar date or date with time and UTC offset.
questionyesQuestionWhich question.
valueyesstring | integer | CodeableConceptThe answer: for a coded question its built-in answer name or any FHIR CodeableConcept as an escape; for a numeric question an integer in the question's range. See Question.

Exactly one of: usual-cycle-length → UsualCycleLength | CodeableConcept; periods-per-year → integer 0..100; missed-periods-3-months → integer 0..3; period-in-last-year → YesNo | CodeableConcept; periods-stopped → PeriodsStopped | CodeableConcept; age-periods-stopped → integer 0..100; age-at-menarche → integer 0..100.

Bbt

Basal body temperature readings (0.01 °C / 0.01 °F precision, distinct from LOINC 8310-5 general body temperature).

fieldrequiredtypemeaning
unityesTemperatureUnitUnit of every reading.
entriesyesarray of TempEntryReadings in natural degrees of unit (at most 2 decimal places, e.g. 36.52). Cel 34-42, [degF] 93-107.6.

Exactly one of: readings in Cel (34..42); readings in [degF] (93..107.6).

BuiltinInterval

A built-in state over a range of calendar dates.

fieldrequiredtypemeaning
kindyesIntervalKindWhich state.
startyesCalendarDateFirst calendar date.
endyesCalendarDateLast calendar date (inclusive), not before start.

CodeableConcept

A FHIR R4 CodeableConcept: either a single Coding with optional plain-text text, or a text-only concept { text } with no coding (no synthetic URI required). For built-in concepts, coding[0].display is optional on input and stripped in canonical form, and text is not allowed. For any non-built-in escape coding, both coding[0].display and text are preserved and must agree across all occurrences of the same (system, code).

fieldrequiredtypemeaning
codingarray (≤ 1) of Coding, or nullAt most one standard FHIR Coding { system, code, display? }. Required unless text is given.
textstring (1–128 chars), or nullPlain-text label (1-128 characters, no control characters or leading/trailing whitespace). Required when coding is absent; optional on non-built-in escape codings; not allowed on built-in concepts.

CodedInterval

Any other state: an observation code and a coded or text-only value, over a range of calendar dates.

fieldrequiredtypemeaning
codeyesCodeableConcept (restricted)What is observed (an Observation CodeableConcept), e.g. LOINC 8659-5 "Birth control method". Not a built-in per-day series code and not an R4 vital-sign code.
valueyesCodeableConceptThe state, e.g. LOINC LA27913-5 (diaphragm or cervical cap) or a text-only concept.
startyesCalendarDateFirst calendar date.
endyesCalendarDateLast calendar date (inclusive), not before start.

Coding

A standard FHIR Coding from any code system. For built-in concepts, display is optional on input and stripped in canonical form. For any non-built-in escape concept (including SNOMED CT, LOINC, RxNorm, ICD-10-CM, ATC, NDC, or app URIs), display is carried and all occurrences of the same (system, code) must agree on the same display text.

fieldrequiredtypemeaning
systemyesstring (1–255 chars)Code system URI: absolute URI of printable ASCII without spaces or "|", 1-255 characters.
codeyesstring (1–128 chars)Concept code within system: 1-128 characters, no control characters, no leading/trailing/repeated spaces. SNOMED CT codes must be valid 6-18 digit concept ids (Verhoeff check digit, partition 00 or 10).
displaystring (1–128 chars), or nullOptional human-readable display text (1-128 characters, no control characters or leading/trailing whitespace). Carried for any non-built-in escape concept; optional on input and stripped in canonical form for built-in concepts.

ConditionEntry

A condition the person reports.

fieldrequiredtypemeaning
codeyesConditionKind | CodeableConceptThe condition: a built-in keyword (ConditionKind) or any FHIR CodeableConcept as an escape.
statusConditionStatus, or nullWhat the person says about it now. Not stated: absent.
onsetFhirDate, or nullWhen it started, as precisely as the person says (1900-2150). Not stated: absent.

CustomBooleanComponent

A yes / no component (component.valueBoolean).

fieldrequiredtypemeaning
codeyesCodeableConceptThe component CodeableConcept.
valueTypeyes"boolean"FHIR Observation component value type: boolean (component.valueBoolean).

CustomBooleanSeries

Yes / no entries (also events: only true).

fieldrequiredtypemeaning
codeyesCodeableConcept (restricted)The Observation CodeableConcept. Not a built-in series code. An R4 vital-sign code makes the series a vital sign (category vital-signs); a code with its own R4 profile needs that profile's valueType and unit (VITAL_SIGN_PROFILES).
valueTypeyes"boolean"FHIR Observation value type: boolean (Observation.valueBoolean).
entriesyesarray of {date: DateTime, value: boolean}Entries with boolean values (false is an explicit negative).

CustomCodedComponent

A coded or text-only component: one CodeableConcept per reading (component.valueCodeableConcept).

fieldrequiredtypemeaning
codeyesCodeableConceptThe component CodeableConcept.
valueTypeyes"coded"FHIR Observation component value type: coded or text-only (component.valueCodeableConcept).

CustomCodedSeries

Coded or text-only entries: categorical, ordinal or multi-select alike (each entry is one fact).

fieldrequiredtypemeaning
codeyesCodeableConcept (restricted)The Observation CodeableConcept. Not a built-in series code. An R4 vital-sign code makes the series a vital sign (category vital-signs); a code with its own R4 profile needs that profile's valueType and unit (VITAL_SIGN_PROFILES).
valueTypeyes"coded"FHIR Observation value type: coded or text-only (Observation.valueCodeableConcept).
entriesyesarray of {date: DateTime, value: CodeableConcept}Entries with FHIR CodeableConcept values (each one fact). Level order is not carried, so displays or text should state the rank ("3 of 5").

CustomComponentValue

One recorded component value inside a CustomComponentsEntry.

fieldrequiredtypemeaning
codeyesCodeableConceptThe component CodeableConcept (must match one of series.components).
valueyesboolean | CodeableConcept | number -999999999.999999..999999999.999999The component's value: boolean, CodeableConcept, or decimal number matching the component's valueType.

CustomComponentsEntry

One multi-component reading entry on a date or timestamp.

fieldrequiredtypemeaning
dateyesDateTimeWhen the reading was taken: calendar date or date with time and UTC offset.
componentsyesarray (≤ 16) of CustomComponentValueRecorded component values (1..16). Each code must match a declared component of the series, with no duplicate component code in one entry.

CustomComponentsSeries

A reading of several components, written as one Observation with a component per recorded value and no top-level value (blood pressure: LOINC 85354-9 with 8480-6 and 8462-4 in mm[Hg]). Nothing here is specific to blood pressure: any code may have components.

fieldrequiredtypemeaning
codeyesCodeableConcept (restricted)The Observation CodeableConcept. Not a built-in series code. An R4 vital-sign code makes the series a vital sign (category vital-signs); 85354-9 must be a components series whose 8480-6 and 8462-4 components are quantities in mm[Hg].
valueTypeyes"components"FHIR Observation value type: multi-component reading with no top-level value (Observation.component[]).
componentsyesarray (≤ 16) of (CustomBooleanComponent | CustomCodedComponent | CustomQuantityComponent)The declared components, each with its own code and valueType. Codes differ. Canonical order is the concepts' canonical order; a component never recorded in any entry is dropped.
entriesyesarray of CustomComponentsEntryThe readings, each carrying its date/time and at least one recorded component value.

CustomQuantityComponent

A decimal quantity component in a UCUM unit (component.valueQuantity, at most 6 decimal places).

fieldrequiredtypemeaning
codeyesCodeableConceptThe component CodeableConcept.
valueTypeyes"quantity"FHIR Observation component value type: decimal quantity in UCUM unit (component.valueQuantity).
unityesstring (1–64 chars)UCUM unit code (printable ASCII, no spaces). In a vital-sign series, one of the units the R4 vital-signs profile allows for components (UCUM_VITALS_COMMON).

CustomQuantitySeries

Natural decimal quantity entries in a UCUM unit (at most 6 decimal places).

fieldrequiredtypemeaning
codeyesCodeableConcept (restricted)The Observation CodeableConcept. Not a built-in series code. An R4 vital-sign code makes the series a vital sign (category vital-signs); a code with its own R4 profile needs that profile's valueType and unit (VITAL_SIGN_PROFILES).
valueTypeyes"quantity"FHIR Observation value type: decimal quantity in UCUM unit (Observation.valueQuantity).
unityesstring (1–64 chars)UCUM unit code (printable ASCII, no spaces).
entriesyesarray of {date: DateTime, value: number -999999999.999999..999999999.999999}Entries with natural decimal numbers below 1,000,000,000 in magnitude and at most 6 decimal places. 0 is a value.

MedDose

Exact positive decimal medication dose in a UCUM unit.

fieldrequiredtypemeaning
valueyesnumber 0.000001..999999999.999999Strictly positive decimal dose below 1,000,000,000, with at most 6 decimal places (e.g. 400, 12.5).
unityesstring (1–64 chars)UCUM unit code (printable ASCII, no spaces, e.g. "mg", "ug", "mL", "[iU]").

MedEntry

One medication entry on a date or timestamp.

fieldrequiredtypemeaning
dateyesDateTimeWhen the medication was taken (or missed): calendar date or date with time and UTC offset.
codeyesMedicationKind | CodeableConceptThe product: a built-in keyword (MedicationKind) or any FHIR CodeableConcept as an escape.
statusyesMedStatusWhether it was taken.
doseMedDose, or nullOptional exact dose taken (maps to MedicationStatement.dosage[0].doseAndRate[0].doseQuantity).

PatientInfo

Optional identity: deliberately small. An empty object means no identity.

fieldrequiredtypemeaning
familystring (1–64 chars), or nullFamily name. Not recorded: absent.
givenarray (≤ 3) of string (1–64 chars), or nullGiven names, in order. Not recorded: absent or []. Each 1-64 characters.
birthDateFhirDate, or nullBirth date, from 1900 to 2150. A year alone is enough to give age without identity. Not recorded: absent.

Procedure

A completed procedure on a date or dateTime.

fieldrequiredtypemeaning
dateyesFhirDateTimeWhen: YYYY, YYYY-MM, YYYY-MM-DD, or YYYY-MM-DDTHH:MM(:SS)?(Z|±HH:MM) (year 1900-2150).
codeyesProcedureKind | CodeableConceptWhich procedure: a built-in keyword (ProcedureKind) or any FHIR CodeableConcept.

SkinTemp

Wearable nightly temperature from one device.

fieldrequiredtypemeaning
kindyesSkinTempKindWhether values are deviations from the device's baseline or absolute temperatures.
unityesTemperatureUnitUnit of every value. For a deviation, a temperature difference in this unit.
entriesyesarray of TempEntryReadings by wake date, in natural degrees of unit (at most 2 decimal places, e.g. -0.31). Deviation: Cel -5..5, [degF] -9..9. Absolute: Cel 25..40, [degF] 77..104.

Exactly one of: deviation in Cel (-5..5); deviation in [degF] (-9..9); absolute in Cel (25..40); absolute in [degF] (77..104).

Source

The exporting app, shown as the source device of every observation.

fieldrequiredtypemeaning
nameyesstring (1–64 chars)The app's name as users know it, 1-64 characters.
versionstring (1–32 chars), or nullThe app's version, 1-32 characters. Not recorded: absent.

TempEntry

One temperature reading with date/time and optional disturbance/exclusion flag.

fieldrequiredtypemeaning
dateyesDateTimeWhen the reading was taken: calendar date or date with time and UTC offset.
valueyesnumberTemperature in natural degrees of the series unit, at most 2 decimal places (e.g. 36.52).
excludedboolean, or nullTrue when the user or app marked this reading disturbed/excluded from thermal-shift interpretation.
excludeReasonExcludeReason | CodeableConcept, or nullOptional coded or text-only reason for exclusion (only allowed when excluded is true).

Enumerations and built-in tables

Each built-in value is a short name for a concept. A coded field accepts the names below or, as an escape, any concept. The built-in tables of symptoms, medications and conditions are the concepts that are cheap to encode; any other concept is allowed in the same field.

Bleeding

Menstrual bleeding on one day: the legal combinations of bleeding and flow.

valuemeaning
no-bleedingExplicitly no bleeding.
flow-noneExplicitly no bleeding, logged on a flow scale's "none" option.
bleedingBleeding, amount not recorded.
spottingBleeding, flow category spotting (also bleeding between periods with no amount).
lightBleeding, flow category light.
moderateBleeding, flow category moderate (medium).
heavyBleeding, flow category heavy.

ConditionKind

Built-in condition keywords (SNOMED CT), pending clinical review: the main explanations of a bleeding pattern. Any other condition is passed as a FHIR CodeableConcept.

valuemeaning
pcosPolycystic ovary syndrome. (237055002)
uterine-fibroidsUterine leiomyoma (fibroids). (95315005)
adenomyosisUterine adenomyosis. (784314006)
endometrial-polypEndometrial polyp. (1237359009)
endometriosisEndometriosis. (129103003)
von-willebrand-disordervon Willebrand disorder. (128105004)
coagulation-disorderBlood coagulation disorder. (64779008)
iron-deficiency-anemiaIron deficiency anemia. (87522002)
hypothyroidismHypothyroidism. (40930008)
hyperthyroidismHyperthyroidism. (34486009)
hyperprolactinemiaHyperprolactinemia. (237662005)
premature-ovarian-insufficiencyPremature ovarian insufficiency. (237788002)
hypothalamic-amenorrheaHypothalamic amenorrhea. (237120002)
perimenopausePerimenopausal state. (161541000119104)
postmenopausePostmenopausal state. (76498008)

ConditionStatus

A reported condition's status, as the person states it.

valuemeaning
activeThe person has it now.
resolvedThe person had it and it is over (explicit negative for now).

Energy

Energy, 4 points (Clue).

valuemeaning
exhausted1 of 4.
low2 of 4.
high3 of 4.
energized4 of 4.

ExcludeReason

Built-in disturbance/exclusion reason on a BBT or skinTemp reading.

valuemeaning
feverFever or acute febrile illness.
alcoholAlcohol consumption the previous evening.
poor-sleepPoor, broken, or unusually short sleep.
late-wakeWoke significantly later (or earlier) than usual.
travelTravel or time-zone shift.
stressAcute stress.
medicationMedication affecting basal temperature.
otherOther unspecified disturbance.

IntervalKind

Built-in states over a range of days. Contraception values are LOINC answers to 8659-5.

valuemeaning
noneNot using contraception (explicit negative). (http://loinc.org
combined-pillCombined oral contraceptive pill. (http://loinc.org
progestin-pillProgestin-only pill. (http://loinc.org
patchContraceptive patch. (http://loinc.org
ringVaginal ring. (http://loinc.org
injectionInjectable contraceptive. (http://loinc.org
implantContraceptive implant. (http://loinc.org
hormonal-iudHormonal (progestin) IUD. (http://loinc.org
copper-iudCopper IUD. (http://loinc.org
iud-unspecifiedIUD, type not recorded. (http://loinc.org
condomMale condom. (http://loinc.org
fertility-awarenessFertility awareness-based method. (http://loinc.org
lactational-amenorrheaLactational amenorrhea method. (http://loinc.org
pregnantPregnant (LOINC 82810-3). (http://loinc.org
breastfeedingBreastfeeding (LOINC 63895-7). (http://loinc.org

MedStatus

Whether a medication was taken on a day.

valuemeaning
takenTaken.
not-takenExplicitly not taken (a missed dose).

MedicationKind

Built-in medication keywords (SNOMED CT medicinal products). Any other product (RxNorm, SNOMED CT, text-only, ...) is passed as a FHIR CodeableConcept.

valuemeaning
ibuprofenIbuprofen-containing product. (38268001)
naproxenNaproxen-containing product. (11847009)
acetaminophenAcetaminophen-containing product. (90332006)
mefenamic-acidMefenamic acid-containing product. (34364009)
tranexamic-acidTranexamic acid-containing product. (109006003)
ironIron-containing product. (30729008)
folic-acidFolic acid-containing product. (6247001)

Mood

Mood valence, 7 points (Apple HealthKit State of Mind).

valuemeaning
very-unpleasant1 of 7.
unpleasant2 of 7.
slightly-unpleasant3 of 7.
neutral4 of 7, neither pleasant nor unpleasant.
slightly-pleasant5 of 7.
pleasant6 of 7.
very-pleasant7 of 7.

Mucus

Cervical mucus, as self-observed.

valuemeaning
dryNo mucus; feels dry.
stickySticky, tacky or crumbly.
creamyCreamy, lotion-like.
wateryWatery, wet.
egg-whiteClear and stretchy, like raw egg white.

OvulationTest

LH (ovulation) urine test result.

valuemeaning
negativeNo surge detected.
lh-surgeLH surge detected (a positive test).
estrogen-surgeEstrogen rise detected (high fertility on two-hormone tests).
indeterminateThe result could not be read.

PeriodsStopped

Answers to "periods-stopped".

valuemeaning
yes-no-periodsYes, no menstrual periods. (http://loinc.org
yes-hormonesYes, but has periods now due to female hormones. (http://loinc.org
noNo. (http://loinc.org
not-sureNot sure. (http://loinc.org

PillLog

Contraceptive pill log for one day.

valuemeaning
takenThe pill was taken.
missedThe pill was missed (explicit negative).

ProcedureKind

Built-in procedures (SNOMED CT).

valuemeaning
iud-insertionInsertion of an intrauterine device. (65200003)
iud-removalRemoval of an intrauterine device. (1263416007)
implant-insertionInsertion of a contraceptive implant. (169553002)
implant-removalRemoval of a contraceptive implant. (301807007)
emergency-contraceptionEmergency contraception taken. (1372819003)
hysterectomyHysterectomy: afterwards absent bleeding is not amenorrhea or menopause. (236886002)
endometrial-ablationEndometrial ablation: afterwards little or no bleeding is expected. (265060005)
oophorectomyOophorectomy (one ovary or unspecified). (83152002)
bilateral-oophorectomyBilateral oophorectomy: surgical menopause. (76876009)
myomectomyMyomectomy (fibroid removal). (42010004)
d-and-cDilation and curettage. (11401008)
polypectomyEndometrial polypectomy. (236884004)
uterine-artery-embolizationUterine artery embolization. (312138002)

Question

Screening questions (LOINC). A coded question's value is one of its answer names (or any CodeableConcept as an escape); a numeric question's value is an integer.

valuemeaning
usual-cycle-lengthUsual cycle length over the last year. Answer: UsualCycleLength. (http://loinc.org
periods-per-yearNumber of periods per year. Answer: integer 0-100 (unit /a). (http://loinc.org
missed-periods-3-monthsPeriods missed over the past 3 months. Answer: integer 0-3. (http://loinc.org
period-in-last-yearHad a period within the last year. Answer: YesNo. (http://loinc.org
periods-stoppedPeriods stopped permanently. Answer: PeriodsStopped. (http://loinc.org
age-periods-stoppedAge in years when periods stopped. Answer: integer 0-100. (http://loinc.org
age-at-menarcheAge in years at the first period. Answer: integer 0-100. (http://loinc.org

Sex

Sexual intercourse on one day.

valuemeaning
noneExplicitly no intercourse.
protectedIntercourse with protection (e.g. a condom).
unprotectedIntercourse without protection.
unspecifiedIntercourse, protection not recorded.

SkinTempKind

What a wearable temperature value means.

valuemeaning
deviationDifference from the device's own baseline (Oura, Fitbit, Garmin); signed.
absoluteAbsolute nightly skin or wrist temperature (Apple Watch, Google, Whoop).

SymptomKind

Built-in symptom keywords (SNOMED CT, plus hot-flash in cycle-log). The first 14 are the starter set of the Period Tracking guide the design started from. Any other symptom is passed as a FHIR CodeableConcept.

valuemeaning
menstrual-crampMenstrual cramp. (431416001)
backacheBackache. (161891005)
headacheHeadache. (25064002)
migraineMigraine. (37796009)
stomach-acheStomach ache. (271681002)
nauseaNausea. (422587007)
breast-tendernessBreast tenderness. (55222007)
ovulation-painOvulation pain. (43548008)
fatigueFatigue. (84229001)
bloatingAbdominal bloating. (116289008)
depressed-moodDepressed mood. (366979004)
irritableFeeling irritable. (55929007)
stressStress. (73595000)
dyspareuniaDyspareunia. (71315007)
acneAcne. (11381005)
pelvic-painPain in pelvis. (30473006)
low-back-painLow back pain. (279039007)
breast-painPain of breast. (53430007)
mood-swingsMood swings. (18963009)
anxietyAnxiety. (48694002)
diarrheaDiarrhea. (62315008)
constipationConstipation. (14760008)
dizzinessDizziness. (404640003)
food-cravingCraving for food or drink. (248132003)
vaginal-clotsPassing clots vaginally. (289532003)
hot-flashHot flash (cause not stated); a proposed code. (https://joshuamandel.com/shc2-poc/CodeSystem/cycle-log
night-sweatsNight sweats. (42984000)
insomniaInsomnia. (193462001)
vaginal-drynessVaginal dryness. (31908003)
palpitationsPalpitations. (80313002)
urinary-incontinenceUrinary incontinence. (165232002)
memory-lapsesMemory lapses. (225038006)
hair-lossAlopecia (hair loss). (56317004)
increased-libidoIncreased libido. (58436003)
reduced-libidoReduced libido. (8357008)

TemperatureUnit

Temperature unit (UCUM).

valuemeaning
CelDegrees Celsius.
[degF]Degrees Fahrenheit.

TestResult

A urine test result (progesterone or pregnancy).

valuemeaning
negativeNegative.
positivePositive.
indeterminateThe result could not be read.

UsualCycleLength

Answers to "usual-cycle-length".

valuemeaning
<21Less than 21 days. (http://loinc.org
21-2521-25 days. (http://loinc.org
26-3226-32 days. (http://loinc.org
33-3533-35 days. (http://loinc.org
36-9036-90 days. (http://loinc.org
>90More than 90 days. (http://loinc.org
too-variableToo variable to say. (http://loinc.org
dont-knowDon't know. (http://loinc.org

YesNo

Answers to "period-in-last-year".

valuemeaning
yesYes. (http://loinc.org
noNo (explicit negative). (http://loinc.org

3. Not recorded and explicit negatives

The card distinguishes three things for every day and every field:

the person loggedwriteexample
nothingnull, [], or leave the field (or the end of the array) out"pain": [null, 4]: no pain score on day 0
a positive valuethe value"bleeding": ["heavy"]
an explicit "no"the field's negative value"bleeding": ["no-bleeding"], "pain": [0], "sex": ["none"], {"code": "38268001", "status": "not-taken"}, a custom boolean false, contraception interval kind "none", condition status "resolved", answer "no"
  • Absence is never a negative. A day with no bleeding entry is "not recorded", not "not bleeding". A viewer must not compute cycle lengths as if unlogged days were negatives.
  • Symptoms have no negative. A symptom set lists what was present. "No symptoms today" has no representation; if an app records it explicitly, use a custom boolean series.
  • Fields without a negative. bbt, skinTemp, mood and energy are measurements or ratings: there is nothing to negate.

4. Concepts and escapes

  • Key.
    • SNOMED CT is a bare id: 6–18 digits, Verhoeff check digit, concept partition. "http://snomed.info/sct|…" is normalized to the bare id.
    • Every other system is "<system>|<code>":
      • the system is an absolute URI of printable ASCII without spaces or |, at most 255 characters;
      • the code follows FHIR code syntax, 1–128 characters, any Unicode except control characters and unpaired surrogates.
  • Well-known systems. These get small indices in a codec: SNOMED CT, LOINC, RxNorm, UCUM, cycle, cycle-log (the proposed concepts), ATC, ICD-10-CM, NDC. Any other system is spelled out once per card.
  • Canonical spelling. A concept equal to a built-in level, interval pair or procedure is written as that built-in. For example, https://joshuamandel.com/shc2-poc/CodeSystem/cycle-log|valence-neutral becomes "neutral".
  • Order. Built-in table index first, then SNOMED CT numerically, then code-point order.
  • Labels. At most 200 characters, at most 512 per card. Labels are allowed only on concepts in code systems outside the well-known terminologies, so never on built-ins, SNOMED CT, LOINC or RxNorm. Receivers look those displays up, and a label that differs from the official display fails validation. Unused labels are dropped by normalize, with a warning. App code systems should not be under example.org: the HL7 validator rejects "example URLs" (MAPPING.md §6).

5. Custom series

shapemodel valuesFHIR value[x]limits
booleantrue / false / null per dayvalueBoolean–
codeda set of concepts per dayvalueCodeableConcept, one fact per conceptany number per day
quantityinteger per day; unit (UCUM), scalevalueQuantity {value = v × 10^−scale, unit = code = unit}|v / 10^scale| < 10^9; scale 0–6 (canonical: smallest exact); unit ≤ 64 chars
componentsper day a reading: one entry per declared component (boolean, concept or integer by the component's shape, null = that component not recorded), or nullno value; one component per recorded value1–16 components with different codes
  • A custom series' code is any concept except a built-in series code.
  • Readings with components. Blood pressure is the motivating case (85354-9 with systolic 8480-6 and diastolic 8462-4 in mm[Hg]), but any code may have components, each with the value shapes above (one value per reading, a coded component one concept).
    • A day's reading is null (nothing measured) or an array with one entry per component; an entry is null when that component was not recorded. A reading whose entries are all null is the same as null and is not written.
    • Components are kept in the canonical concept order (the Bundle carries no order), and a component recorded on no day is dropped.
    • Each reading counts one fact per recorded component toward the 20,000-fact limit.
  • Vital signs. A series whose code is an R4 vital-sign LOINC code (R4_VITAL_SIGN_CODES, about 90) is written with the vital-signs category. A code with its own R4 profile must have that profile's shape (rule vital-sign-profile): heart rate 8867-4 and respiratory rate 9279-1 in /min, oxygen saturation 2708-6 in %, body height 8302-2 and head circumference 9843-4 in cm or [in_i], body weight 29463-7 in kg, g or [lb_av], BMI 39156-5 in kg/m2, and blood pressure 85354-9 as a components series. MAPPING.md §1 says exactly which Bundles then conform to the R4 vital-signs profiles; in short, use each measurement's own profile code, and record both blood-pressure values.
  • Body temperature is BBT. LOINC 8310-5 "Body temperature" is the built-in bbt series: waking basal readings, written with the vital-signs category and conforming to R4 bodytemp. A custom series may not use 8310-5. Temperatures that are not basal readings (a fever log) go in a custom quantity series under a site-specific LOINC code such as 8331-1 "Oral temperature"; it is written as a vital sign, but the validator applies bodytemp, which expects the 8310-5 coding, so it does not conform to that profile.
  • At most 32 series, one per code. Each fact has the shape of every built-in fact (MAPPING.md §1).
  • An event is a boolean series with only true, or a coded series, or a custom procedure.
  • Ordinal scales. Levels are coded concepts. Their order is not carried, because FHIR has no element for it without a CodeSystem or an extension, so labels should state the rank ("3 of 5").
  • Built-ins are cheaper spellings of the same thing. Pain and sleep are quantity series. Symptoms, mucus, the tests, sex, mood and energy are coded series. The pill log is a boolean series. Their facts are identical to the equivalent custom series apart from Observation.code (tested).
  • Special built-ins. Bleeding/flow (two paired facts), BBT (category), the window, built-in intervals, and medications and procedures (MedicationStatement and Procedure resources, open to any concept).

6. Cross-field rules and what validate accepts

The JSON Schema is necessary, not sufficient. Any model validate accepts satisfies the schema, and the schema rejects most mistakes: wrong types, unknown fields, values outside an enumeration, integers out of range, strings too long, malformed concepts and dates, reserved codes in custom series, labels on built-in or well-known concepts. These rules involve more than one field, or a computation, and are checked only by validate / validateJson and the codec's encoder:

rulewhat to do
date-spanAcross all daily series, intervals and answers, recorded dates span at most 10,000 days from earliest to latest, and every interval has start ≤ end.
calendar-dateEvery full calendar date (DateTime, CalendarDate, FhirInstant, and full dates in FhirDate / FhirDateTime) is a real Gregorian date (no 2026-02-30; 29 February only in leap years).
decimal-precisionTemperature readings (bbt, skinTemp) have at most 2 decimal places; medication doses and custom quantities have at most 6 decimal places.
snomed-check-digitA SNOMED CT Coding (system: "http://snomed.info/sct") has a 6-18 digit concept id passing the Verhoeff check digit with partition 00 or 10 (not a description or relationship id).
no-unpaired-surrogatesCodes, displays, texts and names contain no unpaired UTF-16 surrogate (possible only through a \ud800-style escape in JSON text).
display-consistencyFor non-built-in coded concepts, every occurrence of the same (system, code) with a display must agree on the same display, and every occurrence with text must agree on the same text; text is not allowed on built-in concepts; at most 512 distinct escape labels (displays, coded texts, and text-only concepts) may appear on a card.
unique-custom-codeEach custom series has a different code (distinct (system, code) or distinct text-only text).
entriesA temperature entry's excludeReason is allowed only when excluded is true (identical entries, and entries that disagree, are all valid: each is its own fact).
component-readingA components series declares 1-16 components with distinct codes; each entry records at least one component with no duplicate code, matching a declared component and carrying a value of that component's valueType. A component code has one valueType, and as a quantity one unit, on the whole card.
vital-sign-profileA custom series whose code has its own R4 vital-signs profile has that profile's valueType and unit: 8310-5 in Cel or [degF], 8867-4 and 9279-1 in /min, 2708-6 in %, 8302-2 and 9843-4 in cm or [in_i], 29463-7 in kg, g or [lb_av], 39156-5 in kg/m2 (quantity series), and 85354-9 a components series whose 8480-6 and 8462-4 components are quantities in mm[Hg]; in any R4 vital-sign series a quantity component's unit is one of %, cm, [in_i], kg, g, [lb_av], Cel, [degF], mm[Hg], /min, kg/m2, m2.
fact-limitThe model has at most 20,000 facts in all (a bound on encoder and decoder work, far above real use).
number-spellingIn JSON text, integer fields (pain, volume, sleep, numeric answers) are spelled -?(0|[1-9][0-9]*); decimal fields are spelled -?(0|[1-9][0-9]*)(\.[0-9]{1,N})? (N = 2 for temperatures, N = 6 for doses and custom quantities); never -0, -0.0 or scientific notation.

The tests check that every invalid case in the rejection table is either rejected by the schema or named here.

What validate accepts

validate(model) returns a list of problems for any input whatsoever. It never throws, and a fuzz test (3,000 random and mutated models) checks this. validateJson(text) additionally checks how numbers are spelled.

  • Fields. Every object carries only the fields in the reference (§2); any other field is an error, so nothing is dropped silently. Every field except start and days may be absent or null; an absent series means nothing recorded.
  • Numbers.
    • Every number in the model is an integer within its field's range, and every range lies inside ±2⁵³.
    • In JSON text a number must be spelled -?(0|[1-9][0-9]*), and -0 is not allowed. 2.0, 1e3, 1e-400, 0.5 and -0 are all rejected.
    • validateJson enforces the spelling on the text.
    • validate sees only the parsed value. It rejects non-integers, unsafe integers, -0, NaN and ±Infinity, but cannot see the spelling of a value that parses to an integer (2.0 → 2, 1e-400 → 0).
    • Encoders that read JSON text should apply the spelling rule, as the Rust encoder does.
  • Non-canonical spellings are accepted and normalized, uniformly. validate accepts them and normalize canonicalizes them. An encoder must produce exactly normalize(model). The accepted non-canonical forms are:
    • http://snomed.info/sct|<id> for a valid SNOMED CT id, in every concept slot, normalized to the bare id;
    • a concept equal to a built-in level, interval pair, procedure or screening answer, normalized to its name or kind;
    • a time of day with :00 seconds, normalized to HH:MM±HH:MM; a day in the entries form that the plain form can say (one untimed entry; a set's untimed, distinct items), written plain; a plain set day with a repeated item (the same concept twice, in any spelling), written in the entries form, one entry per occurrence; entries in any order, normalized to the canonical order;
    • any order of sets, conditions, intervals, procedures, answers, custom series and label keys;
    • series shorter than days (missing days are not recorded), and null for an empty per-day set;
    • a quantity series at a larger scale than needed, normalized to the smallest exact scale;
    • an empty patient (normalized to null), unused labels (dropped, with a warning), custom series with no values and empty bbt / skinTemp (dropped).
    • Everything else must already be canonical. In particular, -0 is an error, not normalized.
  • Dates are proleptic-Gregorian YYYY-MM-DD, checked arithmetically for every year 0000–9999. For example, 0099-01-01 is a valid date and is reported as outside the window range.
  • Other limits. At most 20,000 facts (fact-limit above), and a card of at most 4,096 bytes, more than any QR code holds, which is the encoder's check. There is no limit on the size of the Bundle; tools warn when a card would be unusually costly to decode or its Bundle unusually large.

7. Published files

filewhatwhere
model.d.tsthe normative definition (TypeScript types with TSDoc)https://joshuamandel.com/shc2-poc/codecs/cycle-log/model.d.ts
model.schema.jsonJSON Schema 2020-12, derived from model.d.tsits $id, https://joshuamandel.com/shc2-poc/codecs/cycle-log/model.schema.json
examples/<persona>.model.jsonthe sixteen personas of §12 as normalized modelsexamples/ beside the schema
examples/minimal-teaching.model.json, .mdthe hand-written teaching example and its explanationexamples/

How the three stay in agreement. model.d.ts holds every description and every enumeration's members and meanings. make-schema.ts reads it (a small reader for that one file) and takes field names, optionality, nullability, descriptions, examples and enumeration members from it. It takes limits, patterns, table order and reserved codes from the constants validate uses. Wherever the two meet it checks them, and any disagreement fails the build:

  • every field in the types has a schema and the reverse;
  • union members equal the vocab.ts arrays in order;
  • @minimum, @maximum, @maxLength and @maxItems tags equal the schema's values;
  • @code tags equal the built-in codes.

The tests regenerate the schema, the examples and the generated sections of this file and fail if any committed file differs. They also check that every persona, every random model and every fuzzed model that validate accepts satisfies the schema.

8. Context and devices

A reduced card (reduced). An exporter that left out data to fit a size sets reduced: true. Then a series, time of day, or label that is absent may have been tracked; recorded values are never altered, and the flag says nothing about which items were omitted. A viewer shows that the card is reduced. In the Bundle it is the R4 tag SUBSETTED (MAPPING.md §1). Not reduced is false (canonical), null or absent; a card without the flag asserts nothing about reduction beyond that. The flag is one bit, not a list of the steps taken.

Reported conditions.

  • The 15 built-ins are the main explanations of a bleeding pattern: PALM-COEIN (Munro 2011/2018), endocrine causes, and menopausal status. Evidence for each is in vocab.ts and EXPRESSIVENESS.md.
  • The table is pending clinical review.
  • Any other condition is an escape.
  • status and onset are only what the person states.

Surgical history.

  • Procedures before the window carry a year, a month, or a full date.
  • After a hysterectomy or an endometrial ablation, absent bleeding is not amenorrhea and not menopause. A viewer suppresses amenorrhea and cycle-length inferences after the procedure's date.
  • Ovarian signals (BBT, LH, skin temperature, cyclic symptoms) continue unless both ovaries were removed. After a bilateral oophorectomy the viewer shows surgical menopause.
  • Age without identity is a patient.birthDate year alone.

Measured volume (volume).

  • What a smart or graduated cup collects per day, in whole mL.
  • It is menstrual fluid, not blood. The blood fraction varies widely: 36% on average but from 1.6% to 81.7% between people (Fraser 1985), and about half in heavy losses (Fraser 2001).
  • So a measured fluid volume does not establish whether the classic heavy-menstrual-bleeding threshold of 80 mL of blood per period was exceeded.
  • A day can have both a flow category and a volume. Neither implies the other, and a volume implies no Layer 0 fact.

Wearable skin temperature (skinTemp).

  • One series per card:
    • deviation: Oura temperature_deviation, Fitbit nightlyRelative, Garmin. The difference from the device's own baseline.
    • absolute: Apple appleSleepingWristTemperature, Google Health nightly temperature, Whoop.
  • Attributed to the wake day.
  • The unit is Cel (or [degF] for a Fahrenheit device) in both cases. For deviation the value is a temperature difference in that unit: −0.31 means 0.31 °C below baseline, and the Observation code says it is a deviation. This is the owner's choice over UCUM's K for differences.
  • It is never pooled with BBT.

Source (source). One Device per card, named by the source app (and version). Every Observation references it.

Several entries a day, and times of day. A day of a per-day series normally holds one value (a set series: a set of items), written as today: "pain": [3, null, 5]. When the source app recorded more than that, the day is written as entries instead: an array of {"value": …, "time": …} objects, one per entry (a set series: one per item occurrence), each with its own optional time of day.

  • When. A day uses the entries form exactly when the plain form cannot say it: an entry has a time, a single-valued series has more than one entry, or an item of a set repeats. Otherwise it must be plain (normalize writes it so), so a set of facts has one spelling.
  • Times. HH:MM±HH:MM, or HH:MM:SS±HH:MM when seconds were recorded (rare: a device sync). The local time the source app recorded, with its UTC offset; the day is the day the fact belongs to (sleep and skin temperature: the wake day). Optional per entry: a day may mix entries with and without a time. The offset may change from day to day (daylight saving time, travel) and within a day.
  • Order (canonical): entries without a time first, then by instant (local time minus offset), then by local time; ties by value (the series' value order: levels in table order, then concepts; numbers ascending).
  • Repeats are separate facts, never merged. Any number of entries a day (the model's 20,000-fact limit is the only bound), each its own fact: two pain scores, morning and evening blood pressure, a symptom at 09:00 and another at 21:00. Entries are what was recorded: two identical entries (the same value, and the same time or both without one) are two facts, and entries that disagree are all carried as recorded: two different untimed blood-pressure readings, a medication taken and not-taken at one time, two pain scores at one time. Nothing is deduplicated, merged or refused for disagreeing; a reader that wants one value per day chooses its own rule.
  • Bleeding is no exception: a day may hold any bleeding entries, timed or not, including states that disagree at one time ("light" and "heavy" at 09:00) or an untimed "no-bleeding" beside a timed "light". Each entry is its bleeding fact and, for a flow state, its flow fact (MAPPING.md §1); the states are recovered from those facts exactly, as a multiset per time.
  • Not recorded and negatives keep their per-day meaning: an absent day or null is not recorded; "no-bleeding", pain 0, a medication "not-taken" are entries like any other.
  • Screening answers and procedures inside the window carry their own time. The same question may be answered more than once on a day, even at one time and differently; a procedure listed twice is two procedures; a condition stated more than once (even with different statuses or onsets) is carried as stated. Intervals, conditions and the window have no time.
  • In the Bundle every entry is its own Observation (or MedicationStatement), and a timed one's effectiveDateTime is YYYY-MM-DDTHH:MM:SS±HH:MM (MAPPING.md §1).
what was loggedmodel
one pain score, no time"pain": [3] (unchanged)
two pain scores with times"pain": [[{"value": 3, "time": "08:00-05:00"}, {"value": 6, "time": "20:30-05:00"}]]
headache at 09:00, cramps at 21:00"symptoms": [[{"value": "25064002", "time": "09:00-05:00"}, {"value": "431416001", "time": "21:00-05:00"}]]
blood pressure morning and evening"values": [[{"value": [128, 84], "time": "07:10-05:00"}, {"value": [121, 79], "time": "21:40-05:00"}]] in the 85354-9 components series
BBT at 06:45"bbt": {"unit": "Cel", "values": [[{"value": 3652, "time": "06:45-05:00"}]]}
ibuprofen twice"medications": [[{"value": {"code": "38268001", "status": "taken"}, "time": "08:00-05:00"}, {"value": {"code": "38268001", "status": "taken"}, "time": "20:00-05:00"}]]
two identical untimed pain scores"pain": [[{"value": 3}, {"value": 3}]] (two facts)
blood pressure twice, no times"values": [[{"value": [79, 121]}, {"value": [84, 128]}]] (components in code order: diastolic 8462-4, systolic 8480-6)
"light" and "heavy" both logged at 09:00"bleeding": [[{"value": "light", "time": "09:00-05:00"}, {"value": "heavy", "time": "09:00-05:00"}]]

Screening answers (answers).

questionLOINCanswer
usual cycle length last year64700-8<21, 21-25, 26-32, 33-35, 36-90, >90, too-variable, dont-know
periods per year92656-80–100, /a
periods missed in the last 3 months65930-00–3
period in the last year63889-0yes, no
periods stopped permanently64701-6yes-no-periods, yes-hormones, no, not-sure
age when periods stopped64702-40–100, a
age at menarche63888-20–100, a
  • Each answer is what the person said, on the day they said it. The card carries no value computed from the log, so an answer cannot be mistaken for one.
  • "Fewer than eight periods a year" is the PCOS guideline threshold (Teede 2023) applied to the periods-per-year answer. A viewer derives it; it is not a question.

9. Design decisions

decisionwhy
days 1..10,000Up to ~27 years; QR byte capacity is the natural bound rather than an arbitrary 1-year cap.
bleeding: 7 values + nullExactly the legal one-day combinations of the bleeding and flow facts (MAPPING.md §1). HealthKit unspecified → bleeding; intermenstrualBleeding → spotting.
symptoms and medications are sets of concepts from any system; the built-in tables only fix short codes and orderOne representation for every source: tables are shortcuts, not limits.
BBT in integer hundredths of Cel or [degF]; the grid is implied by the valuesReal thermometers read to 0.01 in both units (§10). A resolution field would not survive the Bundle round trip (JSON loses trailing zeros); a codec detects the grid.
any number of entries a day, each with an optional time of day with UTC offset; the plain per-day value stays the spelling of the common caseApps log several pain scores, morning and evening readings, symptoms when they happen. One mechanism for times and repeats; a card with one untimed entry per series per day pays about half a bit for it (FORMAT.md §4.11, 4.12). The plain form keeps simple exporters simple; normalize allows exactly one spelling.
mood: 7-point valence; energy: 4-point; sleep in any whole minuteHealthKit and Clue scales. A coarser grid is the exporting app's choice and simply compresses better (coarsen, §13).
fertility signs: mucus, LH (4 values), PdG and pregnancy testsHealthKit's value sets exactly. Other values (Flo "ClumpyWhite", Clue "atypical") are escapes.
a per-day pill log (taken / missed) and an emergency-contraception procedureThe pill's identity is carried by the contraception interval covering the day: a viewer reads a pill fact together with the 8659-5 interval that contains its day. A pill log with no covering interval is allowed and means "a contraceptive pill, kind not recorded".
an optional, deliberately small patient (name, birth date); a Patient is always resource:0 and every fact references itFacts are linked to a patient. R4 bodytemp, MedicationStatement and Procedure need a subject. Without identity the Patient is {"resourceType":"Patient","id":"0"}, the least assertive valid Patient (MAPPING.md §1).
medications are MedicationStatements, procedures are ProceduresThe FHIR resources made for them.
custom series, custom intervals and procedures, labels, escapes in every coded slotNothing short of a new kind of structure is unrepresentable (§5, EXPRESSIVENESS.md).
tracking window carried explicitlyTrailing unrecorded days would otherwise be lost, and the window tells a viewer where "not recorded" applies.
reported conditions with a 15-entry tableThe main explanations of a bleeding pattern travel with it (§8).
procedures carry a date, with partial precision before the windowOne list holds in-window events and prior surgical history (§8).
measured fluid volume as its own seriesThe only calibrated amount; flow categories are uncalibrated (§8).
wearable skin temperature as its own series, deviation or absoluteWhat Oura, Fitbit, Apple Watch and others actually provide; not BBT (§8).
one Device for the source appNames where the data came from (§8).
seven screening answers with their LOINC questionsWhat a person says about their cycles, kept apart from anything computed (§8).

10. Evidence for the built-ins

  • Apple HealthKit (developer.apple.com/documentation/healthkit, fetched 2026-12-03):
    • menstrualFlow: unspecified / none / light / medium / heavy;
    • intermenstrualBleeding;
    • cervicalMucusQuality: dry / sticky / creamy / watery / eggWhite;
    • ovulationTestResult: negative / LH surge / estrogen surge / indeterminate;
    • pregnancyTestResult, progesteroneTestResult;
    • sexualActivity with ProtectionUsed;
    • contraceptive, pregnancy, lactation, basalBodyTemperature;
    • 40 symptom types;
    • HKStateOfMind, 7-value valence.
  • Clue. Li et al. 2020 (npj Digit Med, Table 3); the measurements.json export format comes from open-source converters (EXPRESSIVENESS.md §2.2).
  • Flo. PMC7927251, PMC10956037, and a real export (EXPRESSIVENESS.md §2.3).
  • Natural Cycles. Help centre; Daily Entries.csv (EXPRESSIVENESS.md §2.4).
  • drip. src/db/schemas/4.js.
  • Fitbit and Samsung exports (EXPRESSIVENESS.md §2.5).

Clinical relevance:

  • bleeding, flow, clots and pain give the FIGO AUB System 1 parameters;
  • BBT, LH, PdG and mucus confirm ovulation and luteal length;
  • pregnancy and breastfeeding explain amenorrhea;
  • contraception and procedures explain bleeding patterns;
  • analgesics, tranexamic acid and iron show treatment burden;
  • vasomotor and sleep symptoms matter for perimenopause;
  • mood matters for PMS/PMDD.

The wellbeing resolutions are:

  • Mood: HealthKit's 7-point valence. Tag-style moods (Clue, Flo, drip) are custom coded sets.
  • Energy: Clue's four levels.
  • Sleep: minutes. Wearable total-sleep 95% limits of agreement against polysomnography span about ±60–130 min (Schyvens et al. 2025, SLEEP Advances 6(2):zpaf021), so coarsening to 15–30 minutes loses nothing real.

11. Excluded on principle

These are excluded on principle, not for lack of a slot; the full list with handling advice is EXPRESSIVENESS.md §3:

  • free text;
  • sub-daily streams;
  • predictions and derived flags;
  • per-fact attributes (an "excluded" BBT, a device per reading);
  • values outside a built-in code's definition (pain beyond 0–10, flow beyond the five levels) — use a custom series with its own code instead;
  • the order of ordinal levels;
  • identifiers, address, contact and gender (only name and birth date are carried), and more than one source device.

Things that only lack a built-in slot are expressible as a custom series or escape: for example symptom severity, multi-select emotions, other energy and mood scales, cervix position, sleep stages, libido scales, app tags and RxNorm medications.

12. Samples

generate({persona, seed?, start?, days?}) is deterministic: mulberry32, no clock. SAMPLES holds the sixteen personas, and golden.json pins them.

12.1 Physiology engine and sources

  • Cycles. Each cycle is follicular + luteal. The luteal phase is about 13 ± 1.2 d and the follicular phase carries the variability. Sources: Bull et al. 2019 (612,613 cycles: 29.3 ± 5.2 d; follicular 16.9 ± 5.3; luteal 12.4 ± 2.4; per-user SD 2.6 d; bleed 4.0 ± 1.5 d) and Fehring 2006.
  • LH. Positive the day before ovulation, with estrogen-rise results 2–4 days earlier (Su et al. 2017; Ecochard 2001).
  • BBT. A rise of 0.32–0.38 °C over days +1..+3, with noise SD 0.06–0.09 °C, 4% disturbed mornings, a premenstrual drop, and a persistent rise in pregnancy. Sources: Barron & Fehring via Fukaya 2017; Natural Cycles 0.2–0.45 °C; Prior 2024. Measured on the power tracker, the rise is 0.34–0.46 °C.
  • Mucus. Progresses to egg-white on ovulation −1/0 (Billings/WHO 1978; Fehring).
  • Symptoms. Phase-linked, with a shared "bad day" factor (Apple Women's Health Study; Pierson et al. 2021).
  • Adherence. Skipped days, paused and abandoned categories, categories started mid-year, and an unlogged period that produces the spurious 60-day cycle Li et al. 2020 had to exclude.

12.2 Personas (all synthetic)

samplewindowstory
(a) power-tracker2025-12-01, 365 dFertility awareness, then trying to conceive; conceives in month 11. BBT 0.01 °C, LH with estrogen results, mucus, PdG, pregnancy tests, wearable sleep, mood, energy, ibuprofen, folic acid, one SNOMED escape symptom. Source app.
(b) copper-iud2025-12-08, 365 dThe case the design started from, extended to a year. IUD inserted 2026-03-18 (procedure + interval, condoms before). Heavier, longer, more painful periods that improve. Intermenstrual spotting that does not fade (Hubacher 2009). BBT for three cycles at 06:45 −05:00.
(c) pcos2025-10-15, 400 dCycles of 34–88 d, mostly anovulatory. Monophasic BBT in °F. LH strips positive without ovulation. Negative pregnancy tests. Hirsutism and metformin as escapes. One condom failure followed by emergency contraception. Reported PCOS (onset 2019); answers: 5 periods a year, usual cycle 36–90 days.
(d) minimal2026-01-01, 365 dLayer 0 only, with gaps; one period unlogged.
(e) perimenopause2025-11-20, 365 dSTRAW+10 late transition (cycles 20–66 d). Hot flashes and night sweats rising (SWAN). Insomnia, clots, tranexamic acid, iron. Reported perimenopausal state.
(f) combined-pill2026-01-05, 364 dCombined pill all year. pill log with 4 missed pills and breakthrough spotting. Withdrawal bleeds starting on pill-free day 3–5.
(g) near-empty2026-01-01, 365 dBreastfeeding, lactational amenorrhea, one 3-day bleed logged.
(h) own-vocabulary2026-02-01, 365 dOutside the built-ins throughout: 5-level energy and an 8-option emotion multi-select (custom coded, app codes with labels); per-symptom severity for cramps and headache (custom coded, SNOMED Mild / Moderate / Severe); cervix position; wrist-temperature deviation (the built-in skinTemp); RxNorm ibuprofen 400 mg and naproxen sodium 220 mg; SNOMED and app-local symptoms ("Brain fog"); a sex escape value ("Solo sex"); a diaphragm (custom contraception interval); minute-precision sleep.
(i) wellness-diary2026-01-10, 365 dThe same card used mostly for something else: a migraine and wellness diary with migraine yes/no every day (custom boolean, SNOMED 37796009 as code), trigger multi-select, caffeine (mg), steps (LOINC 41950-7), resting heart rate (app code, because LOINC 40443-4 triggers the R4 heart-rate profile), the built-in pain score on attack days, sleep, RxNorm sumatriptan with daily magnesium and riboflavin (explicit missed doses), and only 31 Layer 0 bleeding facts.
(j) calendar-only2026-01-01, 365 dBuilt by import-ics.ts from calendar-sample.ts (a Google Calendar-style export): 58 bleeding days, spotting, a "Period due?" reminder skipped, no explicit negatives, nothing logged from mid-June to late August. Answers: usual cycle 26–32 days, 12 periods a year. Birth year only.
(k) smart-cup-hmb2026-01-15, 365 dHeavy menstrual bleeding measured with a smart cup: 126–244 mL of fluid per period (about 60–120 mL blood) before a myomectomy on day 196, 59–87 mL after. Clots, fatigue, pain; reported fibroids (2023) and iron-deficiency anaemia; tranexamic acid on heavy days; daily iron with missed doses.
(l) wearable2026-03-01, 365 dA ring: nightly skin temperature deviation (biphasic, about +0.33 °C luteal), minute-precision sleep; light manual logging (bleeding without flow, occasional cramps). Ovulation visible without BBT.
(m) post-ablation2026-02-01, 365 dEndometrial ablation 2023-05 (before the window), ovaries intact: almost no bleeding (4 spotting days, explicit no-bleeding days), but biphasic BBT and cyclic breast tenderness, bloating and mood continue. Adenomyosis resolved; answers: 0 periods a year, no period in the last year. Absent bleeding is not menopause.
(n) vitals-follow-up2026-01-20, 365 dHypertension follow-up while tracking cycles: blood pressure (85354-9, systolic and diastolic components in mm[Hg]) on about half the days, falling from about 146/94 to 130/84 as treatment takes effect; resting heart rate (8867-4) most mornings, a little higher in the luteal phase; weight (29463-7, 0.1 kg) on Mondays; daily lisinopril (RxNorm) with occasional misses; essential hypertension reported (onset 2025-09); ordinary bleeding with cramps; source app.
(o) timestamped2026-01-12, 365 dAn app that timestamps every entry (held out; designed after the time and entry coding, which were tuned on synthetic data added to power-tracker). New York offsets (−05:00, −04:00 from 8 March to 31 October) and ten days in Lisbon (+01:00) in June. BBT on waking (about 06:25 on weekdays, 08:00 at weekends), LH tests in the afternoon, mood and energy at an evening check-in, bleeding whenever the app was opened (on the first day of most periods, spotting in the morning and the flow in the evening). Symptoms at the time each was noticed: cramps in the morning and again in the evening on heavy days, a headache in the afternoon, the rest at the check-in. Pain in the morning and at the check-in in the first days of a period; ibuprofen once or twice on those days. A pregnancy test synced with seconds; two onboarding answers and the removal of a hormonal IUD (day 17) with their times.
(p) bp-twice-daily2026-02-02, 365 dHome blood pressure morning and evening (held out; a variant of (n)). A reading at about 07:10 on most days and another at about 21:30 on three quarters of those, a little lower; resting heart rate with the morning reading; a daily antihypertensive at about 07:25 with occasional misses; Pacific offsets with daylight saving time; ordinary bleeding with cramps; essential hypertension reported.

13. Measurements

From bun report.ts. The QR version is what one codec-reference byte plus the estimated payload needs with the dense-qr digit transport (src/transport.ts toQr); "–" means it does not fit version 40.

sampleentriesJSON Bdeflate-raw Bentropy estimate Bof which declarations Bof which identity BQR L / M
power-tracker2,8421,175,89031,8551,2646026 / 30
copper-iud (named)695258,9987,61534111412 / 14
pcos495165,9915,78728410011 / 13
minimal6219,80480635103 / 4
perimenopause1,435500,71614,5756796018 / 21
combined-pill631217,3466,4992431010 / 12
near-empty103,39149320102 / 3
own-vocabulary (named)2,226850,45225,8441,9445912533 / 37
wellness-diary2,417763,10127,7132,499366037 / –
calendar-only7327,6751,21563134 / 5
smart-cup-hmb820285,9618,4303391012 / 14
wearable745282,7948,0817091019 / 22
post-ablation617263,9817,5814731315 / 17
vitals-follow-up1,046487,18914,35676575019 / 23
timestamped1,286585,57519,9032,4001037 / –
bp-twice-daily1,324730,21922,0232,946620– / –
power-tracker coarsened: sleep 30 min, mood 5-pt, BBT 0.051,1106024 / 28
power-tracker coarsened: sleep 60 min, mood 3-pt, BBT 0.11,0176023 / 26
power-tracker coarsened: sleep 60 min, mood 3-pt, BBT unchanged1,1606025 / 28
wearable coarsened: skin temperature 0.056021017 / 19
wearable coarsened: skin temperature 0.1, sleep 15 min3701013 / 15

Identity is estimated as a presence bit, the names as length-prefixed UTF-8, and the birth date as 18 bits (day since 1900 plus precision). An identity-free card spends 1 bit on it.

coarsen maps mood 7→5 points as {1, 2, 2, 4, 6, 6, 7} and 7→3 points as {2, 2, 2, 4, 6, 6, 6}. Sleep, BBT, skin temperature (0.05 / 0.1) and volume (5 / 10 mL) are rounded to the nearest step, ties up. Energy is unchanged.

13.1 The entropy estimate

This is an estimate, not a bound. Each category is coded on its own, day by day, with an adaptive Krichevsky–Trofimov (add-½) estimator, using the cheaper of order 0 and order 1 (context = the previous day's value). That is what an adaptive arithmetic coder achieves, learning cost included.

  • Numeric series (BBT, skin temperature, volume, sleep, custom quantities, and each quantity component of a reading over the days it was recorded) are coded on their gcd grid, as the cheaper of direct values and day-to-day deltas. A reading with components adds its presence per day and each component's presence per reading.
  • The header is the window and one bit for the reduced flag.
  • Context (source name and version as UTF-8; conditions as table index, status, onset; answers; procedure dates as a day offset inside the window or year/month/day before it) at fixed-width cost.
  • Further entries: per series with repeats, the count per day (KT over 0..3) and about a byte per entry.
  • Times of day: a flag; per timed series one shared time (minutes and offset, 20 bits), or the has-time flags (KT), the minutes as a numeric series, the seconds when any and the offset changes; each timed answer or procedure 18 bits.
  • Declarations cover each escape concept once (SNOMED and digit codes as numbers; each unknown system URI once; text codes as UTF-8), labels, and custom-series headers.
  • Not exploited: the cycle structure across categories. A cycle-aware codec should land below these numbers.

Per-category bytes are in bun report.ts. For the power tracker:

categorybytes
BBT276
symptoms205
sleep183
source app name29
mood110
energy93
mucus82
pain64
bleeding62
sex46
ovulation test40
medications32
everything else< 30

What this means.

  • Years of the core cycle facts alone need 20–330 B (QR versions 2–14).
  • The power tracker needs about 1.2 KB (version 25-L). Half of that is irreducible daily numbers: BBT noise at 0.01 resolution, sleep, mood and energy. Coarsening saves at most about 20%.
  • Leaving the built-ins costs a fixed declaration overhead (EXPRESSIVENESS.md §4): 659 B for (h), mostly labels and app codes. Rich daily wearable numbers are the other large cost: (i)'s steps and resting heart rate.
  • Neither (h) nor (i) fits a small QR. Both are representable and round-trip losslessly.
  • The context features are cheap: a calendar-only year with two answers is ~56 B (QR 4-L), a smart-cup year ~332 B. Conditions cost about 2 B each, an answer 1.5 B. The source app's name (about 1 B per character) is the largest of them.
  • Nightly wearable temperature is as costly as BBT: about 290 B a year at 0.01 °C, 180 B at 0.05 and 130 B at 0.1.

14. Notes for the codec author

  • Encode exactly normalize(m). Decoding must give stringify(toBundle(m)) byte for byte; golden.json pins every sample.
  • Indices of the tables and enumerations in vocab.ts are the codes. The lists are append-only once shipped. The tables are BLEEDING, MUCUS, OVULATION_TEST, TEST_RESULT, SEX, MOOD, ENERGY, PILL_LOG, MED_STATUS, INTERVAL_KIND, PROCEDURE, CONDITION_STATUS, SKIN_TEMP_KIND, QUESTIONS (key order, and each coded question's answer order), BUILTIN_SYMPTOMS, BUILTIN_MEDICATIONS, BUILTIN_CONDITIONS and WELL_KNOWN_SYSTEMS.
  • Ranges:
    • patient: family 1–64 chars, given ≤ 3 × 1–64 chars, birthDate YYYY / YYYY-MM / YYYY-MM-DD from 1900 to the window start;
    • days 1..10,000; start 2000-01-01..2099-12-31;
    • pain 0–10; sleep 0–1440;
    • BBT hundredths: Cel 3400–4200, [degF] 9300–10760;
    • skin temperature hundredths: deviation Cel −500..500, [degF] −900..900; absolute Cel 2500–4000, [degF] 7700–10400;
    • volume 0–500 mL; answers per QUESTIONS (periods per year and ages 0–100, missed periods 0–3);
    • source.name 1–64 and source.version 1–32 characters (label character rules);
    • condition onsets and procedure dates before the window: YYYY, YYYY-MM or YYYY-MM-DD from 1900; procedure dates inside the window: full dates; nothing after the window;
    • quantities: |v / 10^scale| < 10^9 with scale 0–6 (so |v| < 10^15, 15 significant digits);
    • a component code has one shape, and as a quantity one unit, on the whole card;
    • times of day: hours 00–23, minutes and seconds 00–59, offset ±00:00..±14:00 in quarter hours, never −00:00;
    • entries: any number per series per day, identical or disagreeing (each its own fact); a reading entry records at least one component;
    • concepts and labels per §4; custom series ≤ 32; intervals ≤ 256; procedures ≤ 512; facts ≤ 20,000 (a bound on work, not on Bundle size).
  • Canonical order: MAPPING.md §3. Note the code-point order for non-SNOMED keys and the 100 × series index sub-rank for custom facts.
  • Repeats: never deduplicate or merge. Identical entries, a set item that repeats, a condition or procedure listed twice and a question answered twice are each a fact, kept in canonical order with their ties broken by value (conditions: code, then status — none, active, resolved — then onset, unstated first; answers: day, question, time, then value: coded answers in the question's answer order with escapes after, numbers ascending).
  • Serialization: MAPPING.md §2.
    • The six fixed displays are mandatory.
    • Labels become display on every coding of the concept.
    • Every fact carries subject: {"reference":"resource:0"}; with a source, every Observation also carries device: {"reference":"resource:1"}.
    • The Patient is {"resourceType":"Patient","id":"0"} without identity; otherwise it has name and/or birthDate and no id.
    • Numbers are printed from integers, with no trailing zeros.
    • Strings get JSON escaping of " and \, and are otherwise raw UTF-8.
  • Decimals: a custom quantity prints v / 10^scale in shortest form. With |v| < 10^15 and scale ≤ 6 (at most 15 significant digits) this equals the plain decimal literal.
  • Validation messages: validate() reports the field path and, for per-day data, the day and date ("... (day 57, 2026-03-03)"). Encoders should surface them. The accepted set (§6) is the contract an encoder must match exactly.