Skip to content

FHIR IG generation (dhis2w_fhir)

dhis2w_fhir is the package behind d2w fhir: the fhir.toml document, the emitters that turn DHIS2 metadata into an Implementation Guide - FSH for the definitional artifacts, pre-built R4 JSON for the organisation-unit registry, the option-set terminology, and the category terminology - and the DHIS2 period grammar they share. It mounts onto the CLI through the dhis2w.plugins.v1 entry point, and every component symbol re-exports from the top-level package, so from dhis2w_fhir import GenerateConfig keeps working however the components are arranged internally. What a service is built from - the R4 models, periods, the spool - lives in dhis2w_fhir_engine.

When to reach for it

  • Read or write a project's fhir.toml from Python (load_project, load_fhir_config, find_project_fhir_config, write_fhir_config).
  • Parse a DHIS2 ISO period into its type and date range, or walk backwards from a date (parse_period, recent_periods, PERIOD_TYPE_DEFINITIONS).
  • Carry DHIS2 attribute values onto a generated resource (AttributeValueIn, AttributeCodeIndex, resolve_attribute_code_index, attribute_value_extensions).
  • Build FSH artifacts without the CLI (build_foundation_artifacts, build_questionnaire_artifacts, build_page_artifacts) and sync them to disk (sync_artifacts).
  • Build the pre-built R4 documents - the registry (dhis2w_fhir_engine.r4.resources.Organization, dhis2w_fhir_engine.r4.resources.Location), the option-set terminology (build_option_set_artifacts), and the category terminology (build_category_artifacts), the last two on dhis2w_fhir_engine.r4.resources.CodeSystem and dhis2w_fhir_engine.r4.resources.ValueSet - and sync them to disk (sync_json_artifacts), one owned directory per source.
  • Map an option set's generated concept codes back to the DHIS2 option UID and option code (build_option_set_concept_maps for the dhis2w_fhir_engine.r4.resources.ConceptMap models, build_option_set_concept_map_artifacts for the JSON files that land in CONCEPT_MAP_DIRECTORY).
  • Generate one target, or the whole guide, without the command (generate_foundation, generate_option_sets, generate_categories, generate_questionnaires, generate_examples, generate_organisation_units, generate_pages, generate_full). Each returns a GenerateReport, and each raises BuildAbortingCodeError or BuildAbortingNameError rather than writing a guide the IG publisher will die on hours later.
  • Scaffold a project, or re-render one that already exists (init_project, refresh_project, read_project_scaffold_state, ProjectScaffoldState).
  • Produce a validation report rather than only rendering one (validate_codes, with resolve_validation_context, resolve_validation_scope, and resolve_code_source for the three things a run has to decide first). build_aborting_code and build_aborting_name are the two predicates the report's error grade and the generate refusal share, so a caller can ask the same question either command asks; display_code renders a DHIS2 code for human eyes the way the report does.
  • Ask the same question of the files a build publishes, with no instance behind it (check_publishable_artifacts, returning an ArtifactCheckReport of ArtifactFindings). It reads a project's compiled resources, pre-built JSON, and FSH sources through those same two predicates, which is what d2w fhir check-artifacts and make build run.
  • Run the conformance chain in process, or grade one phase of it on its own (run_doctor, DoctorOptions, DoctorReport, render_doctor_markdown, phase_evidence, resolve_doctor_profile, and the graders grade, grade_capture, grade_forward, grade_oracle over DoctorFinding, CaptureOutcome, and FamilyOutcome). Read run_doctor's own docstring first: it writes a workspace, shells out to a compiler, and posts a corpus, which the graders do not.
  • Assemble one person's International Patient Summary out of a projected subject and the doses somebody already read (build_patient_summary, AssembledSummary, RecordedDose, summary_caveat, REQUIRED_SECTIONS, IpsSection), and publish the section mapping behind it as a ConceptMap (build_section_concept_map, build_section_concept_map_artifacts). The assembly opens no connection and reads no store, so a command is as free to call it as a served facade is.
  • Record why a spooled response was refused, and read the record back (record_refusal, read_refusal_record, ForwardRefusalRecord, RefusalReason, SPOOL_RELATIVE_PATH). ForwardRefusalRecord is the declared type of SpooledReceipt.refusal, so a caller reading receipts holds instances of it either way.
  • Talk to a running facade from Python without composing a request (FacadeClient, with submit_response answering a CaptureReceipt, generate, read_response, read, search over a ResourceQuery, resolve for a canonical, capability, and evaluate answering an EvaluationOutcome). Credentials are BearerToken, UsernamePassword, or PersonalAccessToken; a refusal raises FacadeError carrying the OperationOutcome the facade stated its reason in.

Every capability above that reads DHIS2 takes the connection as an argument: client= on validate_codes, run_doctor, and each generate target, with the Profile form kept as the convenience wrapper the commands use. A handed-in client is used as it stands and left open, so an application already holding an authenticated connection makes one connection rather than one per call.

Worked example — parse a period, then walk backwards

import datetime

from dhis2w_fhir_engine.facade.period.parser import parse_period
from dhis2w_fhir_engine.facade.period.recent import recent_periods

parse_period("2024BiW2")
# PeriodValue(iso='2024BiW2', period_type='BiWeekly',
#             start_date=date(2024, 1, 15), end_date=date(2024, 1, 28))

recent_periods("Monthly", 3, datetime.date(2026, 8, 2))
# ['202607', '202606', '202605']

Reference

The conformance runner

What d2w fhir doctor concluded about one instance, as models rather than as terminal output. A DoctorReport carries one DoctorPhaseResult per phase - the outcome, the one line it is read by, the reason a phase that did not run gives, and every DoctorFinding it raised with the field path a mismatch was found at. The graders are the pure half of the runner: grade_forward, grade_capture, grade_oracle, and grade_drift turn a phase's own report into the verdict it is recorded under, over ForwardReport, CaptureOutcome, FamilyOutcome, and DriftReport, and render_doctor_markdown turns the whole run into the report file a handover is read from.

run_doctor is the other half, and what it does to the machine is part of its contract: it mints a workspace directory (or writes into the one DoctorOptions.workspace names) and removes a minted one unless keep is set, runs sushi or docker run where a compiler is on the machine, writes compiled resources under ig/fsh-generated/resources, runs an ASGI application in process, and posts a synthetic corpus at the instance under validate-only mode. A caller that cannot afford that wants the graders rather than the run.

