SHC vNext QR proof of concept

cycle-log: FHIR representation

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

toBundle(model) in to-bundle.ts returns the exact Bundle a cycle-log codec must emit, and stringify(bundle) returns its exact bytes. fromBundle(bundle) inverts it. The tests check fromBundle(JSON.parse(stringify(toBundle(m)))) equals normalize(m) on all twenty samples and on 300 random models that exercise every field, so the mapping is lossless for the model. Each sample's Bundle hash is pinned in golden.json.

Model semantics are in MODEL.md. This file covers the wire shape, the codes and the canonical form.

1. Bundle shape

Bundle  type=collection, no id/identifier; optional timestamp (from exportedAt); meta only on a reduced card
 entry[0]  resource:0  Patient (always)
 entry[1]  resource:1  Device (only when the model has a source)
 then                  Conditions, then all Procedures (sorted by date, kind, code, time),
                       then one Observation or MedicationStatement per dated fact, in the order of §3
  • Export timestamp (exportedAt) maps directly to FHIR Bundle.timestamp (YYYY-MM-DDTHH:MM:SS±HH:MM, seconds always written, +00:00 rather than Z; input FhirInstant accepts both Z and omitted :00 seconds). When exportedAt is omitted, Bundle.timestamp is absent. There is no synthetic tracking-window Observation.
  • A reduced card (reduced: true) is tagged "meta":{"tag":[{"system":"http://terminology.hl7.org/CodeSystem/v3-ObservationValue","code":"SUBSETTED","display":"subsetted"}]} on the Bundle. SUBSETTED is the R4 v3-ObservationValue code for "some information has been removed from the source object when the view this object contains was constructed" (checked in hl7.fhir.r4.core 4.0.1 and on tx.fhir.org, display "subsetted"); FHIR names it for exactly this use on Bundle.meta.tag. An unreduced card has no meta. fromBundle accepts no other meta.
  • The Patient is always resource:0. Every fact (Observation, MedicationStatement, Procedure, Condition) has "subject":{"reference":"resource:0"}.
  • The source app is one Device at resource:1: {"resourceType":"Device","deviceName":[{"name":…,"type":"user-friendly-name"}],"version":[{"value":…}]} (version only if stated). Every Observation then carries "device":{"reference":"resource:1"}. MedicationStatement, Procedure and Condition have no element that can reference a Device, so they do not.
  • Identity is optional and small. The model's patient carries at most a family name, up to three given names and a birth date.
    • With identity, the Patient is {"resourceType":"Patient","name":[{"family":…,"given":[…]}],"birthDate":…}, with each part present only if the model has it, and no id.
    • Without identity, it is exactly {"resourceType":"Patient","id":"0"}.
  • Why id: "0" for the identity-free Patient.
    • A completely empty Patient fails bdl-5 ("must be a resource unless there's a request or response"): R4 treats an element with no value or children as absent.
    • id is the least assertive content. It is a logical id with no clinical meaning, unlike active: true (which asserts the record is in active use), a name or a gender.
    • Both id and active validate cleanly; the id was chosen because it asserts nothing.
    • The id "0" matches the 0 of fullUrl resource:0. resource:N is not a RESTful URL, so R4 imposes no fullUrl/id consistency rule, and none is assumed. References always use the fullUrl.
    • A host that knows the person may replace the whole Patient.
  • No id, meta, text, identifier, performer, issued or note anywhere, except the Patient's id and a reduced card's Bundle tag above.
  • display appears on the codes of the built-in fact types and vital-signs category (§4.1), and on any non-built-in escape concept that carries coding[0].display; CodeableConcept.text appears on any non-built-in escape concept that carries text and on text-only { text } concepts.

Resources by model field

