"""Vertical slice definitions for the implementation plan. HAND-AUTHORED: edit this file, then run build_slices.py.

Each slice is a thin end-to-end release that crosses domains. Requirements are written as
"<DOMAIN ABBREV>: <MODULE CODE>-<NNN>, ..." and expand to FR-<ABBREV>-<CODE>-<NNN>.
Every functional requirement in the domain specifications must appear in exactly one slice;
build_slices.py fails if one is missing, duplicated or unknown.

phase  = phase of PRS section 16.1 in which the slice is released
tier   = PRS section 12.1 service tier of the workflow the slice delivers
after  = slices whose gate must be passed before this slice can pass its own
gate_wfs = (optional) specification workflows that gate this slice, placed by hand; other workflows are
         placed automatically in the slice holding most of the requirements that cite them
"""

FLOWS = [
    ('RC', 'Registration to care delivery', 'Domain Scope section 5.1',
     'A patient is identified, registered and given an encounter; care is documented against that encounter; the patient has governed digital access.'),
    ('OR', 'Order to result', 'Domain Scope section 5.2',
     'A clinician places a signed order; the owning service fulfils it; a validated result or completed service returns to the clinical record, with critical results acknowledged. '
     'Medication order to administration is included here as the same order-to-fulfilment loop.'),
    ('PA', 'Pathway activation', 'Domain Scope section 5.3',
     'Approved evidence is published as a versioned pathway; an eligible patient is identified; a clinician confirms activation; the pathway coordinates work through the owning domains and its outcomes are evaluated.'),
    ('BC', 'Billing and coding', 'Domain Scope section 5.4',
     'Care activity becomes charges, invoices and claims; the record is completed, coded, retained and disclosed under policy; reconciled measures are reported.'),
    ('XF', 'Outside the four flows', 'Not a Domain Scope flow',
     'Requirements that no critical flow exercises. They are listed so that nothing is left unplaced.'),
]