doctor

The instance conformance runner behind d2w fhir doctor: run the whole toolchain, report what breaks.

Doctor scaffolds a throwaway project against the ambient DHIS2 profile, generates the IG source from that instance, compiles it when a compiler is on the machine, serves it in process, captures a synthetic corpus through the served endpoint, drains that corpus at the instance under validate-only mode, lets the instance judge the served resources object by object, and closes by asking whether the guide already on disk still describes the instance it was generated from. Every phase reports one typed result, and a failure never stops a phase that does not depend on it.

The direction of judgement is the whole point of the oracle phase: the DHIS2 instance is the authority and the served output is what is on trial, never the reverse. A mismatch is a fact about this toolchain against this instance, stated with the field path it was found on.

No MCP tool, the way d2w profile has none. A run writes a project tree, shells out to a compiler, posts a corpus through an in-process server, and reads a whole instance - a write-heavy orchestration with no read-only shape an MCP tool could honestly advertise.

run_doctor is a library call all the same, and what it does to the machine is part of its contract rather than a surprise: it mints a workspace directory (or writes into the one DoctorOptions.workspace names) and removes a minted one unless keep is set, runs sushi or docker run when a compiler is on the machine, writes compiled resources under ig/fsh-generated/resources, runs an ASGI application in process, and posts a synthetic corpus at the instance under validate-only mode. A caller that cannot afford any of that wants the phases it grades rather than the run: grade, grade_capture, grade_forward, grade_oracle, and grade_drift are pure over DoctorFinding, CaptureOutcome, FamilyOutcome, ForwardReport, and DriftReport.

The drift phase is the one phase whose subject is not the throwaway project. It reads the published guide the working directory sits in, so resolve_published_project runs before anything is written and returns nothing for a working directory inside the workspace: a project this run generated seconds ago can only agree with the instance, and a phase that always passes says nothing.

That same published project is where the run takes its [generate] posture from. The scaffold picks a representative selection of its own, and then generates it under the calling project's answers - its hostile-name posture, its identity source, its concept code source - so every phase answers whether the toolchain runs against this instance as this project is configured to run it.

Classes

DoctorPhase

Bases: StrEnum

The phases of one doctor run, in the order they execute.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
class DoctorPhase(StrEnum):
    """The phases of one doctor run, in the order they execute."""

    CONNECT = "connect"
    SCAFFOLD = "scaffold"
    GENERATE = "generate"
    COMPILE = "compile"
    VALIDATE = "validate"
    SERVE = "serve"
    CAPTURE = "capture"
    FORWARD = "forward"
    ORACLE = "oracle"
    DRIFT = "drift"

DoctorOutcome

Bases: StrEnum

What one phase concluded, which is what the verdict and the exit code are read off.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
class DoctorOutcome(StrEnum):
    """What one phase concluded, which is what the verdict and the exit code are read off."""

    #: The phase ran and found nothing worth acting on.
    PASSED = "pass"

    #: The phase ran and found something that degrades the result without breaking it.
    WARNED = "warn"

    #: The phase ran and found something broken. A run holding one of these exits 1.
    FAILED = "fail"

    #: The phase did not run because this machine or this invocation does not offer what it needs.
    SKIPPED = "skipped"

    #: The phase did not run because an earlier phase it is built on did not produce its input.
    BLOCKED = "blocked"

DoctorFinding

Bases: BaseModel

One thing a phase found: what object, what is wrong with it, and where on it.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
class DoctorFinding(BaseModel):
    """One thing a phase found: what object, what is wrong with it, and where on it."""

    model_config = ConfigDict(frozen=True)

    phase: DoctorPhase
    severity: Literal["error", "warning"]
    subject: str
    detail: str
    field_path: str | None = None
    """The path on the served resource a mismatch was found at, for the findings that have one."""
Attributes
field_path = None class-attribute instance-attribute

The path on the served resource a mismatch was found at, for the findings that have one.

DoctorPhaseResult

Bases: BaseModel

The outcome of one phase: the verdict, the one line it is read by, and what it found.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
class DoctorPhaseResult(BaseModel):
    """The outcome of one phase: the verdict, the one line it is read by, and what it found."""

    model_config = ConfigDict(frozen=True)

    phase: DoctorPhase
    outcome: DoctorOutcome
    evidence: str
    reason: str | None = None
    """Why a phase did not run, stated on every SKIPPED and BLOCKED result."""

    findings: tuple[DoctorFinding, ...] = ()
    elapsed_seconds: float = 0.0

    @property
    def error_count(self) -> int:
        """How many of this phase's findings are broken rather than merely degraded."""
        return sum(1 for finding in self.findings if finding.severity == "error")
Attributes
reason = None class-attribute instance-attribute

Why a phase did not run, stated on every SKIPPED and BLOCKED result.

error_count property

How many of this phase's findings are broken rather than merely degraded.

DoctorOptions

Bases: BaseModel

The dials one doctor run is invoked with.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
class DoctorOptions(BaseModel):
    """The dials one doctor run is invoked with."""

    model_config = ConfigDict(frozen=True)

    workspace: Path | None = None
    """Where the throwaway project is written. None mints a temporary directory."""

    keep: bool = False
    """Keep a minted temporary workspace instead of removing it when the run ends."""

    all_targets: bool = False
    """Scaffold empty selection tables, which selects every data set and every program."""

    live: bool = False
    """Run the oracle phase, where the instance judges the served resources object by object."""

    samples: int = DEFAULT_ORACLE_SAMPLES
    """How many resources per family the oracle deep-compares against the instance."""
Attributes
workspace = None class-attribute instance-attribute

Where the throwaway project is written. None mints a temporary directory.

keep = False class-attribute instance-attribute

Keep a minted temporary workspace instead of removing it when the run ends.

all_targets = False class-attribute instance-attribute

Scaffold empty selection tables, which selects every data set and every program.

live = False class-attribute instance-attribute

Run the oracle phase, where the instance judges the served resources object by object.

samples = DEFAULT_ORACLE_SAMPLES class-attribute instance-attribute

How many resources per family the oracle deep-compares against the instance.