Model fieldcodevalueeffective
exportedAtBundle.timestamp (not a separate resource)YYYY-MM-DDTHH:MM:SS±HH:MM (seconds always written)–
conditionsCondition: optional clinicalStatus (condition-clinical active / resolved), code = the condition (ConditionKind → SNOMED CT, or any FHIR CodeableConcept), subject, optional onsetDateTime (the onset date as given), asserter = the Patient––
bleedingproposed menstrual-bleeding + displayvalueBooleaneffectiveDateTime date, or date and time (below)
bleeding flow states, in additionproposed menstrual-flow + displayvalueCodeableConcept proposed flow-*date (the bleeding fact's time)
volumeproposed menstrual-fluid-volumevalueQuantity integer mLdate
painLOINC 72514-3 + displayvalueQuantity integer {score}date
symptoms, one fact per symptomproposed symptom + displayvalueCodeableConcept (SymptomKind → SNOMED CT or proposed hot-flash, or any escape CodeableConcept including text-only { text })date
bbtproposed basal-body-temperature + display (distinct from LOINC 8310-5 Body temperature, which stays a vital-sign custom series)valueQuantity Cel or [degF] (natural decimal, up to 2 decimal places); optional components reading-excluded (valueBoolean: true) and reading-exclusion-reason (valueCodeableConcept)date
skinTempproposed skin-temperature-deviation (kind deviation) or nightly-skin-temperature (kind absolute); no categoryvalueQuantity Cel or [degF] (natural decimal, up to 2 decimal places); optional components reading-excluded and reading-exclusion-reasondate (the wake day)
mucusproposed cervical-mucusproposed mucus-*date
ovulationTestproposed ovulation-testSNOMED CT Negative / Positive / Indeterminate, proposed estrogen-surgedate
progesteroneTestproposed pdg-testSNOMED CT Negative / Positive / Indeterminatedate
pregnancyTestLOINC 2106-3SNOMED CT Negative / Positive / Indeterminatedate
sexSNOMED CT 364316005SNOMED CT 63537005 / 2314005 / 70256003, proposed no-sexual-intercoursedate
moodproposed mood-valenceproposed valence-* (7)date
energyproposed energy-levelproposed energy-* (4)date
sleepLOINC 93832-4valueQuantity integer mindate (the wake day)
pillproposed contraceptive-pill-takenvalueBoolean (true = taken, false = explicitly missed)date
medications, one per (date, code)MedicationStatement: status completed (taken) / not-taken; medicationCodeableConcept = the product (MedicationKind → SNOMED CT, or any escape CodeableConcept including RxNorm with display/text or text-only { text }); optional dosage[0].doseAndRate[0].doseQuantity (natural decimal UCUM quantity, up to 6 decimal places, when dose is recorded)–effectiveDateTime date
intervals contraceptionLOINC 8659-5LOINC answer from LL4578-2effectivePeriod start..end
intervals pregnantLOINC 82810-3LOINC LA15173-0effectivePeriod
intervals breastfeedingLOINC 63895-7LOINC LA29252-6effectivePeriod
proceduresProcedure: status completed; code = SNOMED CT procedure (built-in ProcedureKind) or any FHIR CodeableConcept–performedDateTime = the model's date (FhirDateTime: YYYY, YYYY-MM, YYYY-MM-DD, or full timestamp with seconds written in FHIR)
answersthe question's LOINC code (64700-8, 92656-8, 65930-0, 63889-0, 64701-6, 64702-4, 63888-2)coded questions: valueCodeableConcept LOINC answer (LL1227-9, LL361-7, LL1228-7) or escape CodeableConcept; numeric: valueQuantity integer with the question's UCUM unit (/a, {#}/(3.mo), a)date answered
custom interval {code, value}the given CodeableConceptvalueCodeableConcept the given CodeableConcepteffectivePeriod
custom valueType: "boolean"the series CodeableConceptvalueBooleandate
custom valueType: "coded", one fact per entrythe series CodeableConceptvalueCodeableConceptdate
custom valueType: "quantity"the series CodeableConceptvalueQuantity {value = natural decimal (≤ 6 decimal places), unit = code = the UCUM unit}date
custom valueType: "components", one fact per readingthe series CodeableConceptno value; component [{code: the component CodeableConcept, valueBoolean / valueCodeableConcept / valueQuantity}], one per recorded component, in the components' canonical orderdate

Addressing. toBundle writes resource:N fullUrls and references, no meta.profile, and the identity-free Patient's id "0". fromBundle accepts exactly the addressing and order the project's profiles allow: entries in any order, any distinct fullUrls (urn:uuid, RESTful, resource:N), any Resource.id, subject / asserter / device references in any form that resolves within the Bundle to the Patient or the Device (an exact fullUrl, or Type/id against the referring entry's RESTful fullUrl base; as in R4 and the HL7 validator, a Type/id from a urn:uuid or resource:N entry and a version-specific _history reference do not resolve and are refused), meta.profile naming the resource's own profile (PROFILE_URL(profileNameOf(resource)), and cycle-log-bundle on the Bundle), and the SUBSETTED tag with or without its display. An identity-free Patient carries some id. It refuses anything else, and on content it is the exact inverse of toBundle.

Intervals of one state (the same kind, or the same code and value) that overlap or touch mean the same days in that state as their union; normalize merges them, so toBundle writes one interval and fromBundle accepts several.

Entries and times of day. Every entry in a series' { date, ... }[] array is its own fact, as above: one Observation, MedicationStatement or reading per entry; a bleeding entry is its bleeding fact and, for a flow state, its flow fact, both with the entry's date. A dated fact is precise to the day (YYYY-MM-DD) unless its DateTime (or FhirDateTime on a procedure) includes a time; then effectiveDateTime (or performedDateTime) is YYYY-MM-DDTHH:MM:SS±HH:MM: the local time with the offset as stored, seconds always written (:00 when the time has none), +00:00 rather than Z (input accepts Z and :00). Intervals and conditions have no time. fromBundle turns every fact into an entry of its series array (a flow fact joins the bleeding fact of the same date and time), normalizes Z to +00:00, drops :00 seconds, and writes each series in canonical order; repeats and disagreements are separate facts and stay separate entries, never merged (two identical Observations are two entries).

Escapes, displays and custom series

  • Concepts (readable keywords & FHIR R4 CodeableConcept).
    • Built-in slots accept readable string keywords (SymptomKind, MedicationKind, ConditionKind, Mucus, Sex, Mood, Energy, ProcedureKind, IntervalKind, ExcludeReason, coded Answer values) that expand on decode to canonical SNOMED CT, LOINC, or cycle-log codings.
    • Escapes and custom[] use genuine FHIR R4 CodeableConcept objects: either {"coding":[{"system":…,"code":…,"display"?:…}],"text"?:…} or text-only {"text":…} (requiring no synthetic code-system URI).
    • Any CodeableConcept can appear as symptoms, medications, conditions, and escape values of mucus, tests, sex, mood, energy, exclusion reasons and coded answers, as well as custom-series codes and values, custom interval concepts, and procedures.
  • Built-in vs. escape display and text.
    • The six fixed displays appear only on Observation.code of the built-in bleeding, flow, symptom, pain and BBT facts, and on the vital-signs category.
    • For any built-in concept (BUILTIN_CONCEPTS), coding[0].display is optional on model input and stripped in canonical form and in the emitted Bundle (apart from the six fixed displays above), and CodeableConcept.text is not allowed.
    • For any non-built-in escape concept — whether in SNOMED CT, LOINC, RxNorm, ICD-10-CM, ATC, NDC, or an app-defined system URI — both coding[0].display and CodeableConcept.text (≤ 128 chars each) are preserved verbatim and emitted on every occurrence of that (system, code) (and all occurrences in the model must agree on the same display and the same text). This enables offline human readability even for standard escape codes (as in offline-displays).
    • Text-only concepts ({"text":…}) emit {"text":…} directly as FHIR CodeableConcept (as in text-tags).
    • fromBundle checks displays and text by position, rejecting unexpected displays/text on built-in concepts or conflicting displays/text for one (system, code).
  • Custom series (valueType).
    • Each declares its FHIR Observation.value[x] via valueType ("boolean" → valueBoolean, "coded" → valueCodeableConcept, "quantity" → valueQuantity decimal in UCUM unit, "components" → component[] with no top-level value) and has the shape of every built-in fact: status final, effectiveDateTime (date, or date and time), subject resource:0.
    • It may not use a built-in series code. Anything with a built-in code is carried by the built-in, whose coded values accept any CodeableConcept.
    • Vital signs. A series whose code is one of the LOINC codes for which the HL7 validator applies an R4 vital-signs profile (the R4 ValueSet observation-vitalsignresult plus the related codes the validator maps, R4_VITAL_SIGN_CODES in vocab.ts) is a vital sign: every fact carries "category":[{"coding":[{"system":"http://terminology.hl7.org/CodeSystem/observation-category","code":"vital-signs","display":"Vital Signs"}]}]. Any other series has no category.
    • Components. A reading (valueType: "components") is one Observation with no value of its own and a component per recorded value (each component declares its own valueType: "boolean", "coded", or "quantity"). A component not recorded that day is absent from the list; a day with no recorded component has no Observation. fromBundle rebuilds the components from the codes and value types it finds; their order is the canonical concept order, because a Bundle carries none.
  • Quantity values. Custom quantity values are natural JSON decimals (up to 6 decimal places), printed in shortest form (valueQuantity.value). Internally, the codec chooses the smallest exact scale (0..6) that keeps every value an integer.
  • Equivalence. Built-in pain and sleep (quantity), symptoms, mucus, tests, sex, mood and energy (coded), and the pill log (boolean) are produced by the same three renderers as custom series. For each, the facts are identical to the equivalent custom series apart from Observation.code. A test checks this for six of them. Bleeding/flow, BBT, built-in intervals, and medications and procedures (MedicationStatement and Procedure resources) are special (EXPRESSIVENESS.md §1).

Quantities always carry value, unit, system (http://unitsofmeasure.org) and code, with unit equal to code. R4's body-temperature profile requires unit, and the same rule everywhere means one rule to implement.

Vital signs and the R4 vital-signs profiles

What the profiles in hl7.fhir.r4.core 4.0.1 require (StructureDefinitions vitalsigns, heartrate, resprate, oxygensat, bodyheight, headcircum, bodyweight, bmi, bp, bodytemp, vitalspanel), and what the card does about each:

requirementguaranteed by
status, subject (the Patient), effective[x] precise to the day (vs-1)every fact
category vital-signs (slice VSCat, 1..1)emitted on every fact of a series whose code is in R4_VITAL_SIGN_CODES
code with the profile's own LOINC coding (e.g. 8867-4 for heartrate)the series code, when it is the profile's own code
a value, or components (vs-2); each component has a value (vs-3)a reading always has at least one recorded component, and only recorded components are written
the profile's UCUM unit: heart rate and respiratory rate /min, oxygen saturation %, body height and head circumference cm or [in_i], body weight kg, g or [lb_av], BMI kg/m2validate (rule vital-sign-profile) requires it for those seven codes
a Quantity component's unit in ucum-vitals-common (required binding)validate requires it for every quantity component of a vital-sign series
bp: components 8480-6 and 8462-4, each a Quantity in mm[Hg]validate requires 85354-9 to be a components series, and its 8480-6 / 8462-4 components to be quantities in mm[Hg]

Not guaranteed:

  • A blood-pressure reading with only one of its two components. The model carries it (a component can be not recorded), but bp requires both (component min 2, each slice 1..1); the validator reports two errors per such reading.
  • The validator's related codes (for example 40443-4 "Heart rate --resting", 8889-8): the validator applies the matching profile, which also requires the profile's own coding (8867-4); the card writes one coding per concept, so such series do not conform to that profile. They carry the category and otherwise validate. Use the profile's own code where it says the same thing.
  • 8480-6 or 8462-4 as series of their own, and the panel 85353-1 (which requires hasMember): carried, not conformant to the profiles the validator applies.
  • A boolean or coded series under a vital-sign code: carried with the category; the code-specific profiles expect a Quantity.

The sample vitals-follow-up (heart rate 8867-4 in /min, weight 29463-7 in kg, blood pressure 85354-9 with both components in mm[Hg]) validates with 0 errors (§6.1). Basal body temperature uses the proposed code basal-body-temperature (separate from LOINC 8310-5 "Body temperature", which stays available as an R4 vital-sign custom series for fever / clinical temperatures — demonstrated in bbt-exclusions-and-fever).

Bleeding: the bleeding fact and the flow fact

Model stateFacts emitted on the date
(omitted date)none
no-bleedingmenstrual-bleeding false
flow-nonemenstrual-bleeding false, then menstrual-flow flow-none
bleedingmenstrual-bleeding true
spotting / light / moderate / heavymenstrual-bleeding true, then menstrual-flow flow-spotting / flow-light / flow-moderate / flow-heavy

These are all the combinations for one bleeding entry. A bleeding fact is written whenever bleeding or explicit no-bleeding is recorded, and alongside every flow fact; flow-none pairs with false and spotting-or-more with true. So flow without a bleeding fact, true with flow-none, and false with spotting-or-more are excluded; fromBundle and the tests reject each one. A day may have any number of bleeding entries, timed or not, identical or disagreeing (MODEL.md §8), each its own bleeding fact and, for a flow state, its own flow fact. fromBundle recovers them as a multiset per day and time, with no pairing of individual facts needed: of f false facts, t true facts, n flow-none facts and the flow levels L, there are n × flow-none, (f − n) × no-bleeding, the levels L, and (t − |L|) × bleeding. This is exact because each state contributes a fixed set of facts; a Bundle with more flow-none facts than false facts, or more levels than true facts, at one day and time is refused.

Why these shapes

  • Observation for every per-day fact and every state interval. These are things the person observed or reported.
  • MedicationStatement for medications.
    • {"resourceType":"MedicationStatement","status":"completed"|"not-taken","medicationCodeableConcept":…,"subject":{"reference":"resource:0"},"effectiveDateTime":"YYYY-MM-DD"} (with a time when the medication series has one that day).
    • R4 requires status, medication[x] and subject (all 1..1); nothing else is required.
    • completed means the person took it that day. not-taken is an explicitly recorded miss.
    • The product is any concept: a built-in SNOMED CT product, RxNorm, or another escape.
  • Procedure for IUD and implant insertion or removal, emergency contraception and custom procedures.
    • {"resourceType":"Procedure","status":"completed","code":…,"subject":{"reference":"resource:0"},"performedDateTime":"YYYY-MM-DD"}.
    • R4 requires status and subject. code is 0..1 and is always emitted.
    • Emergency contraception is SNOMED CT 1372819003 "Administration of postcoital oral contraceptive". Its fully specified name carries the semantic tag (procedure). A known product (ulipristal 703737005, a levonorgestrel product) can additionally be logged as a medication escape.
  • Contraceptive pill log.
    • It is one boolean Observation per day, in the same pattern as menstrual bleeding: the proposed code contraceptive-pill-taken with valueBoolean. Absence means not recorded.
    • It does not name the pill. The contraception interval (LOINC 8659-5 = combined or progestin-only pill) covering the day does.
    • SNOMED CT 315604002 "Missed contraceptive pill (situation)" covers only the missed case, and nothing exists for "pill taken today". The CodeSystem definition records that false is equivalent to 315604002.
  • Contraception, pregnancy and breastfeeding as Observations with effectivePeriod. The period is the calendar date range (start..end) during which the state held.
    • LOINC 8659-5, 82810-3 and 63895-7 are point-in-time codes, so the validator adds an information-level note.
    • The alternative, one dated Observation per day, would multiply entries about 300-fold.
  • BBT uses the proposed code basal-body-temperature (separate from LOINC 8310-5 Body temperature, so fever readings recorded as vital signs never mix into fertility thermal-shift detection). Disturbed readings carry reading-excluded (valueBoolean: true) and an optional reading-exclusion-reason component (fever, alcohol, poor-sleep, late-wake, travel, stress, medication, other, or any escape concept).
  • Condition for reported conditions.
    • R4 requires only subject, plus code by convention.
    • clinicalStatus appears only when the person stated it.
    • There is no verificationStatus: "confirmed" would claim more than a self-report can.
    • There is no category: problem-list-item and encounter-diagnosis are clinical-record categories, and con-3 only applies to problem-list items.
    • asserter = the Patient marks the condition as patient-reported.
  • Reduced cards carry the R4 SUBSETTED tag rather than a list of what was reduced: the model has one flag (MODEL.md §8).
  • Wearable temperature uses proposed codes, not LOINC.
    • LOINC 39106-0 "Temperature of Skin" is nominal scale (the validator warns on a quantity) and is not a sleep aggregate.
    • Neither proposed code is in the set of LOINC codes the validator binds to R4 vital-signs profiles, so no category is needed.
    • For a deviation the quantity is a difference expressed in Cel (or [degF]), as the code's definition says.
  • Measured volume uses a proposed code. SNOMED CT 364308001 "Quantity of menstrual blood loss" means blood; a cup collects menstrual fluid, whose blood fraction varies widely between people (1.6% to 81.7%, Fraser 1985).
  • Screening answers use the questions' own LOINC codes and answer lists. An answer is dated on the day it was given, and the card has no computed summaries.

2. Canonical serialization (stringify)

  • UTF-8 JSON with no insignificant whitespace and no trailing newline.
  • Key order. Every object's keys follow this single global order, which is FHIR's element order for every object type that occurs (Bundle and its meta, entry, Patient, HumanName, Device and its deviceName and version, Observation and its component, MedicationStatement, Procedure, Condition, CodeableConcept, Coding, Quantity, Period, Reference) merged without conflict. Any other key is an error.
    resourceType id meta tag name type timestamp entry fullUrl resource deviceName version status clinicalStatus
    category coding text value unit system code display medicationCodeableConcept subject reference effectiveDateTime
    effectivePeriod start end dosage doseAndRate doseQuantity performedDateTime onsetDateTime valueBoolean
    valueCodeableConcept valueQuantity device component asserter family given birthDate
    
  • Numbers use the ECMAScript shortest round-trip form (JSON.stringify).
    • Pain, sleep, volume and numeric answers are integers.
    • BBT and skin temperature are natural decimals with up to 2 decimal places (36.5, 37, 98.66, -0.31), printed with no trailing zeros.
    • Medication doses and custom quantities are natural decimals with up to 6 decimal places, printed with no trailing zeros.
    • The Rust WASM codec formats all decimals with exact integer arithmetic (zero floats).
  • Strings use JSON.stringify escaping. Built-in strings are ASCII. Escape codes and labels may contain any Unicode except control characters and unpaired surrogates, so a codec must escape " as \" and \ as \\ and output everything else as UTF-8 unchanged.
  • Dates are YYYY-MM-DD, directly from the model's calendar dates. A time of day follows as THH:MM:SS (seconds always two digits, 00 when not recorded) and the offset exactly as stored (+00:00, never Z). Bundle.timestamp uses the same instant format when exportedAt is present.

3. Entry order

The order is a pure function of the normalized model:

  1. resource:0 is the Patient.
  2. resource:1 is the Device, if the model has a source.
  3. Conditions, in canonical concept order (condition table index, then SNOMED CT ids ascending, then code-point order).
  4. Procedures (all procedures, unified), sorted by date (as a string: 2019 < 2019-05 < 2019-05-03 < 2020), then index in PROCEDURE, then code, then time.
  5. Every other entry, sorted by (date, rank, sub-rank). Date is the fact's calendar date, or start for an interval. Within one series and date, the entries come in their canonical order (MODEL.md §8: without a time first, then by instant).
rankkindsub-rank (within the same date and rank)
1intervalposition in the normalized intervals list, sorted by (start, index in INTERVAL_KIND, end)
2screening answerposition in the normalized answers list (date, then index in QUESTIONS, then time)
3menstrual-bleeding, each followed by its menstrual-flow factthe entry's position on the date
4(unused: flow facts follow their bleeding fact)–
5volume–
6pain–
7symptomthe entry's position on the date: plain dates in canonical concept order (below) with the symptom table
8BBT–
9skin temperature–
10cervical mucus–
11ovulation test–
12progesterone (PdG) test–
13pregnancy test–
14sexual intercourse–
15mood–
16energy–
17sleep–
18pill log–
19MedicationStatement (taken or not-taken)the entry's position on the date: plain dates in canonical medication order (built-in table index, then SNOMED CT ids ascending numerically, then other keys in code-point order)
20custom series100,000 × (position of the series in the canonical custom list, which is sorted by code) + the entry's position on the date

Concept order everywhere is: built-in table index (where a table exists), then coded concepts before text-only concepts (SNOMED CT ids ascending numerically, then other coded keys in Unicode code-point order, equal to UTF-8 byte order), then text-only { text } concepts in Unicode code-point order of their text. Custom intervals sort after built-in kinds that start the same date, by (code, value, end). Procedures sort by date string, then built-in kind index, then custom procedures by code, then time. Every per-day series not listed with a sub-rank above has, for its entries on one date, the entry's position on that date.

fullUrl is resource:<position>.

4. Fixed displays and things deliberately not done

The design started from the HL7 Period Tracking implementation guide; reconciling these codes and shapes with it is future work. The Bundles are validated against FHIR R4 core and the R4 vital-signs profiles (§6); the project's own profiles, generated from the model, plug into the same run (PROJECT_PROFILES, §6.1).

4.1 Fixed displays

  • display on the fixed code codings. The built-in bleeding, flow, symptom and BBT facts (proposed codes menstrual-bleeding "Menstrual bleeding", menstrual-flow "Patient-reported menstrual flow category", symptom "Symptom", basal-body-temperature "Basal body temperature"), pain (LOINC 72514-3 "Pain severity - 0-10 verbal numeric rating [Score] - Reported"), and the vital-signs category ("Vital Signs", emitted on R4 vital-sign custom series) carry these six display strings exactly. Value codings carry no display.
  • Quantity unit is required by R4's body-temperature profile and emitted consistently on all Quantity values.
  • id, text, meta (except SUBSETTED on reduced cards), and Bundle identifier are omitted. Bundle.timestamp is written when exportedAt is present.

4.2 Things deliberately not done

  • No meta.profile. Conformance is checked by validating against the profiles explicitly (§6).
  • A Device appears only when the model names a source app, and the Patient carries identity only if the model has it (§1).
  • No performer. The validator's best-practice warning is accepted.

5. Codes

5.1 Fact-type and flow codes (proposed)

menstrual-bleeding, menstrual-flow, symptom, flow-none, flow-spotting, flow-light, flow-moderate, flow-heavy, basal-body-temperature, reading-excluded, reading-exclusion-reason and the exclude-* reasons are concepts of this codec's CodeSystem (§5.3), with definitions there. Built-in symptoms 0–13 are the 14 SNOMED CT starter symptoms the design started from; pain (LOINC 72514-3), clinical body temperature / fever (LOINC 8310-5, observation-category#vital-signs in custom[]) and IUD insertion (SNOMED CT 65200003) are standard codes in the table below.

5.2 Standard codes, verified

Every code was looked up on 2026-12-03 with https://tx.fhir.org/r4/CodeSystem/$lookup?system=…&code=…:

  • LOINC 2.83;
  • SNOMED CT International Edition http://snomed.info/sct/900000000000207008/version/20260701;
  • RxNorm 2026-11-24;
  • ATC 2026;
  • HL7 terminology (condition-clinical);
  • UCUM.

The table covers every built-in code and every coding used by the first fourteen samples and the test fixtures, 162 codes in all (timestamped and bp-twice-daily use no other code; the tests check every sample). It also lists codes that were considered and not used: ATC G03AA/AC/AD and SNOMED 315604002.

All are active. bun verify-codes.ts repeats the lookups and rewrites codes-verified.json, which holds the full evidence: display, inactive flag, version, parents and answer lists. The tests fail if the mapping can emit a code that is neither in that file nor defined in the proposed CodeSystem.

SystemCodeDisplay returnedStatusUsed forEvidence
LOINC72514-3Pain severity - 0-10 verbal numeric rating [Score] - ReportedactiveObservation.code (pain); sample power-tracker; sample copper-iud; sample pcos; sample perimenopause; sample combined-pill; sample wellness-diary; sample smart-cup-hmblookup
LOINC8310-5Body temperatureactiveObservation.code (bbt); sample power-tracker; sample copper-iud; sample pcos; sample post-ablationlookup
LOINC2106-3Choriogonadotropin [Presence] in UrineactiveObservation.code (pregnancyTest); sample power-tracker; sample pcoslookup
SNOMED CT364316005Sexual intercourse observableactiveObservation.code (sex); sample power-tracker; sample copper-iud; sample pcos; sample combined-pill; sample own-vocabularylookup
LOINC93832-4Sleep durationactiveObservation.code (sleep); sample power-tracker; sample perimenopause; sample own-vocabulary; sample wellness-diary; sample wearablelookup
LOINC8659-5Birth control method - ReportedactiveObservation.code (contraception); sample power-tracker; sample copper-iud; sample combined-pill; sample near-empty; sample own-vocabularylookup
LOINC82810-3Pregnancy statusactiveObservation.code (pregnancy); sample power-trackerlookup
LOINC63895-7Breastfeeding statusactiveObservation.code (breastfeeding); sample near-emptylookup
SNOMED CT260385009NegativeactiveovulationTest value; progesteroneTest value; pregnancyTest value; sample power-tracker; sample pcoslookup
SNOMED CT10828004PositiveactiveovulationTest value; progesteroneTest value; pregnancyTest value; sample power-tracker; sample copper-iud; sample pcoslookup
SNOMED CT82334004IndeterminateactiveovulationTest value; progesteroneTest value; pregnancyTest value; sample pcoslookup
SNOMED CT63537005Protected sexual intercourseactivesex value; sample power-tracker; sample pcos; sample combined-pill; sample own-vocabularylookup
SNOMED CT2314005Unprotected sexual intercourseactivesex value; sample power-tracker; sample pcos; sample combined-pilllookup
SNOMED CT70256003Sexual intercourse - findingactivesex value; sample power-tracker; sample copper-iudlookup
SNOMED CT431416001Menstrual crampactivesymptom 0: Menstrual cramp; sample power-tracker; sample perimenopause; sample combined-pill; sample own-vocabulary; sample wearablelookup
SNOMED CT161891005Backacheactivesymptom 1: Backachelookup
SNOMED CT25064002Headacheactivesymptom 2: Headache; sample power-tracker; sample copper-iud; sample combined-pill; sample own-vocabularylookup
SNOMED CT37796009Migraineactivesymptom 3: Migraine; sample wellness-diarylookup
SNOMED CT271681002Stomach acheactivesymptom 4: Stomach achelookup
SNOMED CT422587007Nauseaactivesymptom 5: Nausea; sample power-tracker; sample combined-pilllookup
SNOMED CT55222007Tenderness of breastactivesymptom 6: Breast tenderness; sample power-tracker; sample post-ablationlookup
SNOMED CT43548008Mittelschmerzactivesymptom 7: Ovulation pain; sample power-tracker; sample post-ablationlookup
SNOMED CT84229001Fatigueactivesymptom 8: Fatigue; sample power-tracker; sample copper-iud; sample pcos; sample smart-cup-hmblookup
SNOMED CT116289008Abdominal bloatingactivesymptom 9: Abdominal bloating; sample power-tracker; sample copper-iud; sample own-vocabulary; sample post-ablationlookup
SNOMED CT366979004Depressed moodactivesymptom 10: Depressed mood; sample copper-iud; sample pcoslookup
SNOMED CT55929007Feeling irritableactivesymptom 11: Feeling irritable; sample power-tracker; sample copper-iud; sample post-ablationlookup
SNOMED CT73595000Stressactivesymptom 12: Stress; sample power-trackerlookup
SNOMED CT71315007Dyspareuniaactivesymptom 13: Dyspareunia; sample copper-iudlookup
SNOMED CT11381005Acneactivesymptom 14: Acne; sample power-tracker; sample pcoslookup
SNOMED CT30473006Pain in pelvisactivesymptom 15: Pain in pelvislookup
SNOMED CT279039007Low back painactivesymptom 16: Low back pain; sample power-trackerlookup
SNOMED CT53430007Pain of breastactivesymptom 17: Pain of breastlookup
SNOMED CT18963009Mood swingsactivesymptom 18: Mood swings; sample power-tracker; sample perimenopauselookup
SNOMED CT48694002Anxietyactivesymptom 19: Anxiety; sample perimenopauselookup
SNOMED CT62315008Diarrheaactivesymptom 20: Diarrhea; sample power-trackerlookup
SNOMED CT14760008Constipationactivesymptom 21: Constipationlookup
SNOMED CT404640003Dizzinessactivesymptom 22: Dizzinesslookup
SNOMED CT248132003Craving for food or drinkactivesymptom 23: Craving for food or drink; sample power-trackerlookup
SNOMED CT289532003Passing clots vaginallyactivesymptom 24: Passing clots vaginally; sample copper-iud; sample perimenopause; sample smart-cup-hmblookup
SNOMED CT42984000Night sweatsactivesymptom 26: Night sweats; sample perimenopauselookup
SNOMED CT193462001Insomniaactivesymptom 27: Insomnia; sample perimenopauselookup
SNOMED CT31908003Vaginal drynessactivesymptom 28: Vaginal dryness; sample perimenopauselookup
SNOMED CT80313002Palpitationsactivesymptom 29: Palpitations; sample perimenopauselookup
SNOMED CT165232002Urinary incontinenceactivesymptom 30: Urinary incontinencelookup
SNOMED CT225038006Memory lapsesactivesymptom 31: Memory lapses; sample perimenopauselookup
SNOMED CT56317004Alopeciaactivesymptom 32: Alopecia (hair loss)lookup
SNOMED CT58436003Increased libidoactivesymptom 33: Increased libido; sample power-trackerlookup
SNOMED CT8357008Reduced libidoactivesymptom 34: Reduced libidolookup
SNOMED CT38268001Ibuprofen-containing productactivemedication 0: Ibuprofen-containing product; sample power-tracker; sample copper-iudlookup
SNOMED CT11847009Naproxen-containing productactivemedication 1: Naproxen-containing product; sample pcoslookup
SNOMED CT90332006Acetaminophen-containing productactivemedication 2: Acetaminophen-containing product; sample perimenopauselookup
SNOMED CT34364009Mefenamic acid-containing productactivemedication 3: Mefenamic acid-containing productlookup
SNOMED CT109006003Tranexamic acid-containing productactivemedication 4: Tranexamic acid-containing product; sample perimenopause; sample smart-cup-hmblookup
SNOMED CT30729008Iron-containing productactivemedication 5: Iron-containing product; sample perimenopause; sample smart-cup-hmblookup
SNOMED CT6247001Folic acid-containing productactivemedication 6: Folic acid-containing product; sample power-trackerlookup
LOINCLA137-2Noneactiveinterval value: none; sample power-trackerlookup
LOINCLA27908-5Combined oral contraceptive pillsactiveinterval value: combined-pill; sample combined-pilllookup
LOINCLA27909-3Progestin only contraceptive pillsactiveinterval value: progestin-pilllookup
LOINCLA16581-3Contraceptive patchactiveinterval value: patchlookup
LOINCLA27911-9Vaginal ringactiveinterval value: ringlookup
LOINCLA27907-7Injectablesactiveinterval value: injectionlookup
LOINCLA27901-0Implantable rodactiveinterval value: implantlookup
LOINCLA27902-8IUD with Progestinactiveinterval value: hormonal-iudlookup
LOINCLA27903-6IUD copperactiveinterval value: copper-iud; sample copper-iudlookup
LOINCLA27904-4IUD unspecifiedactiveinterval value: iud-unspecifiedlookup
LOINCLA27912-7Male condomactiveinterval value: condom; sample copper-iudlookup
LOINCLA27918-4Fertility awareness-based methodsactiveinterval value: fertility-awareness; sample power-trackerlookup
LOINCLA27919-2Lactational amenorrhea methodactiveinterval value: lactational-amenorrhea; sample near-emptylookup
LOINCLA15173-0Pregnantactiveinterval value: pregnant; sample power-trackerlookup
LOINCLA29252-6Currently breastfeedingactiveinterval value: breastfeeding; sample near-emptylookup
SNOMED CT65200003Insertion of intrauterine contraceptive deviceactiveprocedure: iud-insertion; sample copper-iudlookup
SNOMED CT1263416007Removal of intrauterine contraceptive deviceactiveprocedure: iud-removallookup
SNOMED CT169553002Implantation of subcutaneous contraceptiveactiveprocedure: implant-insertionlookup
SNOMED CT301807007Removal of subcutaneous contraceptive implantactiveprocedure: implant-removallookup
SNOMED CT1372819003Administration of postcoital oral contraceptiveactiveprocedure: emergency-contraception; sample pcoslookup
SNOMED CT236886002Hysterectomyactiveprocedure: hysterectomylookup
SNOMED CT265060005Endometrial ablationactiveprocedure: endometrial-ablation; sample post-ablationlookup
SNOMED CT83152002Oophorectomyactiveprocedure: oophorectomylookup
SNOMED CT76876009Excision of bilateral ovariesactiveprocedure: bilateral-oophorectomylookup
SNOMED CT42010004Uterine myomectomyactiveprocedure: myomectomy; sample smart-cup-hmblookup
SNOMED CT11401008Dilation and curettage of uterusactiveprocedure: d-and-clookup
SNOMED CT236884004Excision of uterine polypactiveprocedure: polypectomylookup
SNOMED CT312138002Embolization of uterine arteryactiveprocedure: uterine-artery-embolizationlookup
SNOMED CT237055002Polycystic ovary syndromeactivecondition 0: Polycystic ovary syndrome; sample pcoslookup
SNOMED CT95315005Uterine leiomyomaactivecondition 1: Uterine leiomyoma (fibroids); sample smart-cup-hmblookup
SNOMED CT784314006Uterine adenomyosisactivecondition 2: Uterine adenomyosis; sample post-ablationlookup
SNOMED CT1237359009Endometrial polypactivecondition 3: Endometrial polyplookup
SNOMED CT129103003Endometriosisactivecondition 4: Endometriosislookup
SNOMED CT128105004von Willebrand disorderactivecondition 5: von Willebrand disorderlookup
SNOMED CT64779008Blood coagulation disorderactivecondition 6: Blood coagulation disorderlookup
SNOMED CT87522002Iron deficiency anemiaactivecondition 7: Iron deficiency anemia; sample smart-cup-hmblookup
SNOMED CT40930008Hypothyroidismactivecondition 8: Hypothyroidismlookup
SNOMED CT34486009Hyperthyroidismactivecondition 9: Hyperthyroidismlookup
SNOMED CT237662005Hyperprolactinemiaactivecondition 10: Hyperprolactinemialookup
SNOMED CT237788002Premature ovarian insufficiencyactivecondition 11: Premature ovarian insufficiencylookup
SNOMED CT237120002Hypothalamic amenorrheaactivecondition 12: Hypothalamic amenorrhealookup
SNOMED CT161541000119104Perimenopausal stateactivecondition 13: Perimenopausal state; sample perimenopauselookup
SNOMED CT76498008Postmenopausal stateactivecondition 14: Postmenopausal statelookup
LOINC64700-8On average, during the last year, how many day were there in a typical menstrual cycle, that is, from the beginning of bleeding of one menstrual period to the beginning of bleeding of the next period [PhenX]activequestion: usual-cycle-length; sample pcos; sample calendar-only; sample smart-cup-hmblookup
LOINCLA14649-0Less than 21 daysactiveanswer to usual-cycle-length: <21lookup
LOINCLA14650-821-25 daysactiveanswer to usual-cycle-length: 21-25lookup
LOINCLA14651-626-32 daysactiveanswer to usual-cycle-length: 26-32; sample calendar-only; sample smart-cup-hmblookup
LOINCLA14652-433-35 daysactiveanswer to usual-cycle-length: 33-35lookup
LOINCLA14653-236-90 daysactiveanswer to usual-cycle-length: 36-90; sample pcoslookup
LOINCLA14654-0More than 90 daysactiveanswer to usual-cycle-length: >90lookup
LOINCLA14655-7Too variable to sayactiveanswer to usual-cycle-length: too-variablelookup
LOINCLA12688-0Don't knowactiveanswer to usual-cycle-length: dont-knowlookup
LOINC92656-8Number of menstrual periods per yearactivequestion: periods-per-year; sample pcos; sample calendar-only; sample smart-cup-hmb; sample post-ablationlookup
UCUM/a/avalidunit of periods-per-year; sample pcos; sample calendar-only; sample smart-cup-hmb; sample post-ablationlookup
LOINC65930-0Over the past 3 months, how many menstrual periods have you missed [EDDS]activequestion: missed-periods-3-monthslookup
UCUM{#}/(3.mo){#}/(3.mo)validunit of missed-periods-3-monthslookup
LOINC63889-0Have you had a menstrual period within the last year [PhenX]activequestion: period-in-last-year; sample post-ablationlookup
LOINCLA33-6Yesactiveanswer to period-in-last-year: yeslookup
LOINCLA32-8Noactiveanswer to period-in-last-year: no; answer to periods-stopped: no; sample post-ablationlookup
LOINC64701-6Have your menstrual periods stopped permanently [PhenX]activequestion: periods-stoppedlookup
LOINCLA14656-5Yes, no menstrual periodsactiveanswer to periods-stopped: yes-no-periodslookup
LOINCLA14657-3Yes, but have periods now due to female hormonesactiveanswer to periods-stopped: yes-hormoneslookup
LOINCLA12693-0Not sureactiveanswer to periods-stopped: not-surelookup
LOINC64702-4How old were you when your periods stopped [PhenX]activequestion: age-periods-stoppedlookup
UCUMaavalidunit of age-periods-stopped; unit of age-at-menarchelookup
LOINC63888-2Age at first menstrual periodactivequestion: age-at-menarchelookup
condition-clinicalactiveActiveactiveCondition.clinicalStatus; sample pcos; sample perimenopause; sample smart-cup-hmblookup
condition-clinicalresolvedResolvedactiveCondition.clinicalStatus; sample post-ablationlookup
UCUMmLmLvalidvolume unit; sample smart-cup-hmblookup
UCUM{score}{score}validbuilt-in Quantity unit; sample power-tracker; sample copper-iud; sample pcos; sample perimenopause; sample combined-pill; sample wellness-diary; sample smart-cup-hmblookup
UCUMCelCelvalidbuilt-in Quantity unit; sample power-tracker; sample copper-iud; sample own-vocabulary; sample wearable; sample post-ablationlookup
UCUM[degF][degF]validbuilt-in Quantity unit; sample pcoslookup
UCUMminminvalidbuilt-in Quantity unit; sample power-tracker; sample perimenopause; sample own-vocabulary; sample wellness-diary; sample wearablelookup
SNOMED CT34363003Pruritus of vaginaactivesample power-trackerlookup
SNOMED CT399939002Hirsutismactivesample pcoslookup
SNOMED CT109081006Metformin-containing productactivesample pcoslookup
SNOMED CT57676002Pain of jointactivesample perimenopauselookup
LOINCLA27913-5Diaphragm or cervical capactivesample own-vocabularylookup
SNOMED CT68962001Muscle painactivesample own-vocabularylookup
SNOMED CT255604002Mildactivesample own-vocabulary; test fixture escapelookup
RxNorm197805ibuprofen 400 MG Oral Tabletactivesample own-vocabularylookup
SNOMED CT24484000Severeactivesample own-vocabulary; test fixture escapelookup
SNOMED CT6736007Moderate severityactivesample own-vocabulary; test fixture escapelookup
RxNorm849574naproxen sodium 220 MG Oral Tabletactivesample own-vocabularylookup
SNOMED CT422400008Vomitingactivesample own-vocabularylookup
RxNorm198741magnesium oxide 400 MG Oral Tabletactivesample wellness-diarylookup
LOINC41950-7Number of steps in 24 hour Measuredactivesample wellness-diarylookup
UCUM/d/dvalidsample wellness-diarylookup
UCUMmgmgvalidsample wellness-diarylookup
UCUM/min/minvalidsample wellness-diarylookup
RxNorm313161sumatriptan 50 MG Oral Tabletactivesample wellness-diarylookup
RxNorm1368932riboflavin 400 MG Oral Tabletactivesample wellness-diarylookup
SNOMED CT143661000119109Non-menopausal hot flashactivetest fixture escapelookup
SNOMED CT703737005Ulipristal-containing productactivetest fixture escapelookup
ATCG03AAProgestogens and estrogens, fixed combinationsactiveconsidered for pill coding (not used)lookup
ATCG03ACProgestogensactiveconsidered for pill coding (not used)lookup
ATCG03ADEmergency contraceptivesactiveconsidered for pill coding (not used)lookup
SNOMED CT315604002Missed contraceptive pillactiveconsidered for missed pill (not used)lookup

Notes on choices:

  • LOINC answers as values.
    • 8659-5's own answer list (LL353-4, "ART_4_Family planning") is too coarse: "Injectable/implantable hormone" and "Intrauterine device" do not separate copper from hormonal IUDs.
    • The values therefore come from LL4578-2. That is the list LOINC attaches to the HL7 Family Planning (FPAR) questions 86649-1 and 86651-7, which are birth control method at intake and at exit.
    • The alternative was the SNOMED CT "Uses … contraception" findings (448962006 copper IUD, 449038007 hormone-releasing IUD, 268458002 combined oral, 445375000 does not use contraception, and others). They are exact as well. The LOINC answers were chosen because a question/answer pair under one LOINC code is the pattern FPAR uses.
  • Contraceptive pills are not medications. LOINC answer-list values (LA27908-5 and the others) are answers to the "birth control method" question. They appear only as values of the 8659-5 interval Observation, never as a medication code.
    • The daily pill log is a separate boolean series (§1).
    • Also considered for a pill medication code: the ATC classes G03AA "Progestogens and estrogens, fixed combinations", G03AC "Progestogens" and G03AD "Emergency contraceptives". All verified active on tx.fhir.org ($lookup?system=http://www.whocc.no/atc&code=G03AA, ATC 2026), but they are class-level and say nothing about a specific pill.
    • SNOMED CT International has only ingredient-specific products, for example 779205005 "Ethinyl estradiol and levonorgestrel only product in oral dose form". An app that knows the product can still log it as a medication escape.
  • Emergency contraception is a procedure-history Observation with SNOMED CT 1372819003 (§1). A known product (703737005 ulipristal, or a levonorgestrel product) may additionally be logged as a medication escape.
  • Medication codes are SNOMED CT products only, from the built-in table or escapes. They are emitted as MedicationStatement medicationCodeableConcept, with status completed (taken) or not-taken (§1).
  • Pregnancy test. 2106-3 "Choriogonadotropin [Presence] in Urine" describes exactly what a home test measures. The values are the SNOMED CT qualifiers Negative, Positive and Indeterminate, as used for presence tests.
  • Sexual activity. 364316005 is an observable entity, used as Observation.code. Its findings are the values: 63537005 protected, 2314005 unprotected, and 70256003, their common parent, when protection is not recorded.
  • Sleep. 93832-4 "Sleep duration" is unqualified (main sleep vs total). The model attributes it to the wake day.

5.3 Proposed codes (https://joshuamandel.com/shc2-poc/CodeSystem/cycle-log, CodeSystem-cycle-log.json)

The URL is the constant CYCLE_LOG_CS in vocab.ts. The CodeSystem is experimental: true with content: complete, and make-codesystem.ts writes it.

CodeUseWhy no standard code fits (searched on tx.fhir.org: ValueSet/$expand?url=http://loinc.org/vs and …?url=http://snomed.info/sct?fhir_vs with filter=)
menstrual-bleeding, menstrual-flow, symptom, flow-none, flow-spotting, flow-light, flow-moderate, flow-heavythe bleeding fact (valueBoolean), the flow fact and its five values, and the code of a symptom fact (value: the symptom)The design started from these fact types; they are defined here, with definitions, so the card depends on no other code system. Mapping them to LOINC or SNOMED CT is future work.
basal-body-temperaturewaking basal body temperature (bbt)Keeps waking BBT distinct from LOINC 8310-5 "Body temperature" (fever / clinical vital signs), which stays available as an R4 vital-sign custom series without polluting thermal-shift baselines.
reading-excluded, reading-exclusion-reason, exclude-fever, exclude-alcohol, exclude-poor-sleep, exclude-late-wake, exclude-travel, exclude-stress, exclude-medication, exclude-otheroptional disturbance/exclusion components on bbt and skinTempNo standard LOINC or SNOMED CT observation component codes distinguish a disturbed fertility-tracking temperature reading excluded from thermal-shift interpretation and its coded reason.
cervical-mucus + mucus-dry/-sticky/-creamy/-watery/-egg-whiteself-observed mucusLOINC 10570-0 "Consistency of Cervical mucus" and 79333-1 "Viscosity … Qualitative" are laboratory specimen properties. Their answer list LL2446-4 (viscous, mildly viscous, slightly viscous, watery, liquified) cannot say "dry" or "egg white". SNOMED CT has vaginal-discharge findings (289553007 creamy, 289549005 watery) but no fertility-awareness mucus categories. Those would be close but wrong.
ovulation-test (+ value estrogen-surge)home LH testLOINC has only quantitative lutropin in urine (15079-7 [Units/volume], 111244-0 [Measurement]). "Lutropin [Presence] in Urine" does not exist. The negative, positive and indeterminate values are SNOMED CT. Only the HealthKit estrogenSurge result ("high fertility" on combined monitors) needed a proposed value.
pdg-testhome progesterone (PdG) testLOINC has only quantitative pregnanediol (2833-2, 110593-1, 15091-2), with no presence test for pregnanediol glucuronide.
no-sexual-intercourseexplicit "didn't have sex"Searches found only 102956007 "Non-consummation of sexual intercourse" (a marital/diagnostic concept), 162171002 "Currently not sexually active" (a status, not a day) and the LOINC PhenX survey answer LA14635-9. None means "no intercourse on this day".
mood-valence + 7 valence-*daily moodLOINC has instrument-specific mood items (MDQ, MFQ, CMS assessments). Nothing is a generic daily valence rating. HealthKit's 7-point valence is the model's source.
energy-level + 4 energy-*daily energyLOINC 65515-9 (QIDS, past 7 days) and 69731-8 (PHQ, past 4 weeks) are instrument items with other time frames and answer lists.
contraceptive-pill-takendaily pill log, valueBooleanSNOMED CT 315604002 "Missed contraceptive pill (situation)" covers only the missed case, and there is no concept for "pill taken". One boolean fact with one code mirrors the menstrual-bleeding fact (§1).
menstrual-fluid-volumemeasured volumeSNOMED CT 364308001 "Quantity of menstrual blood loss" is blood; collected menstrual fluid is 36% blood on average (Fraser 1985, PMID 3969232), about 50% in heavy losses (Fraser 2001, PMID 11704173). No LOINC concept for menstrual volume.
skin-temperature-deviation, nightly-skin-temperaturewearable nightly temperatureLOINC 39106-0 "Temperature of Skin" is nominal (palpation), and the validator warns on a quantity. There is no LOINC or SNOMED CT quantity concept for a sleep-aggregated skin temperature or its deviation from a personal baseline. The LOINC body-temperature codes would bind R4 vital-signs profiles.
hot-flashsymptom (built-in 25)SNOMED CT International has only cause-specific concepts. 198436008 "Menopausal flushing" and 427368007 "Climacteric flushing" assert a menopausal cause. 143661000119109 "Non-menopausal hot flash" asserts the opposite, and 439407002 is drug-caused. The parent 238810007 "Flushing" is a skin sign without the heat sensation. A tracker does not know the cause. A producer that does can send 198436008 as an escape.

6. Validation

6.1 HL7 FHIR validator

The HL7 IG Publisher jar contains org.hl7.fhir.validation.ValidationEngine. hl7-validate/Validate.java (about 40 lines, run with java -cp publisher.jar Validate.java) drives it, with the R4 core package from the local cache and terminology from https://tx.fhir.org. bun hl7-validate/run.ts validates every sample:

passloadedresult, all sixteen samples
baseR4 core (with the R4 vital-signs profiles the validator applies by LOINC code), CodeSystem-cycle-log.json (as a receiver that knows it)0 errors (2026-12-03, all sixteen, including timestamped and bp-twice-daily with several entries a day, times and offsets)
projectonly with PROJECT_PROFILES set: the project's own profiles, generated from the model, with meta.profile added from their profile-map.json– (the hook for those profiles)

Warnings, all expected:

  • dom-6: no narrative.
    • This is the only issue the validator raises on the Patient (both forms), the Device, the MedicationStatements, the Procedures and the Conditions, apart from one information note on the PCOS Condition (laterality).
    • It raised no best-practice warning about a missing performer, subject or informationSource on those resource types.
  • "all observations should have a performer". This applies to Observations only.
  • {score}: UCUM annotation advice. LOINC 72514-3 is a 0–10 score.
  • "A definition for CodeSystem … could not be found": the app code systems of samples (h) and (i).

Information-level notes:

  • the validator applied R4 bodytemp to 8310-5, and heartrate, bp and bodyweight to the vital-sign series;
  • point-in-time LOINC codes (8659-5, 82810-3, 63895-7) used with a period;
  • LOINC 41950-7 (steps, a 24-hour collection) used with a single date.

Other runs:

  • A limits-maximal random model (every built-in and context field populated, 32 custom series, 64 concepts per day, 255-character urn: systems, 128-character codes and 128-character displays containing ", \, |, non-ASCII and an emoji, quantities ±2³¹−1 at scale 6): 0 errors.
  • Negative controls produced the expected errors:
    • an invented SNOMED CT code (unknown code);
    • an invented LOINC answer;

Validity findings that shaped the model. Each was found by running the validator:

  1. The empty Patient {"resourceType":"Patient"} fails bdl-5.
    • Without identity the Patient is {"resourceType":"Patient","id":"0"}. {"resourceType":"Patient","active":true} also validates, but asserts more.
    • With identity it is name and/or birthDate (§1).
  2. BBT without a subject fails R4 bodytemp, and R4 MedicationStatement.subject and Procedure.subject are 1..1. The Patient therefore always exists, and every fact references it as resource:0.
  3. The validator applies R4 vital-signs profiles to about 90 LOINC codes, not just the 13 in the R4 ValueSet. For example, 40443-4 "Heart rate --resting" triggers the heart-rate profile. A custom series with any of these codes is therefore written as a vital sign, with the category and, for a code with its own profile, the profile's unit or components (§2); intervals may not use them (R4_VITAL_SIGN_CODES, taken from the validator's own BasePolicyAdvisorForFullValidation).
  4. Code systems under example.org (and example.com) are an error: "Example URLs are not allowed in this context". The samples' fictitious app systems therefore use the reserved .invalid TLD.
    • The proposed concepts are therefore at https://joshuamandel.com/shc2-poc/CodeSystem/cycle-log, where the CodeSystem JSON is served.
    • Validated without CodeSystem-cycle-log.json loaded (a receiver that has never seen it), the combined-pill sample gives 0 errors and 541 warnings "A definition for CodeSystem 'https://joshuamandel.com/shc2-poc/CodeSystem/cycle-log' could not be found, so the code cannot be validated". The near-empty sample gives 0 errors and 1 such warning.
    • With the CodeSystem loaded, all sixteen samples give 0 errors.
  5. A Coding.display on a SNOMED CT, LOINC or RxNorm concept that does not match an official display is a "Wrong Display Name" error. Built-in concepts therefore omit custom displays and text (their displays are canonical); non-built-in escape concepts may carry coding[0].display (which must be an official display for standard terminologies) and/or plain-text CodeableConcept.text for offline readability (demonstrated in offline-displays).

6.2 Offline structural checker

r4-structure.ts checks every Bundle against the R4 StructureDefinitions in specs/fhiredaction-studio/fhir/.cache/profiles-{resources,types}.json. It runs in the test suite, where all samples and 30 random models pass.

It establishes:

  • every property is an R4 element of its resource or data type (choice types resolved);
  • arrays versus single values match max cardinality;
  • required elements are present;
  • primitives match the R4 regexes;
  • there are no empty objects, arrays or strings.

It does not establish anything about:

  • invariants (it misses bdl-5);
  • bindings or terminology;
  • profiles, patterns or fixed values;
  • references.

§6.1 covers those.