SLICES = [
    # ------------------------------------------------------------------ Registration to care delivery
    dict(id='RC-1', phase=1, tier='1', after=[],
         title='Register a patient and open an encounter on the platform',
         outcome='The walking skeleton: an authenticated user registers a patient through the gateway, the enterprise index resolves the identity, an encounter is opened, the event is published and the action is audited. It proves the platform, shared services and the first business transaction together.',
         steps=['A registration clerk signs in with multi-factor authentication and is authorized by role (Domain 10).',
                'The clerk searches the enterprise index; matching returns candidates with scores and the duplicate check prompts before a new person is created (Domain 1).',
                'The clerk registers the patient; enterprise and facility identifiers are assigned and demographics are stored with provenance (Domain 1, using Domain 10 registries and terminology).',
                'An encounter is created with its case identifier (Domain 1).',
                'The encounter-opened event is published on the event backbone and is consumable idempotently (Domain 2).',
                'A possible duplicate raises a review task in a work queue through the shared task service (Domains 1 and 10).',
                'Every step is in the audit trail with actor, patient and correlation identifier, and is visible in telemetry (Domains 10 and 2).'],
         reqs=['ESS: IAM-001, IAM-002, IAM-003, IAM-004, AUZ-001, AUD-001, AUD-002, MDM-001, MDM-002, MDM-003, REG-001, TRM-001, TRM-002, CFG-001, CFG-002, CFG-003, WFL-001, WFL-002',
               'ISE: PLT-001, PLT-002, PLT-004, GWY-001, EVT-001, EVT-002, KEY-001, KEY-002, REL-001, REL-002, OBS-001, NET-001, SUP-001, SUP-003',
               'ADM: MPI-001, MPI-002, MPI-003, XRF-001, REG-001, REG-002, REG-003, ENC-001']),
    dict(id='RC-2', phase=2, tier='2', after=['RC-1'],
         title='Outpatient visit: book, arrive, queue and be seen',
         outcome='A patient is booked against provider and resource calendars, reminded, checked in, queued and called, with payer and consent references captured.',
         steps=['A scheduler books an appointment that needs a provider and a room; conflicts are prevented (Domain 1).',
                'A reminder is sent through the notification service and its delivery status is recorded (Domain 10).',
                'On arrival the patient is checked in, payer and consent references are captured and a consent directive is recorded (Domains 1 and 10).',
                'The patient enters a priority queue and appears on the patient-flow board; the clinic calls the patient (Domain 1).',
                'The encounter moves through its governed states; a cancelled or no-show appointment releases the slot to the waiting list (Domain 1).'],
         reqs=['ADM: SCH-001, SCH-002, SCH-003, SCH-004, FLW-001, FLW-002, ENC-002, REF-001, REF-002',
               'ESS: NTF-001, CNS-001']),
    dict(id='RC-3', gate_wfs=['WF-ADM-002', 'WF-ISE-003', 'WF-ISE-005', 'WF-ISE-006', 'WF-ISE-008'], phase=2, tier='1', after=['RC-1'],
         title='Inpatient stay: admit, allocate a bed, transfer and discharge',
         outcome='The admission-transfer-discharge backbone works end to end, feeds external systems, and survives a platform failure. This is the first slice that could carry live patients, so it also brings in backup, disaster recovery, downtime enablement and security assurance.',
         steps=['A patient is admitted and a bed is reserved and allocated without conflict (Domain 1).',
                'The patient is transferred as one governed transition with handover and responsible team (Domain 1).',
                'ADT events are published in order, exchanged with an external system over HL7 v2 or FHIR, acknowledged and reconciled message to transaction (Domains 1 and 2).',
                'A duplicate identity is found, reviewed in the stewardship queue, merged and then unmerged without loss (Domain 1).',
                'The patient is discharged and the encounter is closed; downstream activity is validated against encounter status (Domain 1).',
                'A platform failure is simulated: the service is restored from backup within the approved objectives and downtime entries are reconciled (Domain 2).'],
         reqs=['ADM: ADT-001, ADT-002, ADT-003, BED-001, BED-002, TRF-001, TRF-002, ENC-003, MPI-004, MPI-005, XRF-002',
               'ISE: INT-001, INT-002, INT-003, INT-005, INT-006, GWY-002, KEY-003, PLT-003, REL-003, OBS-002, SUP-002, BCR-001, BCR-002, BCR-003',
               'ESS: AUD-003']),
    dict(id='RC-4', gate_wfs=['WF-ADM-003', 'WF-ESS-002'], phase=2, tier='1', after=['RC-2', 'RC-3'],
         title='Emergency arrival: unidentified patient, triage and emergency access',
         outcome='An unidentified patient is registered in seconds, triaged and routed; a clinician gains emergency access with justification; the identity is reconciled later.',
         steps=['An unidentified patient arrives and is registered under a temporary identity (Domain 1).',
                'Triage assigns acuity and routes the patient; the emergency board shows the state (Domain 1).',
                'A clinician without a care relationship opens the record through break-the-glass, with reason, time limit and review (Domain 10).',
                'The patient is admitted or discharged from emergency through the disposition hand-off (Domain 1).',
                'The real identity is established and reconciled with the temporary record, including newborn and alias cases (Domain 1).'],
         reqs=['ADM: FLW-003, REG-004', 'ESS: AUZ-002']),
    dict(id='RC-5', gate_wfs=['WF-ESS-004'], phase=3, tier='1', after=['RC-3'],
         title='Document care in the clinical record',
         outcome='A clinician opens the chart in the encounter context, records problems, allergies, observations and a signed note, and hands over. Signed content is immutable and amended only with provenance.',
         steps=['A clinician opens the patient chart from the worklist; patient context is persistent and access respects consent and privacy labels (Domains 3 and 10).',
                'Problems, diagnoses and allergies are recorded with governed terminology; unmapped codes go to a steward (Domains 3 and 10).',
                'A nurse records vital signs and an assessment; a risk score triggers an escalation task (Domain 3).',
                'The clinician writes and signs a note from a governed template; an amendment preserves the original (Domain 3).',
                'A care plan and nursing tasks are created; a structured handover is given at shift change (Domain 3).',
                'An external document is imported, registered in the document service and reconciled into the record (Domains 3 and 10).'],
         reqs=['CLI: EHR-001, EHR-002, RSP-003, PRB-001, PRB-002, DOC-001, DOC-002, DOC-003, OBS-001, OBS-002, CAR-001, CAR-002, CAR-003',
               'ESS: TRM-003, AUZ-003, CNS-002, DOC-001']),
    dict(id='RC-6', phase=5, tier='3', after=['RC-2'],
         title='Patient digital access: enrol, appointments, messages and forms',
         outcome='A patient enrols in the portal with identity linking, sees appointments, requests one, receives reminders, exchanges secure messages and submits forms. The portal degrades without affecting core services.',
         steps=['A patient enrols and the account is linked to the enterprise identity after identity proofing; a representative is granted proxy access (Domain 7 with Domain 1).',
                'The patient views and requests an appointment; staff confirm it and a reminder is sent (Domains 7 and 1).',
                'The patient reviews consent and communication preferences and changes one (Domains 7 and 10).',
                'The patient sends a non-urgent message; it is routed, and an urgent-care safeguard is shown (Domain 7).',
                'The patient completes an assigned questionnaire; a clinician reviews it before it enters the record (Domains 7 and 3).',
                'The patient authorizes and then revokes a third-party application (Domains 7, 2 and 10).'],
         reqs=['PEX: ACC-001, ACC-002, ACC-003, ACC-004, ACC-005, PRT-001, PRT-002, APT-001, APT-002, APT-003, MSG-001, MSG-002, FRM-001, FRM-002, PRF-001, PRF-002, PRO-001, PRO-002, NTF-001, NTF-002',
               'ISE: GWY-003, EVT-003', 'ESS: AUZ-004']),
    # ------------------------------------------------------------------ Order to result
    dict(id='OR-1', phase=3, tier='1', after=['RC-5'],
         title='Order entry and result display against a simulated fulfilment service',
         outcome='A clinician signs an order with decision support, the order is routed and tracked, and a result is displayed and acknowledged. The fulfilment side is the agreed Domain 4 contract behind a simulator, which settles the two-way dependency between Domains 3 and 4 before either is complete.',
         steps=['A clinician selects an orderable from the catalogue or an order set and enters the order (Domain 3).',
                'Decision support evaluates the order in context and shows a tiered alert; the clinician overrides with a reason, which is logged (Domain 3).',
                'The order is signed and routed as a versioned request; duplicate orders are controlled (Domains 3 and 2).',
                'The simulator accepts the order and returns status updates and a result on the agreed contract (Domain 4 contract).',
                'The result is shown with version, provenance and trend; the clinician reviews and acknowledges it (Domain 3).'],
         reqs=['CLI: CPO-001, CPO-002, ORD-001, ORD-002, ORD-003, RSP-001, RSP-002, CDS-001, CDS-002, CDS-004, CDS-005']),
    dict(id='OR-2', phase=4, tier='2', after=['OR-1'],
         title='Laboratory order to validated result',
         outcome='The simulator is replaced by the laboratory workflow: specimen collected with positive identification, accessioned, analysed, validated and released to the chart.',
         steps=['The laboratory receives the signed order on its worklist (Domain 4).',
                'A specimen is collected at the bedside with patient-to-specimen barcode verification and labelled (Domain 4).',
                'The specimen is accessioned and its custody tracked; an analyzer returns results over a bidirectional interface (Domain 4).',
                'A delta check flags a result; the scientist validates and releases it (Domain 4).',
                'The result is correlated to its order and appears in the chart; an unmatched result goes to a work queue; a corrected result supersedes the first with both versions kept (Domains 4 and 3).'],
         reqs=['ANC: LIS-001, LIS-002, LIS-003, LIS-004, LIS-005, SPM-001, SPM-002, SPM-003, RES-001, RES-002']),
    dict(id='OR-3', phase=4, tier='1', after=['OR-2'],
         title='Critical result: notify, acknowledge, escalate and close',
         outcome='A critical result reaches an accountable clinician, is acknowledged within the configured time or escalates, and the loop is closed and auditable.',
         steps=['A validated result meets a critical rule (Domain 4).',
                'The responsible clinician is resolved and notified; an accountable work item is created (Domains 4 and 10).',
                'No acknowledgement arrives in time; the notification escalates to the next recipient (Domain 10).',
                'The clinician acknowledges and records the action taken; the loop is closed (Domains 3 and 4).'],
         reqs=['ANC: RES-003', 'ESS: NTF-002']),
    dict(id='OR-4', phase=4, tier='2', after=['OR-1'],
         title='Imaging order to report',
         outcome='An imaging order is scheduled, acquired on a modality from a worklist, stored with DICOM, reported and returned to the chart with an image reference.',
         steps=['An imaging order is received and scheduled on a modality (Domain 4).',
                'The modality takes the patient from the worklist and reports acquisition status (Domains 4 and 2).',
                'The study is stored in the archive and its metadata and image reference are registered (Domain 4).',
                'A radiologist reports the study; the report returns to the chart with a controlled link to the images (Domains 4 and 3).',
                'The archive content is exported in standard form to show it is replaceable (Domain 4).'],
         reqs=['ANC: RIS-001, RIS-002, IMG-001, IMG-002', 'ISE: INT-004']),
    dict(id='OR-5', phase=4, tier='1 for transfusion verification and blood issue; 2 for blood bank inventory (DEC-ANC-008)', after=['OR-2'],
         gate_extra=[('The blood bank decision functions (compatibility testing, electronic issue, bedside verification) are classified as Software as a Medical Device, built as a separately versioned component, and hold an NIE from Kemenkes before production use', 'Approved SaMD classification record and NIE', '[COMP-ANC-009](../../../domain_specs/D04-ANC/09-security-privacy-compliance.md#comp-anc-009)')],
         title='Pathology, blood bank and procedure or consultation fulfilment',
         outcome='The remaining fulfilment paths work on the same order contract: a pathology case, a blood product from request to bedside-verified transfusion, human milk feed verification, and a procedure or consultation.',
         steps=['A pathology case is accessioned, processed and reported (Domain 4).',
                'A blood product is requested, compatibility tested, issued and verified at the bedside before transfusion; a reaction is recorded (Domain 4).',
                'A unit is traced from receipt to final fate (Domain 4).',
                'The SaMD classification record of the blood bank decision functions is approved and the NIE from Kemenkes is held before production use (Domain 4, COMP-ANC-009).',
                'A human milk feed is verified against the infant at the bedside (Domain 4).',
                'A procedure or consultation order is accepted, performed and completed back to the order (Domain 4).'],
         reqs=['ANC: PTH-001, BBK-001, BBK-002, BBK-003, BBK-004, PRC-001']),
    dict(id='OR-6', gate_wfs=['WF-CLI-008'], phase=4, tier='1', after=['OR-1', 'BC-6'],
         title='Medication order to bedside administration (closed loop)',
         outcome='A medication is prescribed with safety checks, verified and dispensed by pharmacy against stock, and administered at the bedside with barcode verification. Downtime administrations are reconciled; offline recording is disabled in release 1 (DEC-CLI-006).',
         steps=['The medication list is reconciled at admission from history and external sources (Domain 3).',
                'A clinician prescribes; allergy, interaction and dose checks run; a hard stop cannot be overridden and a soft alert needs a reason (Domain 3).',
                'A pharmacist verifies the order, substitutes within the formulary and dispenses a barcoded unit dose; stock is decremented in the single ledger (Domains 3 and 5).',
                'A nurse scans patient and medication at the bedside; a mismatch blocks administration; the administration is recorded on the eMAR (Domain 3).',
                'A controlled substance is dispensed from a cabinet with witness and the count reconciles (Domains 3 and 5).',
                'The network is lost; the bedside screen shows "Not connected · nothing has been recorded" and staff follow the downtime procedure, then enter the doses on the downtime entry screen without duplicates (offline recording is disabled in release 1, DEC-CLI-006; Domains 3 and 2).'],
         reqs=['CLI: RXV-001, RXV-002, RXV-003, MHR-001, MHR-002, MAR-001, MAR-002, MAR-003, CDS-003', 'ISE: EVT-004']),
    dict(id='OR-7', phase=4, tier='1 for ICU charting and the intra-operative record; 2 for theatre scheduling (DEC-ANC-008)', after=['OR-1', 'RC-3'],
         title='Surgical case, critical care and therapy',
         outcome='A surgical case runs from request through checklist, anesthesia record and recovery handoff; an ICU patient is charted with validated device data; a therapy referral is treated.',
         steps=['A surgical case is requested and scheduled in a theatre (Domain 4).',
                'Pre-operative assessment and checklist are completed and the team time-out is recorded before incision (Domain 4).',
                'The anesthesia and intra-operative record captures events, implants and counts (Domain 4).',
                'The patient is handed over from recovery to the ward with a structured handoff (Domains 4 and 3).',
                'In ICU a device is associated with the patient; its measurements are validated by a clinician before entering the flowsheet; a care bundle escalates (Domain 4).',
                'A therapy referral is accepted, planned and delivered in sessions (Domain 4).'],
         reqs=['ANC: PER-001, PER-002, IOP-001, IOP-002, ICU-001, ICU-002, DEV-001, DEV-002, RHB-001, RHB-002']),
    dict(id='OR-8', phase=5, tier='3', after=['OR-2', 'RC-6'],
         title='Release results and documents to the patient',
         outcome='A reviewed result reaches the patient portal under release policy; sensitive or unreviewed results are withheld and a release can be withdrawn.',
         steps=['A validated result is evaluated against the approved release policy (Domain 7).',
                'A result that requires clinician review is held until reviewed, then released (Domains 3 and 7).',
                'The patient sees the released result with plain presentation and source (Domain 7).',
                'A sensitive-category result is withheld; a released result is withdrawn after a correction (Domains 7 and 4).',
                'A discharge document is released to the patient (Domains 7 and 6).'],
         reqs=['PEX: REL-001, REL-002, REL-003, REL-004']),
    # ------------------------------------------------------------------ Pathway activation
    dict(id='PA-1', phase=3, tier='Not tiered by the PRS', after=['RC-1'],
         title='Publish an approved guideline and pathway',
         outcome='Evidence is registered with provenance and grade, mapped to terminology, authored as a pathway, tested, clinically approved and published as an immutable version. This slice needs only shared services, so it can run alongside the clinical slices.',
         steps=['An evidence source and guideline are registered with provenance, grade and owner (Domain 9).',
                'Guideline concepts are mapped to clinical terminology and classifications; an ambiguous mapping is resolved by a reviewer (Domains 9 and 10).',
                'A pathway is authored with eligibility, phases, activities and patient-specific parameters, and passes scenario tests (Domain 9).',
                'The governance body approves the version; release checks pass and it is published (Domain 9).',
                'A published version is suspended and rolled back; the earlier version remains retrievable (Domain 9).'],
         reqs=['EBP: EVR-001, EVR-002, EGR-001, MAP-001, MAP-002, GDL-001, GDL-002, GDL-003, PAU-001, PAU-002, PAU-003, PGV-001, PGV-002, PGV-003, GOV-001']),
    dict(id='PA-2', phase=4, tier='Not tiered by the PRS', after=['PA-1', 'RC-5', 'OR-2'],
         title='Eligibility evaluation and clinician-confirmed activation',
         outcome='A potentially eligible patient is identified from current clinical facts; the clinician sees the rationale and confirms, defers or rejects; nothing activates without that action.',
         steps=['Eligibility is evaluated from encounter, diagnosis and result facts read from Domains 1, 3 and 4 (Domain 9).',
                'The clinician sees criteria met and not met with source data; missing or stale data is shown as such (Domain 9).',
                'The clinician confirms activation and a pathway instance is created against the published version (Domain 9).',
                'In a second case the clinician defers, and in a third rejects with a reason (Domain 9).',
                'Pathway guidance is available to decision support in the ordering context (Domains 9 and 3).',
                'Each decision is in the pathway audit trail (Domain 9).'],
         reqs=['EBP: ELG-001, ELG-002, ELG-003, ACT-001, RUN-001, RUN-004, GOV-002']),
    dict(id='PA-3', phase=4, tier='Not tiered by the PRS', after=['PA-2', 'OR-1'],
         title='Pathway execution through the owning domains',
         outcome='An active pathway proposes orders and tasks that are created and owned by Domains 3 and 4, tracks due dates, and records variance, deferral and escalation.',
         steps=['A pathway step proposes an order set; the clinician signs it in CPOE and the order belongs to Domain 3 (Domains 9 and 3).',
                'A nursing task is created through the Domain 3 worklist and its completion advances the pathway (Domains 9 and 3).',
                'A diagnostic step completes when its validated result returns (Domains 9, 3 and 4).',
                'A step is overdue and escalates; a clinician records a variance and pauses the pathway (Domain 9).',
                'The content that applied at the time of care is reconstructed for review (Domain 9).'],
         reqs=['EBP: RUN-002, RUN-003, EXC-001, EXC-002, EXC-003, GOV-003', 'PEX: REL-005']),
    dict(id='PA-4', phase=6, tier='3', after=['PA-3', 'BC-8'],
         title='Pathway and clinical quality outcome evaluation',
         outcome='Adherence and outcome measures are computed on the governed data platform with lineage back to source events, reviewed by governance and fed into the next pathway version.',
         steps=['Measures and cohorts are defined for a pathway with effective dates (Domain 9).',
                'Domain 8 computes adherence and outcome measures from governed feeds; each figure traces to source events (Domains 8 and 9).',
                'Clinical quality indicators are computed on the same platform (Domain 8).',
                'The pathway and evidence dashboard of PRS Appendix B is published in the minimum dashboard catalogue, and the catalogue completeness check now passes for all nine dashboards (Domain 8).',
                'Governance reviews the results and raises a change that starts a new pathway version (Domain 9).'],
         reqs=['EBP: OUT-001, OUT-002, OUT-003', 'ANL: CQI-001, CQI-002']),
    # ------------------------------------------------------------------ Billing and coding
    dict(id='BC-1', phase=5, tier='2', after=['RC-2'],
         title='Eligibility and coverage at registration',
         outcome='Coverage is verified at registration or booking, with multiple coverage layers and authorization tracked. In release 1 verification is a staff check of the guarantee letter or the payer portal, recorded with its source (IF-FIN-003, EXT-FIN-001); electronic real-time checking follows when a payer offers it. Verification never blocks registration.',
         steps=['At registration an eligibility request is sent and the response is stored against the encounter (Domains 5 and 1).',
                'A patient with primary and secondary coverage shows both layers and the benefit summary (Domain 5).',
                'An authorization is requested and its status tracked (Domain 5).',
                'The payer connection is down; registration continues and verification is queued for batch (Domains 5 and 2).'],
         reqs=['FIN: PAY-001, PAY-002, PAY-003']),
    dict(id='BC-2', phase=5, tier='2', after=['OR-1', 'RC-3', 'BC-1', 'BC-6'],  # BC-1 and BC-6 added on review 2026-11-24: payer coverage and stock ledger
         title='Clinical event to priced charge',
         outcome='Chargeable events from care become charge items asynchronously, priced from the effective tariff, traceable to source, without ever blocking the clinical action.',
         steps=['An order completion, a procedure and a bed-day each emit a chargeable event (Domains 3, 4 and 1).',
                'Charge capture consumes the events idempotently and creates charge items validated against the encounter (Domain 5).',
                'Prices come from the effective-dated tariff with payer contract, package and co-payment rules (Domain 5).',
                'A duplicate event creates no second charge; an event that cannot be priced goes to an exception queue (Domain 5).',
                'Source activity reconciles to the charge ledger (Domain 5).'],
         reqs=['FIN: CHG-001, CHG-002, TAR-001, TAR-002, EXC-001']),
    dict(id='BC-3', phase=5, tier='2', after=['BC-2'],
         title='Patient account, invoice and payment',
         outcome='Charges accumulate on a patient account, are invoiced, paid at the cashier, corrected by reversal and reconciled per cashier session; the patient can see the statement.',
         steps=['Charges post to the patient account and receivable ledgers (Domain 5).',
                'An invoice is generated at discharge; a deposit is applied (Domain 5).',
                'The cashier takes payment, issues a receipt and allocates it; a refund is approved and paid (Domain 5).',
                'A wrong charge is corrected by reversal and a credit note, keeping history (Domain 5).',
                'The cashier session closes and reconciles (Domain 5).',
                'The patient views the statement and payment status in the portal (Domain 7).'],
         reqs=['FIN: BIL-001, BIL-002, BIL-003, BIL-004, BIL-005, CSH-001, CSH-002, CSH-003', 'PEX: BIL-001, BIL-002']),
    dict(id='BC-4', phase=3, tier='3', after=['RC-5'],
         title='Record assembly, document stewardship and chart completion',
         outcome='From the first clinical documents onward the encounter record is assembled, its documents are classified and versioned, deficiencies are chased and closed, and the completed record is locked. It is released in phase 3, ahead of the rest of this flow and in the same release as clinical documentation (RC-5), so that every record created from clinical go-live is governed and no manual chart tracking is needed. The phase 3 clinical release does not go live until this slice has passed.',
         steps=['The encounter record is assembled from documents, results and procedure records, and each document is classified and indexed (Domain 6).',
                'A missing signature is detected as a deficiency, assigned to the clinician, escalated and closed (Domains 6 and 3).',
                'The record is completed and locked; a late note is added as a post-lock amendment (Domain 6).',
                'A paper form from downtime is scanned and indexed to the encounter; an indexing error is corrected with history (Domain 6).',
                'HIM staff work the queues with assignment and ageing, and re-link records after an identity merge (Domains 6 and 1).',
                'Encounters and diagnoses are submitted to SATUSEHAT in reference order, rejections reach the owning domain and completeness is reported against the national criteria; medication, specimen and imaging resources join as their phase 4 slices go live (Domains 6, 1, 3, 4 and 2).'],
         reqs=['HIM: RAC-001, RAC-002, RAC-003, CDT-001, CDT-002, WBN-001, WBN-002, DOC-001, DOC-002, DOC-003, ROI-005']),
    dict(id='BC-10', phase=5, tier='3', after=['BC-4'],
         title='Encounter coding to billing readiness',
         outcome='A completed encounter is coded with crosswalk assistance and human review, validated, finalised and its coding status made available to billing.',
         steps=['A completed encounter appears on the coding worklist (Domain 6).',
                'A coder assigns codes with crosswalk assistance; every suggested code is confirmed by a person (Domain 6).',
                'Validation keeps clinical terminology and billing classifications separate and rejects an invalid combination (Domains 6 and 10).',
                'Coding is finalised and the status is available to billing; a later revision is versioned and billing is notified (Domains 6 and 5).'],
         reqs=['HIM: COD-001, COD-002, COD-003, COD-004']),
    dict(id='BC-5', phase=5, tier='3', after=['BC-1', 'BC-3', 'BC-10'],
         title='Claim to remittance and finance posting',
         outcome='A coded, invoiced encounter becomes a validated claim, is submitted, tracked, denied and resubmitted, reconciled against remittance and posted to the finance system.',
         steps=['A claim is generated from the invoice, coverage and final codes and validated against payer rules (Domain 5).',
                'The claim is submitted through the payer adapter and its status tracked (Domains 5 and 2).',
                'A denial enters a work queue, is corrected and resubmitted (Domain 5).',
                'Remittance is reconciled to the claim and the receivable (Domain 5).',
                'Financial events are posted to the finance system and reconcile (Domains 5 and 2).'],
         reqs=['FIN: CLM-001, CLM-002, CLM-003, CLM-004, GLP-001, GLP-002']),
    dict(id='BC-6', phase=4, tier='2', after=['RC-1'],
         title='Stock ledger, procurement and departmental consumption',
         outcome='One stock ledger holds every item, lot and movement; goods are requisitioned, purchased and received; departments consume and are replenished. It is released in phase 4, ahead of the rest of this flow, because medication dispensing must reconcile to stock.',
         steps=['Items, locations and lots with expiry are set up in the item master (Domain 5).',
                'A requisition is approved, ordered and received into stock (Domain 5).',
                'Stock is issued to a department, consumed against a patient and returned; every movement is an append-only ledger entry (Domain 5).',
                'A stocktake finds a variance and an approved adjustment is posted (Domain 5).',
                'Pharmacy and dispensing cabinet balances, including controlled substances, reconcile to the ledger (Domains 5 and 3).',
                'A reorder point triggers replenishment; consumption entered during downtime is reconciled (Domain 5).'],
         reqs=['FIN: INV-001, INV-002, INV-003, INV-004, INV-005, PRC-001, PRC-002, REP-001, REP-002, EXC-002']),
    dict(id='BC-7', phase=5, tier='3', after=['BC-4'],
         title='Disclosure, retention and legal hold',
         outcome='A request for records is verified, assembled, redacted, approved, delivered and logged; records are retained and disposed under schedule; a legal hold prevents disposal.',
         steps=['A disclosure request is received and the requester and authorization are verified (Domain 6).',
                'A release package is assembled within consent and disclosure restrictions, redacted and approved by a second person (Domains 6 and 10).',
                'The package is delivered and the disclosure is logged; the patient can obtain an accounting of disclosures (Domain 6).',
                'A retention schedule marks records as due; disposal is approved and recorded (Domain 6).',
                'A legal hold is applied; disposal and modification are blocked until it is released (Domain 6).',
                'A data-subject request is coordinated across domains (Domain 10).'],
         reqs=['HIM: ROI-001, ROI-002, ROI-003, ROI-004, AUD-001, AUD-002, RET-001, RET-002, RET-003, LHD-001, LHD-002, CEV-001, CEV-002',
               'ESS: CNS-003']),
    dict(id='BC-8', gate_wfs=['WF-ANL-002'], phase=5, tier='3', after=['RC-3'],
         title='Governed data platform fed by flow events',
         outcome='Events from the operational domains are ingested into an isolated analytical platform, validated, conformed and published as curated data products with lineage, quality scores and governed metric definitions.',
         steps=['Analytical workloads run isolated from clinical transaction stores (Domains 8 and 2).',
                'Domain events are ingested to the raw layer; a replay does not duplicate (Domain 8).',
                'Data is validated and conformed; a failing batch is quarantined and sent to a steward (Domains 8 and 10).',
                'A curated data product is published with an owner and lineage to source events (Domain 8).',
                'A metric is defined with an effective date and reproduces the same figure for a past period (Domain 8).',
                'Source counts reconcile to the platform (Domain 8).'],
         reqs=['ANL: DWH-001, DWH-002, DWH-003, DWH-004, DQL-001, DQL-002, DQL-003, SEM-001, SEM-002', 'ESS: DGV-001, DGV-002, DGV-003']),
    dict(id='BC-9', phase=5, tier='3', after=['BC-8', 'BC-2'],
         title='Operational, revenue-cycle and management reporting',
         outcome='The minimum dashboards are live on reconciled data: patient flow, diagnostics, medication safety, revenue cycle, resource use and management trends, each showing freshness and source reconciliation.',
         steps=['The minimum operational dashboard catalogue is published to authorized roles with eight of the nine PRS Appendix B dashboards; the ninth, pathway and evidence, is added by slice PA-4 (Domain 8).',
                'A patient-flow and a diagnostic turnaround dashboard show figures that reconcile to Domains 1 and 4 (Domain 8).',
                'A revenue-cycle report reconciles financial events to the Domain 5 ledger (Domain 8).',
                'Each dashboard shows its data cutoff; a stale source is flagged, not shown as current (Domain 8).',
                'Management reporting shows trends over governed metric definitions (Domain 8).'],
         reqs=['ANL: OPS-001, OPS-002, OPS-003, OPS-004, FRR-001, FRR-002, RUC-001, MGT-001']),
    # ------------------------------------------------------------------ Outside the four flows
    dict(id='XF-1', phase=3, tier='Cross-cutting', after=['RC-3'],
         title='Data portability and exit export',
         outcome='A complete export of data and configuration in documented formats is demonstrated. It is a go-live gate (ACC-008) for every flow, not part of one, and is repeated as each domain adds its export contract.',
         steps=['An export of the data held so far is produced in documented, non-proprietary formats (Domain 2 with each owning domain).',
                'The export is loaded into a clean environment and reconciles to the source (Domain 2).'],
         reqs=['ISE: BCR-004']),
    dict(id='XF-2', phase=6, tier='4', after=['BC-8'],
         title='Governed AI, research extracts and maturity scorecard',
         outcome='Optional capabilities on the data platform: approved research and quality-improvement extracts with de-identification, a governed AI workspace whose outputs are labelled and human-reviewed, and the digital maturity scorecard. None is needed by a critical flow.',
         steps=['An approved research extract is produced as a de-identified or limited data set with re-identification risk controls (Domain 8).',
                'An AI use case is registered and assessed; its access goes through the policy gateway and is logged (Domain 8).',
                'An AI-drafted text is labelled and reviewed by a human before anything is committed; with the model unavailable the core workflow is unaffected (Domain 8).',
                'The digital maturity and operational scorecard is published (Domain 8).'],
         reqs=['ANL: RDX-001, RDX-002, AIG-001, AIG-002, AIG-003, AIG-004, AIG-005, MGT-002']),
]

# Phases of PRS section 16.1 (phase 0 is mobilisation and phase 7 is scale-out; neither releases a slice).
PHASES = {1: 'Platform foundation', 2: 'Patient administration', 3: 'Core clinical', 4: 'Ancillary and medication',
          5: 'Revenue and enterprise operations', 6: 'Analytics and optimization'}

# How individual slices relate to the PRS 16.1 phase table where that is not obvious from the table itself.
PHASE_NOTES = [
    ('RC-1', 'PRS phase 1 exit criteria include a first patient registration and encounter; full patient administration is phase 2.', 'Same. The slice proves the platform foundation with a real transaction.'),
    ('OR-1', 'PRS phase 3 lists CPOE and results; phase 4 lists the laboratory and imaging systems.', 'Order entry and result display are released in phase 3 against a simulator of the Domain 4 contract, so the contract is agreed before either side is finished. The PRS does not prescribe this.'),
    ('XF-1', 'PRS phase 3 exit criteria include a data export demonstration; ACC-008 requires it at go-live.', 'Same: first demonstrated in phase 3 and repeated as later slices add data.'),
]