DoctorReport

Bases: BaseModel

Everything one doctor run concluded: what it ran against, where it ran, and what each phase found.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
class DoctorReport(BaseModel):
    """Everything one doctor run concluded: what it ran against, where it ran, and what each phase found."""

    model_config = ConfigDict(frozen=True)

    profile_name: str
    profile_origin: str
    base_url: str
    dhis2_version: str | None = None
    version_tree: str | None = None
    """The `v41` / `v42` / `v43` / `v44` plugin tree the client bound after detecting the instance's version."""

    workspace: Path
    workspace_kept: bool
    generated_at: datetime
    options: DoctorOptions
    phases: tuple[DoctorPhaseResult, ...] = ()

    @property
    def failed_phases(self) -> tuple[DoctorPhaseResult, ...]:
        """Every phase that concluded the toolchain is broken against this instance."""
        return tuple(phase for phase in self.phases if phase.outcome is DoctorOutcome.FAILED)

    @property
    def findings(self) -> tuple[DoctorFinding, ...]:
        """Every finding of the run, in phase order."""
        return tuple(finding for phase in self.phases for finding in phase.findings)

    @property
    def counts_by_outcome(self) -> dict[str, int]:
        """How many phases reached each outcome - the shape the verdict line is written from."""
        counted = Counter(phase.outcome.value for phase in self.phases)
        return {outcome.value: counted.get(outcome.value, 0) for outcome in DoctorOutcome}

    @property
    def verdict_line(self) -> str:
        """The whole run in one line: the verdict word, then how many phases reached each outcome."""
        counts = self.counts_by_outcome
        tail = ", ".join(f"{counts[outcome.value]} {outcome.value}" for outcome in DoctorOutcome)
        verdict = "BROKEN" if self.failed_phases else "USABLE"
        return f"{verdict}: {tail}"
Attributes
version_tree = None class-attribute instance-attribute

The v41 / v42 / v43 / v44 plugin tree the client bound after detecting the instance's version.

failed_phases property

Every phase that concluded the toolchain is broken against this instance.

findings property

Every finding of the run, in phase order.

counts_by_outcome property

How many phases reached each outcome - the shape the verdict line is written from.

verdict_line property

The whole run in one line: the verdict word, then how many phases reached each outcome.

PhaseOutcome

Bases: BaseModel

One phase's verdict before it is recorded: what it concluded, the line it says so on, its findings.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
class PhaseOutcome(BaseModel):
    """One phase's verdict before it is recorded: what it concluded, the line it says so on, its findings."""

    model_config = ConfigDict(frozen=True)

    outcome: DoctorOutcome
    evidence: str
    findings: tuple[DoctorFinding, ...] = ()

CaptureOutcome

Bases: BaseModel

What one form contributed to the capture phase: whether it generated, whether it was accepted, and why not.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
class CaptureOutcome(BaseModel):
    """What one form contributed to the capture phase: whether it generated, whether it was accepted, and why not."""

    model_config = ConfigDict(frozen=True)

    generated: bool
    accepted: bool
    findings: tuple[DoctorFinding, ...] = ()

FamilyOutcome

Bases: BaseModel

What one oracle family concluded: the line it is summarised by, and every mismatch it found.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
class FamilyOutcome(BaseModel):
    """What one oracle family concluded: the line it is summarised by, and every mismatch it found."""

    model_config = ConfigDict(frozen=True)

    summary: str
    findings: tuple[DoctorFinding, ...] = ()

Functions:

grade(phase, evidence, findings)

Grade one phase off what it found: an error breaks it, a warning degrades it, nothing passes it.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
def grade(phase: DoctorPhase, evidence: str, findings: Sequence[DoctorFinding]) -> PhaseOutcome:
    """Grade one phase off what it found: an error breaks it, a warning degrades it, nothing passes it."""
    if any(finding.severity == "error" for finding in findings):
        outcome = DoctorOutcome.FAILED
    elif findings:
        outcome = DoctorOutcome.WARNED
    else:
        outcome = DoctorOutcome.PASSED
    return PhaseOutcome(outcome=outcome, evidence=evidence, findings=_capped_findings(phase, findings))

generate_findings(notes)

Every note one generate run raised, as the findings the generate phase reports.

A note is a decision the emitters took against this instance's metadata - a form reshaped, a code fallen back to a UID, several tracked entity types left to the default resource - so the phase reports all of them and none of them breaks the run. The projection lives here rather than inline so a note's wording is what a test of the finding reads.

One note is one finding, however many targets raised it. Several targets read the same source notes - a form-structure note reaches the questionnaires, the examples, and the pages alike - and a table stating one fact about the instance three times says nothing the first row did not, while pushing other findings behind the cap that keeps it readable. GenerateNote is frozen, so this dedupes by value and keeps the order the targets raised them in.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
def generate_findings(notes: Sequence[GenerateNote]) -> list[DoctorFinding]:
    """Every note one generate run raised, as the findings the generate phase reports.

    A note is a decision the emitters took against this instance's metadata - a form reshaped, a
    code fallen back to a UID, several tracked entity types left to the default resource - so the
    phase reports all of them and none of them breaks the run. The projection lives here rather
    than inline so a note's wording is what a test of the finding reads.

    One note is one finding, however many targets raised it. Several targets read the same source
    notes - a form-structure note reaches the questionnaires, the examples, and the pages alike -
    and a table stating one fact about the instance three times says nothing the first row did not,
    while pushing other findings behind the cap that keeps it readable. `GenerateNote` is frozen,
    so this dedupes by value and keeps the order the targets raised them in.
    """
    return [
        DoctorFinding(
            phase=DoctorPhase.GENERATE,
            severity="warning",
            subject=note.category.value,
            detail=note.message,
        )
        for note in dict.fromkeys(notes)
    ]

grade_capture(captured)

Grade the capture phase: an endpoint refusing what it generated is broken, a form it cannot fill is not.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
def grade_capture(captured: Sequence[CaptureOutcome]) -> PhaseOutcome:
    """Grade the capture phase: an endpoint refusing what it generated is broken, a form it cannot fill is not."""
    findings = [finding for outcome in captured for finding in outcome.findings]
    generated = sum(1 for outcome in captured if outcome.generated)
    accepted = sum(1 for outcome in captured if outcome.accepted)
    evidence = f"{len(captured):,} form(s), {generated:,} generated, {accepted:,} accepted"
    return grade(DoctorPhase.CAPTURE, evidence, findings)

grade_forward(report)

Grade the forward phase: a DHIS2 rejection is broken, a translator refusal is a note.

Rejections roll up by cause rather than by response, because DHIS2 names one row per broken rule and two hundred responses breaking the same rule are one thing to fix. What a dry run could not check is left out of the findings entirely: an event whose enrollment this very run would have created is unverifiable rather than refused, and an import is what settles it.

A drain that stopped early is an error of its own. It says the instance stopped answering part-way through, which is a fact about the instance this run is judging rather than about any payload, and a phase that passed on the strength of the half it managed would be reporting the quiet failure as a clean bill.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
def grade_forward(report: ForwardReport) -> PhaseOutcome:
    """Grade the forward phase: a DHIS2 rejection is broken, a translator refusal is a note.

    Rejections roll up by cause rather than by response, because DHIS2 names one row per broken rule
    and two hundred responses breaking the same rule are one thing to fix. What a dry run could not
    check is left out of the findings entirely: an event whose enrollment this very run would have
    created is unverifiable rather than refused, and an import is what settles it.

    A drain that stopped early is an error of its own. It says the instance stopped answering
    part-way through, which is a fact about the instance this run is judging rather than about any
    payload, and a phase that passed on the strength of the half it managed would be reporting the
    quiet failure as a clean bill.
    """
    findings = [
        DoctorFinding(
            phase=DoctorPhase.FORWARD,
            severity="error",
            subject=reason.error_code or "no DHIS2 error code",
            detail=f"{reason.responses} response(s): {reason.reason}",
        )
        for reason in report.rejection_reasons
    ]
    if report.stopped is not None:
        findings.append(
            DoctorFinding(
                phase=DoctorPhase.FORWARD,
                severity="error",
                subject=report.stopped.response_id,
                detail=(
                    f"the drain stopped here and left {len(report.not_posted)} response(s) unposted: "
                    f"{report.stopped.reason}"
                ),
            )
        )
    findings.extend(
        DoctorFinding(
            phase=DoctorPhase.FORWARD,
            severity="warning",
            subject=outcome.response_id,
            detail="; ".join(f"{refusal.category}: {refusal.reason}" for refusal in outcome.refusals)
            or "the translator would not read this response whole",
        )
        for outcome in report.refused
    )
    return grade(DoctorPhase.FORWARD, report.counts_line, findings)

grade_oracle(families)

Grade the oracle phase off what the instance said about each family it judged.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
def grade_oracle(families: Sequence[FamilyOutcome]) -> PhaseOutcome:
    """Grade the oracle phase off what the instance said about each family it judged."""
    findings = [finding for family in families for finding in family.findings]
    return grade(DoctorPhase.ORACLE, "; ".join(family.summary for family in families), findings)

drift_findings(report)

Every object that moved since the guide was published, as the findings the drift phase reports.

Drift is warning-class throughout, which is the line doctor already draws: a failure means the toolchain does not work against this instance, and a guide describing the instance as it stood last month still serves, still captures, and still forwards. It is out of date, not broken, and the exit code says so - only a fail exits 1.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
def drift_findings(report: DriftReport) -> list[DoctorFinding]:
    """Every object that moved since the guide was published, as the findings the drift phase reports.

    Drift is warning-class throughout, which is the line doctor already draws: a failure means the
    toolchain does not work against this instance, and a guide describing the instance as it stood
    last month still serves, still captures, and still forwards. It is out of date, not broken, and
    the exit code says so - only a `fail` exits 1.
    """
    return [
        DoctorFinding(
            phase=DoctorPhase.DRIFT,
            severity="warning",
            subject=finding.title,
            detail=finding.detail,
            field_path=finding.kind.value,
        )
        for finding in report.findings
    ]

grade_drift(report)

Grade the drift phase: a moved object is a note about the guide, never a break in the toolchain.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
def grade_drift(report: DriftReport) -> PhaseOutcome:
    """Grade the drift phase: a moved object is a note about the guide, never a break in the toolchain."""
    return grade(DoctorPhase.DRIFT, report.evidence, drift_findings(report))

resolve_published_project(workspace)

The published project this run checks for drift: the one the working directory sits in, or none.

Doctor's own workspace is not it. The run scaffolds and generates that project seconds before the drift phase reads it, so it can only ever agree with the instance - and a phase that always passes says nothing. A published guide is one somebody generated and compiled at some point in the past, which is exactly what a fhir.toml found by walking up from the working directory is.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
def resolve_published_project(workspace: Path) -> FhirProject | None:
    """The published project this run checks for drift: the one the working directory sits in, or none.

    Doctor's own workspace is not it. The run scaffolds and generates that project seconds before the
    drift phase reads it, so it can only ever agree with the instance - and a phase that always
    passes says nothing. A published guide is one somebody generated and compiled at some point in
    the past, which is exactly what a `fhir.toml` found by walking up from the working directory is.
    """
    try:
        project = load_project()
    except (NoFhirProjectError, MalformedFhirConfigError, UnknownFhirConfigKeyError):
        return None
    return None if _is_inside(project.project_root, workspace) else project

resolve_doctor_profile(explicit=None)

The instance doctor runs against: --profile, then d2w -p, then DHIS2_PROFILE, then a project.

The same resolution d2w fhir validate uses, and for the same reason: doctor's subject is an instance rather than a project, and it scaffolds the project it works in, so a fhir.toml in the working directory is a source of the profile name and nothing else.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
def resolve_doctor_profile(explicit: str | None = None) -> GenerationProfile:
    """The instance doctor runs against: `--profile`, then `d2w -p`, then `DHIS2_PROFILE`, then a project.

    The same resolution `d2w fhir validate` uses, and for the same reason: doctor's subject is an
    instance rather than a project, and it scaffolds the project it works in, so a `fhir.toml` in
    the working directory is a source of the profile name and nothing else.
    """
    return service.resolve_validation_context(explicit).generation

run_doctor(generation, options, *, reporter=None, client=None) async

Run every phase against the instance the profile names and report what each one concluded.

client is a connection the caller already holds open. Handed one, the connect phase reads the instance version off it and opens nothing, and the client is left open when the run ends - its lifetime belongs to whoever entered it. With none, the profile opens one for the run and closes it on every exit path.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
async def run_doctor(
    generation: GenerationProfile,
    options: DoctorOptions,
    *,
    reporter: ProgressReporter | None = None,
    client: Dhis2Client | None = None,
) -> DoctorReport:
    """Run every phase against the instance the profile names and report what each one concluded.

    `client` is a connection the caller already holds open. Handed one, the connect phase reads the
    instance version off it and opens nothing, and the client is left open when the run ends - its
    lifetime belongs to whoever entered it. With none, the profile opens one for the run and closes
    it on every exit path.
    """
    return await _DoctorRun(generation, options, reporter, client).execute()

render_doctor_markdown(report)

Render one run as the markdown report a handover is read from, phase table first, findings after.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
def render_doctor_markdown(report: DoctorReport) -> str:
    """Render one run as the markdown report a handover is read from, phase table first, findings after."""
    lines = [
        "# fhir doctor report",
        "",
        f"- Profile: {report.profile_name} ({report.profile_origin})",
        f"- Instance: {report.base_url}",
        f"- DHIS2 version: {report.dhis2_version or 'not detected'} (plugin tree {report.version_tree or 'not bound'})",
        f"- Workspace: {report.workspace}{'' if report.workspace_kept else ' (removed when the run ended)'}",
        f"- Ran: {report.generated_at.isoformat(timespec='seconds')}",
        f"- Verdict: {report.verdict_line}",
        "",
        "## Phases",
        "",
        "| Phase | Outcome | Evidence |",
        "| --- | --- | --- |",
    ]
    lines.extend(
        f"| {phase.phase.value} | {phase.outcome.value} | {_markdown_cell(phase_evidence(phase))} |"
        for phase in report.phases
    )
    lines.append("")
    findings = report.findings
    if findings:
        lines.extend(
            [
                "## Findings",
                "",
                "| Phase | Severity | Subject | Where | What |",
                "| --- | --- | --- | --- | --- |",
            ]
        )
        lines.extend(
            f"| {finding.phase.value} | {finding.severity} | {_markdown_cell(finding.subject)} "
            f"| {_markdown_cell(finding.field_path or '')} | {_markdown_cell(finding.detail)} |"
            for finding in findings
        )
        lines.append("")
    else:
        lines.extend(["## Findings", "", "No phase found anything to report against this instance.", ""])
    return "\n".join(lines)

phase_evidence(phase)

The one line a phase is read by: its evidence, with the reason folded in when it did not run.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/doctor.py
def phase_evidence(phase: DoctorPhaseResult) -> str:
    """The one line a phase is read by: its evidence, with the reason folded in when it did not run."""
    if phase.reason is None:
        return phase.evidence
    return f"{phase.evidence} ({phase.reason})" if phase.evidence else phase.reason

Drift between a published guide and the instance

Whether the guide already on disk still describes the instance it was generated from. detect_drift reads the instance for everything one project publishes and names every organisation unit, option, question, and program stage that moved inside that project's own selection scope; read_published_guide is its offline half, projecting the published artifacts onto the objects the comparison is about. The three comparators - compare_organisation_units, compare_option_set, and compare_form - are pure over a PublishedGuide side and an instance side, so a caller can grade a snapshot it holds without opening a connection. Every finding is a DriftFinding naming what moved, which direction it moved in, and what each side says about it.

drift

What the instance holds that the published guide does not: the drift report behind doctor's last phase.

A guide is a photograph. d2w fhir generate reads the instance once, the compiler turns that reading into artifacts, and from then on the artifacts say what the instance said on the day they were written. DHIS2 keeps moving: a chiefdom is split, an option is added to a set, a question is dropped from a stage. Nothing in the published guide knows, and nothing in the toolchain said so until this module.

Drift is measured inside the project's own selection scope and nowhere else. An organisation unit outside [generate.organisation_units] is not drift - the project never asked for it - and neither is a data set the selection tables leave out. The scope is read from the same fhir.toml the publication was generated under, so the question is always "does this guide still describe the part of the instance it claims to describe", never "has the instance changed anywhere".

The five classes

Class Published side Instance side
Organisation units the Location of every unit in the registry the hierarchy under root, to max_level
Options the concepts of a published option-set CodeSystem that option set's options
Tracked entity attributes a tracker or tracked-entity form's questions the program's or type's attributes
Data elements an aggregate, event, or tracker-event form's questions the data set's or stage's elements
Program stages the tracker-event forms a tracker program publishes that program's stages

Each class reports in both directions and on renames alike: something the instance gained, something it lost, and something whose name changed under an identity that did not. A rename matters because the published display is what a reader of the guide sees - D2TEA_CS carries every attribute's name, a CodeSystem concept carries every option's - so a guide naming an object what the instance no longer calls it is wrong in the way documentation is wrong.

Tracked entity types are out of scope. d2w fhir validate already names every type the project never typed, under unmapped-tracked-entity-type, and one fact reported twice in two vocabularies is worse than one report; the drift phase points at that checklist rather than repeating it.

What is compared, and what is deliberately not

Identity is the DHIS2 UID throughout, because that is what survives a rename and what a consumer joins on. Names are compared through flatten_whitespace, and a published name also matches the wording substitute_build_aborting_text produces: a project generated with hostile_names = "substitute" publishes "Fixed, under 1y" for an instance that says "Fixed, <1y", and reporting that as a rename would be reporting the toolchain's own rewrite back at the reader.

Codes are not compared. A code change is a real event, but it is one the identifier slices already carry and one d2w fhir validate grades for FHIR-safety, so the drift report stays about the objects a form asks and the names a reader reads.

A worked example is not compared either, and is not counted. The guide compiles worked instances beside its profiles so a reader of the published pages can see what one looks like, and the exemplar organisation unit among them carries the identifier d2-example, which belongs to no organisation unit in any instance. Grading it would report a removal every run, forever, that nobody can act on. Which instances are examples is the guide's own word - definition.resource[] of the compiled ImplementationGuide, read through dhis2w_fhir_engine.facade.implementation_guide - so this report and the served store hold out exactly the same set.

The remedy is the same sentence for every finding, which is why it is stated once on the phase rather than once per row: regenerate, then compile. That is the documented lifecycle - d2w fhir generate re-reads the instance, make sushi turns the new source into artifacts - and nothing about a drifted object needs a different answer.

Classes

DriftSubject

Bases: StrEnum

The kinds of object this report covers, each spelled as a reader of the guide would say it.

The first five are what the report is about: the objects a guide carries inside its artifacts. The rest name the DHIS2 object one whole artifact was generated from, for the one case where the artifact outlived it - a selected option set or form the instance no longer holds. Naming that object as an option or a data element would be naming the wrong thing.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class DriftSubject(StrEnum):
    """The kinds of object this report covers, each spelled as a reader of the guide would say it.

    The first five are what the report is about: the objects a guide carries inside its artifacts.
    The rest name the DHIS2 object one whole artifact was generated from, for the one case where the
    artifact outlived it - a selected option set or form the instance no longer holds. Naming that
    object as an option or a data element would be naming the wrong thing.
    """

    ORGANISATION_UNIT = "organisation unit"
    OPTION = "option"
    TRACKED_ENTITY_ATTRIBUTE = "tracked entity attribute"
    DATA_ELEMENT = "data element"
    PROGRAM_STAGE = "program stage"

    OPTION_SET = "option set"
    DATA_SET = "data set"
    EVENT_PROGRAM = "event program"
    TRACKER_PROGRAM = "tracker program"
    TRACKER_PROGRAM_STAGE = "tracker program stage"
    TRACKED_ENTITY_TYPE = "tracked entity type"

DriftKind

Bases: StrEnum

Which direction one object drifted in.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class DriftKind(StrEnum):
    """Which direction one object drifted in."""

    #: The instance holds it and the guide publishes nothing for it.
    ADDED = "added"

    #: The guide publishes it and the instance no longer holds it.
    REMOVED = "removed"

    #: Both hold it, under one identity, under two names.
    RENAMED = "renamed"

DriftFinding

Bases: BaseModel

One drifted object: what it is, where the guide carries it, and what each side says about it.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class DriftFinding(BaseModel):
    """One drifted object: what it is, where the guide carries it, and what each side says about it."""

    model_config = ConfigDict(frozen=True)

    subject: DriftSubject
    kind: DriftKind
    uid: str
    holder: str
    """The published artifact the object belongs to, in the words the guide names that artifact by."""

    published_name: str | None = None
    instance_name: str | None = None

    @property
    def name(self) -> str:
        """The one name to call this object by: the instance's when it holds it, the guide's otherwise."""
        return self.instance_name or self.published_name or self.uid

    @property
    def title(self) -> str:
        """The object as a finding names it: what it is, what it is called, and its DHIS2 UID."""
        return f"{self.subject.value} {self.name} ({self.uid})"

    @property
    def detail(self) -> str:
        """What each side says about this object, as the one line the finding is read by."""
        if self.kind is DriftKind.ADDED:
            return f"the instance holds it in {self.holder}; the guide publishes nothing for it"
        if self.kind is DriftKind.REMOVED:
            return f"the guide publishes it under {self.holder}; the instance no longer holds it there"
        return (
            f"the guide publishes the name {self.published_name!r} under {self.holder}; "
            f"the instance now says {self.instance_name!r}"
        )
Attributes
holder instance-attribute

The published artifact the object belongs to, in the words the guide names that artifact by.

name property

The one name to call this object by: the instance's when it holds it, the guide's otherwise.

title property

The object as a finding names it: what it is, what it is called, and its DHIS2 UID.

detail property

What each side says about this object, as the one line the finding is read by.

PublishedObject

Bases: BaseModel

One DHIS2 object as the published guide carries it: the UID it is keyed by, the name it shows.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class PublishedObject(BaseModel):
    """One DHIS2 object as the published guide carries it: the UID it is keyed by, the name it shows."""

    model_config = ConfigDict(frozen=True)

    uid: str
    name: str | None = None

PublishedOptionSet

Bases: BaseModel

One option-set CodeSystem the guide publishes, and the options its concepts stand for.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class PublishedOptionSet(BaseModel):
    """One option-set CodeSystem the guide publishes, and the options its concepts stand for."""

    model_config = ConfigDict(frozen=True)

    uid: str
    title: str | None = None
    options: tuple[PublishedObject, ...] = ()
    """One entry per concept, keyed by the option UID: its `dhis2-id` property, or the concept code that is the UID."""
Attributes
options = () class-attribute instance-attribute

One entry per concept, keyed by the option UID: its dhis2-id property, or the concept code that is the UID.

PublishedForm

Bases: BaseModel

One Questionnaire the guide publishes: which DHIS2 object it is keyed to, and what it asks.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class PublishedForm(BaseModel):
    """One Questionnaire the guide publishes: which DHIS2 object it is keyed to, and what it asks."""

    model_config = ConfigDict(frozen=True)

    resource_id: str
    kind: FormKind
    """The DHIS2 form kind off the form's own `code`: aggregate, event, tracker, tracker-event, tracked-entity."""

    uid: str
    title: str | None = None
    questions: tuple[PublishedObject, ...] = ()

    @property
    def asks_attributes(self) -> bool:
        """Whether this form's questions are tracked entity attributes rather than data elements."""
        return self.kind in _ATTRIBUTE_FORM_KINDS

    @property
    def holder(self) -> str:
        """How a finding names the form the drifted question belongs to."""
        return f"the published form {self.title or self.resource_id} ({self.uid})"
Attributes
kind instance-attribute

The DHIS2 form kind off the form's own code: aggregate, event, tracker, tracker-event, tracked-entity.

asks_attributes property

Whether this form's questions are tracked entity attributes rather than data elements.

holder property

How a finding names the form the drifted question belongs to.

PublishedGuide

Bases: BaseModel

Everything on disk this report reads: the registry, the published option sets, the published forms.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class PublishedGuide(BaseModel):
    """Everything on disk this report reads: the registry, the published option sets, the published forms."""

    model_config = ConfigDict(frozen=True)

    organisation_units: tuple[PublishedObject, ...] = ()
    option_sets: tuple[PublishedOptionSet, ...] = ()
    forms: tuple[PublishedForm, ...] = ()

    @property
    def program_stage_uids(self) -> frozenset[str]:
        """Every program stage the guide publishes a form for, which is what a new stage is missing from."""
        return frozenset(form.uid for form in self.forms if form.kind == "tracker-event")
Attributes
program_stage_uids property

Every program stage the guide publishes a form for, which is what a new stage is missing from.

InstanceObject

Bases: BaseModel

One DHIS2 object as the instance states it today.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class InstanceObject(BaseModel):
    """One DHIS2 object as the instance states it today."""

    model_config = ConfigDict(frozen=True)

    uid: str
    name: str = ""

InstanceOption

Bases: BaseModel

One option as the instance states it today, under both the identities a concept can be keyed by.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class InstanceOption(BaseModel):
    """One option as the instance states it today, under both the identities a concept can be keyed by."""

    model_config = ConfigDict(frozen=True)

    uid: str
    code: str | None = None
    name: str = ""

InstanceOptionSet

Bases: BaseModel

One option set as the instance states it today.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class InstanceOptionSet(BaseModel):
    """One option set as the instance states it today."""

    model_config = ConfigDict(frozen=True)

    uid: str
    name: str = ""
    options: tuple[InstanceOption, ...] = ()

InstanceForm

Bases: BaseModel

What the instance says a published form's DHIS2 object collects today.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class InstanceForm(BaseModel):
    """What the instance says a published form's DHIS2 object collects today."""

    model_config = ConfigDict(frozen=True)

    uid: str
    name: str = ""
    questions: tuple[InstanceObject, ...] = ()
    stages: tuple[InstanceObject, ...] = ()
    """The program's stages, read only for a tracker program - the one kind that publishes a form per stage."""
Attributes
stages = () class-attribute instance-attribute

The program's stages, read only for a tracker program - the one kind that publishes a form per stage.

DriftReport

Bases: BaseModel

Everything one drift pass concluded: what it read, what it read it against, and what moved.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
class DriftReport(BaseModel):
    """Everything one drift pass concluded: what it read, what it read it against, and what moved."""

    model_config = ConfigDict(frozen=True)

    registry_scope: str
    organisation_unit_count: int = 0
    option_set_count: int = 0
    form_count: int = 0
    findings: tuple[DriftFinding, ...] = ()

    @property
    def evidence(self) -> str:
        """The one line this pass is read by, quiet when nothing drifted and remedied when something did."""
        read = (
            f"{self.organisation_unit_count:,} organisation unit(s), {self.option_set_count:,} option set(s), "
            f"and {self.form_count:,} form(s) read against {self.registry_scope}"
        )
        if not self.findings:
            return f"the guide publishes the instance as it now stands: {read}"
        return (
            f"{len(self.findings):,} object(s) moved since the guide was published: {read}. "
            f"{DRIFT_REMEDY}. {TRACKED_ENTITY_TYPE_CROSS_REFERENCE}"
        )
Attributes
evidence property

The one line this pass is read by, quiet when nothing drifted and remedied when something did.

Functions:

registry_scope_line(config)

The slice of the hierarchy the registry claims to publish, in the words the evidence states it.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
def registry_scope_line(config: GenerateConfig) -> str:
    """The slice of the hierarchy the registry claims to publish, in the words the evidence states it."""
    selection = config.organisation_units
    if selection.root is not None and selection.max_level is not None:
        return f"the hierarchy under {selection.root} down to level {selection.max_level}"
    if selection.root is not None:
        return f"the hierarchy under {selection.root}"
    if selection.max_level is not None:
        return f"the hierarchy down to level {selection.max_level}"
    return "the whole hierarchy"

read_published_guide(project)

Read what one project publishes off disk, through the reader the served store and check-artifacts use.

load_compiled_artifacts is the single reader of the two published trees - ig/fsh-generated for what the compiler wrote, ig/input/resources for the registry and terminology the emitters wrote straight to JSON - so a drift pass, a served store, and a conversion context can never disagree about what a project publishes. It raises CompiledIgMissingError on a project that was generated but never compiled, which is a fact about the project rather than about the instance.

A worked example is held out of the reading on the guide's own word, the way d2w fhir serve holds it out of what it searches and counts: load_declared_examples reads the compiled ImplementationGuide's definition.resource[], and an instance it declares an example of a profile is not something the guide publishes. The exemplar organisation unit this toolchain mints carries an identifier no DHIS2 instance holds, so grading it would report a removal forever.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
def read_published_guide(project: FhirProject) -> PublishedGuide:
    """Read what one project publishes off disk, through the reader the served store and check-artifacts use.

    `load_compiled_artifacts` is the single reader of the two published trees - `ig/fsh-generated`
    for what the compiler wrote, `ig/input/resources` for the registry and terminology the emitters
    wrote straight to JSON - so a drift pass, a served store, and a conversion context can never
    disagree about what a project publishes. It raises `CompiledIgMissingError` on a project that was
    generated but never compiled, which is a fact about the project rather than about the instance.

    A worked example is held out of the reading on the guide's own word, the way `d2w fhir serve`
    holds it out of what it searches and counts: `load_declared_examples` reads the compiled
    `ImplementationGuide`'s `definition.resource[]`, and an instance it declares an example of a
    profile is not something the guide publishes. The exemplar organisation unit this toolchain mints
    carries an identifier no DHIS2 instance holds, so grading it would report a removal forever.
    """
    artifacts = load_compiled_artifacts(project)
    examples = load_declared_examples(project)
    generate = project.config.generate
    identifier_base = f"{generate.identifier_system_base}/id"
    naming = QuestionnaireNaming.from_naming(generate.naming)
    canonical = project.config.ig.canonical
    question_systems = {
        "data-element": code_system_canonical(canonical, naming.data_element_code_system_id),
        "tracked-entity-attribute": code_system_canonical(canonical, naming.tracked_entity_attribute_code_system_id),
    }
    locations = [item for item in artifacts.locations if examples.publishes("Location", item.id)]
    code_systems = [item for item in artifacts.code_systems if examples.publishes("CodeSystem", item.id)]
    questionnaires = [item for item in artifacts.questionnaires if examples.publishes("Questionnaire", item.id)]
    return PublishedGuide(
        organisation_units=_published_organisation_units(locations, identifier_base),
        option_sets=_published_option_sets(code_systems, identifier_base),
        forms=_published_forms(questionnaires, identifier_base, question_systems),
    )

detect_drift(client, project) async

Read the instance for everything one published guide claims, and report every object that moved.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
async def detect_drift(client: Dhis2Client, project: FhirProject) -> DriftReport:
    """Read the instance for everything one published guide claims, and report every object that moved."""
    published = read_published_guide(project)
    generate = project.config.generate
    findings: list[DriftFinding] = []
    findings.extend(
        compare_organisation_units(published.organisation_units, await _instance_organisation_units(client, generate))
    )
    instance_option_sets = await _instance_option_sets(client, [option_set.uid for option_set in published.option_sets])
    for option_set in published.option_sets:
        findings.extend(compare_option_set(option_set, instance_option_sets.get(option_set.uid)))
    instance_forms = await _instance_forms(client, published.forms)
    for form in published.forms:
        findings.extend(compare_form(form, instance_forms.get(form.uid), published.program_stage_uids))
    return DriftReport(
        registry_scope=registry_scope_line(generate),
        organisation_unit_count=len(published.organisation_units),
        option_set_count=len(published.option_sets),
        form_count=len(published.forms),
        findings=tuple(findings),
    )

compare_organisation_units(published, instance)

Judge the published registry against the hierarchy slice the project selected.

Both sides are already narrowed to the selection, so every difference is drift rather than a unit the project never asked for: a unit the instance gained inside the scope, a unit it lost, and a unit whose name changed under a UID that did not.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
def compare_organisation_units(
    published: Sequence[PublishedObject], instance: Sequence[InstanceObject]
) -> list[DriftFinding]:
    """Judge the published registry against the hierarchy slice the project selected.

    Both sides are already narrowed to the selection, so every difference is drift rather than a
    unit the project never asked for: a unit the instance gained inside the scope, a unit it lost,
    and a unit whose name changed under a UID that did not.
    """
    holder = "the registry scope this project publishes"
    return _compare(DriftSubject.ORGANISATION_UNIT, holder, published, instance)

compare_option_set(published, instance)

Judge one published CodeSystem's concepts against the options the instance's set holds today.

A concept is keyed by the option UID under concept_code_source = "id" and by the option's DHIS2 code under "code", so the instance side is indexed under both and the comparison holds whichever mode the guide was published in.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
def compare_option_set(published: PublishedOptionSet, instance: InstanceOptionSet | None) -> list[DriftFinding]:
    """Judge one published CodeSystem's concepts against the options the instance's set holds today.

    A concept is keyed by the option UID under `concept_code_source = "id"` and by the option's DHIS2
    code under `"code"`, so the instance side is indexed under both and the comparison holds whichever
    mode the guide was published in.
    """
    holder = f"the published option set {published.title or published.uid} ({published.uid})"
    if instance is None:
        return [
            DriftFinding(
                subject=DriftSubject.OPTION_SET,
                kind=DriftKind.REMOVED,
                uid=published.uid,
                holder=_SELECTION_HOLDER,
                published_name=published.title,
            )
        ]
    by_identity: dict[str, InstanceOption] = {}
    for option in instance.options:
        by_identity[option.uid] = option
        if option.code:
            by_identity.setdefault(option.code, option)
    findings: list[DriftFinding] = []
    for concept in published.options:
        matched = by_identity.get(concept.uid)
        if matched is None:
            findings.append(
                DriftFinding(
                    subject=DriftSubject.OPTION,
                    kind=DriftKind.REMOVED,
                    uid=concept.uid,
                    holder=holder,
                    published_name=concept.name,
                )
            )
        elif not _names_agree(concept.name, matched.name):
            findings.append(
                DriftFinding(
                    subject=DriftSubject.OPTION,
                    kind=DriftKind.RENAMED,
                    uid=concept.uid,
                    holder=holder,
                    published_name=concept.name,
                    instance_name=flatten_whitespace(matched.name),
                )
            )
    concept_codes = {concept.uid for concept in published.options}
    findings.extend(
        DriftFinding(
            subject=DriftSubject.OPTION, kind=DriftKind.ADDED, uid=option.uid, holder=holder, instance_name=option.name
        )
        for option in instance.options
        if option.uid not in concept_codes and (option.code or "") not in concept_codes
    )
    return findings

compare_form(published, instance, published_stage_uids)

Judge one published form's questions against what the instance says its DHIS2 object collects.

A tracker registration form answers for its program's attributes and a tracked-entity form for its type's; every other kind answers for data elements. A tracker program is also asked for its stages, because a stage the program gained publishes no form and so asks none of its questions.

Source code in packages/dhis2w-fhir/src/dhis2w_fhir/drift.py
def compare_form(
    published: PublishedForm, instance: InstanceForm | None, published_stage_uids: frozenset[str]
) -> list[DriftFinding]:
    """Judge one published form's questions against what the instance says its DHIS2 object collects.

    A tracker registration form answers for its program's attributes and a `tracked-entity` form for
    its type's; every other kind answers for data elements. A tracker program is also asked for its
    stages, because a stage the program gained publishes no form and so asks none of its questions.
    """
    subject = DriftSubject.TRACKED_ENTITY_ATTRIBUTE if published.asks_attributes else DriftSubject.DATA_ELEMENT
    if instance is None:
        return [
            DriftFinding(
                subject=_FORM_SUBJECTS[published.kind],
                kind=DriftKind.REMOVED,
                uid=published.uid,
                holder=_SELECTION_HOLDER,
                published_name=published.title,
            )
        ]
    findings = _compare(subject, published.holder, published.questions, instance.questions)
    findings.extend(
        DriftFinding(
            subject=DriftSubject.PROGRAM_STAGE,
            kind=DriftKind.ADDED,
            uid=stage.uid,
            holder=published.holder,
            instance_name=stage.name,
        )
        for stage in instance.stages
        if stage.uid not in published_stage_uids
    )
    return findings

Package surface

The names below re-export from dhis2w_fhir itself; the generate page covers what each emitter produces.

dhis2w_fhir

Version-neutral FHIR IG generation: fhir.toml config, FSH emission, and project scaffolding.

Each component owns its schemas; this module is the one stable import surface over them, so from dhis2w_fhir import GenerateConfig keeps working however the components are arranged internally.