Skip to main content

wellfare_core/
clinical.rs

1//! Clinical documents / pathology — Restricted, records-first clinical entries.
2//!
3//! Implements the master plan's clinical-document rules (audit CLI-01..13, plan §5):
4//!
5//! - **Records-first, manual entry.** A `ClinicalReport` captures what the owner (or a
6//!   labelled author) actually typed. There is **NO parsing of pathology/imaging PDFs
7//!   here** — a mock extractor must never be presented as real parsing. Structured
8//!   extraction, when it exists, is a separate audited stage that raises its own records;
9//!   this module only stores hand-entered documents and their attachment metadata.
10//! - **Content-addressed attachments (plan §5).** The attachment *content* is a
11//!   content-addressed blob stored elsewhere. `AttachmentMeta` holds only metadata plus
12//!   the content hash — never the bytes.
13//! - **Honest epistemics.** An unconfirmed report is *asserted by its author*, not
14//!   observed by a clinician. Only a `ClinicianConfirmed` report maps to
15//!   `EvidenceType::ClinicianObserved`; a `Disputed` report is surfaced as
16//!   `EpistemicStatus::Disputed`. The envelope never launders a self-reported claim into
17//!   clinician-grade evidence.
18
19use serde::{Deserialize, Serialize};
20use uuid::Uuid;
21
22use crate::record::{
23    EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
24};
25
26/// Category of a manually-entered clinical document.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "snake_case")]
29pub enum ClinicalReportType {
30    Pathology,
31    Imaging,
32    Discharge,
33    Referral,
34    Other,
35}
36
37impl Default for ClinicalReportType {
38    fn default() -> Self {
39        Self::Other
40    }
41}
42
43/// Claim-approval lifecycle for a clinical document.
44///
45/// A report starts life as an owner/author claim and only becomes clinician-grade
46/// evidence once a clinician confirms it. The transitions are deliberately narrow so the
47/// state can never silently upgrade its own trustworthiness (see [`advance_claim`]).
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50pub enum ClaimStatus {
51    /// Being written; not yet put forward for confirmation.
52    Draft,
53    /// Put forward by the author, awaiting clinician review.
54    Submitted,
55    /// A clinician has confirmed the document as accurate.
56    ClinicianConfirmed,
57    /// A clinician (or the owner) disputes the document's accuracy.
58    Disputed,
59    /// Replaced by a newer report (a correction / re-issue).
60    Superseded,
61}
62
63impl Default for ClaimStatus {
64    fn default() -> Self {
65        Self::Draft
66    }
67}
68
69/// Events that can move a [`ClaimStatus`] along its lifecycle.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "snake_case")]
72pub enum ClaimEvent {
73    /// Author submits a draft for clinician review.
74    Submit,
75    /// A clinician confirms a submitted report.
76    Confirm,
77    /// A clinician / owner disputes the report.
78    Dispute,
79    /// A newer report replaces this one.
80    Supersede,
81    /// A disputed report is sent back to the author for revision.
82    Revise,
83}
84
85/// Advance the claim lifecycle for a given event, returning the resulting status.
86///
87/// Transition table (any pair not listed is a **no-op**, i.e. the current status is
88/// returned unchanged — invalid moves never silently succeed):
89///
90/// | From                 | Event      | To                   |
91/// |----------------------|------------|----------------------|
92/// | `Draft`              | `Submit`   | `Submitted`          |
93/// | `Submitted`          | `Confirm`  | `ClinicianConfirmed` |
94/// | `Submitted`          | `Dispute`  | `Disputed`           |
95/// | `ClinicianConfirmed` | `Dispute`  | `Disputed`           |
96/// | `ClinicianConfirmed` | `Supersede`| `Superseded`         |
97/// | `Disputed`           | `Confirm`  | `ClinicianConfirmed` |
98/// | `Disputed`           | `Revise`   | `Draft`              |
99/// | `Disputed`           | `Supersede`| `Superseded`         |
100/// | `Submitted`          | `Supersede`| `Superseded`         |
101///
102/// In particular a `Draft` can **never** jump straight to `ClinicianConfirmed`: a
103/// `Confirm` event on a `Draft` is a no-op, so a document must always pass through
104/// `Submitted` (author submission) before a clinician can confirm it.
105pub fn advance_claim(status: ClaimStatus, event: ClaimEvent) -> ClaimStatus {
106    use ClaimEvent::*;
107    use ClaimStatus::*;
108    match (status, event) {
109        (Draft, Submit) => Submitted,
110        (Submitted, Confirm) => ClinicianConfirmed,
111        (Submitted, Dispute) => Disputed,
112        (Submitted, Supersede) => Superseded,
113        (ClinicianConfirmed, Dispute) => Disputed,
114        (ClinicianConfirmed, Supersede) => Superseded,
115        (Disputed, Confirm) => ClinicianConfirmed,
116        (Disputed, Revise) => Draft,
117        (Disputed, Supersede) => Superseded,
118        // Any other (status, event) pair is not a legal transition: no-op.
119        (other, _) => other,
120    }
121}
122
123/// A manually-entered clinical document (pathology / imaging / discharge / referral).
124///
125/// `body` is exactly what the author typed. `attachment_blob_hash` optionally links to a
126/// content-addressed blob (the original PDF/image) whose metadata lives in
127/// [`AttachmentMeta`]; the bytes are never stored in this struct.
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
129pub struct ClinicalReport {
130    pub id: String,
131    pub title: String,
132    #[serde(default)]
133    pub report_type: ClinicalReportType,
134    /// Free-text label for the author (e.g. "Dr Smith, Pathology") — NOT a verified DID.
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub author_label: Option<String>,
137    /// When the clinical event / observation occurred (unix seconds).
138    pub observed_at_unix: u32,
139    /// High-resolution instant (T71 bridge). Preferred over `observed_at_unix`
140    /// when present; the u32 field is kept for backward-compatible deserialization.
141    #[serde(skip_serializing_if = "Option::is_none", default)]
142    pub observed_at_instant: Option<InstantBridge>,
143    /// The document body as typed by the author. No parsing is performed on it.
144    pub body: String,
145    /// Optional content hash of the attached source document blob.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub attachment_blob_hash: Option<String>,
148    #[serde(default)]
149    pub claim_status: ClaimStatus,
150}
151
152impl ClinicalReport {
153    /// Creates a new instance.
154    pub fn new(
155        title: impl Into<String>,
156        report_type: ClinicalReportType,
157        observed_at_unix: u32,
158        body: impl Into<String>,
159    ) -> Self {
160        Self {
161            id: Uuid::new_v4().to_string(),
162            title: title.into(),
163            report_type,
164            author_label: None,
165            observed_at_unix,
166            observed_at_instant: Some(InstantBridge::from_coarse(observed_at_unix)),
167            body: body.into(),
168            attachment_blob_hash: None,
169            claim_status: ClaimStatus::Draft,
170        }
171    }
172
173    /// Resolve the observed-at instant, preferring the high-resolution
174    /// `InstantBridge` field when present (T71 bridge).
175    pub fn observed_at(&self) -> InstantBridge {
176        self.observed_at_instant
177            .unwrap_or_else(|| InstantBridge::from_coarse(self.observed_at_unix))
178    }
179}
180
181/// Metadata for a content-addressed attachment blob (plan §5).
182///
183/// The blob content itself is stored out-of-band and referenced by `content_hash`; this
184/// struct records only the descriptive metadata needed to present and verify it.
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186pub struct AttachmentMeta {
187    pub id: String,
188    pub filename: String,
189    /// MIME/media type, e.g. "application/pdf" or "image/png".
190    pub media_type: String,
191    pub byte_len: u64,
192    /// Content-address of the blob (e.g. a hex digest). This is the load-bearing anchor.
193    pub content_hash: String,
194}
195
196impl AttachmentMeta {
197    /// Creates a new instance.
198    pub fn new(
199        filename: impl Into<String>,
200        media_type: impl Into<String>,
201        byte_len: u64,
202        content_hash: impl Into<String>,
203    ) -> Self {
204        Self {
205            id: Uuid::new_v4().to_string(),
206            filename: filename.into(),
207            media_type: media_type.into(),
208            byte_len,
209            content_hash: content_hash.into(),
210        }
211    }
212}
213
214///  record ID.
215pub fn clinical_report_record_id(uuid: &str) -> String {
216    format!("urn:wellfair:clinical_report:{uuid}")
217}
218
219///  record ID.
220pub fn clinical_attachment_record_id(uuid: &str) -> String {
221    format!("urn:wellfair:clinical_attachment:{uuid}")
222}
223
224/// Map a claim status to the epistemic status the envelope should honestly carry.
225///
226/// Only a clinician-confirmed report is anything other than an author assertion, and a
227/// disputed report is surfaced as `Disputed`. A superseded document keeps whatever it was
228/// (a superseded correction is still, at heart, an assertion) — its replacement is tracked
229/// via the envelope `predecessor_id`, not by re-labelling epistemics.
230fn epistemic_for_claim(status: ClaimStatus) -> EpistemicStatus {
231    match status {
232        ClaimStatus::Disputed => EpistemicStatus::Disputed,
233        // Confirmation is about *evidence grade* (clinician-observed), not about the
234        // proposition being a hypothesis; a confirmed report is still an assertion.
235        ClaimStatus::Draft
236        | ClaimStatus::Submitted
237        | ClaimStatus::ClinicianConfirmed
238        | ClaimStatus::Superseded => EpistemicStatus::Asserted,
239    }
240}
241
242/// Map a claim status to the evidence type. Crucially, a report only counts as
243/// `ClinicianObserved` once it is `ClinicianConfirmed`; everything else is
244/// `SelfReported`, because it is an author's claim until a clinician confirms it.
245fn evidence_for_claim(status: ClaimStatus) -> EvidenceType {
246    match status {
247        ClaimStatus::ClinicianConfirmed => EvidenceType::ClinicianObserved,
248        _ => EvidenceType::SelfReported,
249    }
250}
251
252/// Build the record envelope for a clinical report, deriving epistemic/evidence honesty
253/// from its claim status. Always `Restricted`.
254pub fn build_clinical_report_envelope(
255    report: &ClinicalReport,
256    owner_did: &str,
257    author_did: &str,
258    asserted_unix: u32,
259    blob_hash: Option<String>,
260) -> RecordEnvelope {
261    RecordEnvelope {
262        id: clinical_report_record_id(&report.id),
263        owner_did: owner_did.to_string(),
264        author_did: author_did.to_string(),
265        proxy_did: None,
266        epistemic_status: epistemic_for_claim(report.claim_status),
267        evidence_type: evidence_for_claim(report.claim_status),
268        sensitivity: SensitivityClass::Restricted,
269        asserted_time_unix: asserted_unix,
270        asserted_instant: None,
271        valid_time_start_unix: Some(report.observed_at_unix),
272        valid_time_start_instant: report.observed_at_instant,
273        valid_time_end_unix: None,
274        valid_time_end_instant: None,
275        predecessor_id: None,
276        blob_hash,
277        tombstone: false,
278    }
279}
280
281/// Build the record envelope for an attachment's metadata. The blob hash is carried both
282/// as the content anchor and (redundantly for the graph) as the envelope `blob_hash`.
283pub fn build_clinical_attachment_envelope(
284    meta: &AttachmentMeta,
285    owner_did: &str,
286    author_did: &str,
287    asserted_unix: u32,
288) -> RecordEnvelope {
289    RecordEnvelope {
290        id: clinical_attachment_record_id(&meta.id),
291        owner_did: owner_did.to_string(),
292        author_did: author_did.to_string(),
293        proxy_did: None,
294        // Attachment metadata describes a stored file; it is an asserted, self-reported fact.
295        epistemic_status: EpistemicStatus::Asserted,
296        evidence_type: EvidenceType::SelfReported,
297        sensitivity: SensitivityClass::Restricted,
298        asserted_time_unix: asserted_unix,
299        asserted_instant: None,
300        valid_time_start_unix: Some(asserted_unix),
301        valid_time_start_instant: None,
302        valid_time_end_unix: None,
303        valid_time_end_instant: None,
304        predecessor_id: None,
305        blob_hash: Some(meta.content_hash.clone()),
306        tombstone: false,
307    }
308}
309
310///  summary.
311pub fn clinical_report_summary(report: &ClinicalReport) -> String {
312    serde_json::json!({
313        "title": report.title,
314        "report_type": report.report_type,
315        "author_label": report.author_label,
316        "observed_at_unix": report.observed_at_unix,
317        "claim_status": report.claim_status,
318        "has_attachment": report.attachment_blob_hash.is_some(),
319    })
320    .to_string()
321}
322
323///  summary.
324pub fn clinical_attachment_summary(meta: &AttachmentMeta) -> String {
325    serde_json::json!({
326        "filename": meta.filename,
327        "media_type": meta.media_type,
328        "byte_len": meta.byte_len,
329        "content_hash": meta.content_hash,
330    })
331    .to_string()
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    #[test]
339    fn report_envelope_kind_and_sensitivity() {
340        let report = ClinicalReport::new(
341            "Full blood count",
342            ClinicalReportType::Pathology,
343            1_700_000_000,
344            "Hb 140 g/L; WCC 6.2",
345        );
346        let env = build_clinical_report_envelope(
347            &report,
348            "did:wf:owner",
349            "did:wf:owner",
350            1_700_000_500,
351            Some("blobhash".into()),
352        );
353        assert!(env.id.contains(":clinical_report:"));
354        assert_eq!(env.sensitivity, SensitivityClass::Restricted);
355        // valid_time_start tracks the clinical observation time, not assertion time.
356        assert_eq!(env.valid_time_start_unix, Some(1_700_000_000));
357    }
358
359    #[test]
360    fn attachment_envelope_kind_and_hash() {
361        let meta = AttachmentMeta::new("path_report.pdf", "application/pdf", 2048, "deadbeef");
362        let env = build_clinical_attachment_envelope(
363            &meta,
364            "did:wf:owner",
365            "did:wf:owner",
366            1_700_000_000,
367        );
368        assert!(env.id.contains(":clinical_attachment:"));
369        assert_eq!(env.sensitivity, SensitivityClass::Restricted);
370        assert_eq!(env.blob_hash.as_deref(), Some("deadbeef"));
371    }
372
373    #[test]
374    fn unconfirmed_report_is_self_reported_not_clinician_observed() {
375        // A draft / submitted report is the author's claim, NOT clinician evidence.
376        let mut report = ClinicalReport::new(
377            "MRI brain",
378            ClinicalReportType::Imaging,
379            10,
380            "No acute findings.",
381        );
382        for status in [
383            ClaimStatus::Draft,
384            ClaimStatus::Submitted,
385            ClaimStatus::Superseded,
386        ] {
387            report.claim_status = status;
388            let env = build_clinical_report_envelope(&report, "did:wf:o", "did:wf:o", 20, None);
389            assert_eq!(
390                env.evidence_type,
391                EvidenceType::SelfReported,
392                "status {status:?} must not be clinician-observed"
393            );
394            assert_eq!(env.epistemic_status, EpistemicStatus::Asserted);
395        }
396    }
397
398    #[test]
399    fn confirmed_report_maps_to_clinician_observed() {
400        let mut report = ClinicalReport::new("Biopsy", ClinicalReportType::Pathology, 10, "benign");
401        report.claim_status = ClaimStatus::ClinicianConfirmed;
402        let env = build_clinical_report_envelope(&report, "did:wf:o", "did:wf:o", 20, None);
403        assert_eq!(env.evidence_type, EvidenceType::ClinicianObserved);
404        assert_eq!(env.epistemic_status, EpistemicStatus::Asserted);
405    }
406
407    #[test]
408    fn disputed_report_is_surfaced_as_disputed() {
409        let mut report = ClinicalReport::new("Referral", ClinicalReportType::Referral, 10, "…");
410        report.claim_status = ClaimStatus::Disputed;
411        let env = build_clinical_report_envelope(&report, "did:wf:o", "did:wf:o", 20, None);
412        assert_eq!(env.epistemic_status, EpistemicStatus::Disputed);
413        // Disputed is still the author's claim in terms of evidence grade.
414        assert_eq!(env.evidence_type, EvidenceType::SelfReported);
415    }
416
417    #[test]
418    fn draft_cannot_jump_to_clinician_confirmed_without_submission() {
419        // Confirm on a Draft is a no-op — the document must be Submitted first.
420        assert_eq!(
421            advance_claim(ClaimStatus::Draft, ClaimEvent::Confirm),
422            ClaimStatus::Draft
423        );
424        // The legal path: Draft --submit--> Submitted --confirm--> ClinicianConfirmed.
425        let submitted = advance_claim(ClaimStatus::Draft, ClaimEvent::Submit);
426        assert_eq!(submitted, ClaimStatus::Submitted);
427        let confirmed = advance_claim(submitted, ClaimEvent::Confirm);
428        assert_eq!(confirmed, ClaimStatus::ClinicianConfirmed);
429    }
430
431    #[test]
432    fn claim_lifecycle_transitions() {
433        // Dispute from confirmed, then revise back to draft, then round-trip again.
434        let confirmed = ClaimStatus::ClinicianConfirmed;
435        let disputed = advance_claim(confirmed, ClaimEvent::Dispute);
436        assert_eq!(disputed, ClaimStatus::Disputed);
437        let redraft = advance_claim(disputed, ClaimEvent::Revise);
438        assert_eq!(redraft, ClaimStatus::Draft);
439
440        // Supersede a confirmed report.
441        assert_eq!(
442            advance_claim(ClaimStatus::ClinicianConfirmed, ClaimEvent::Supersede),
443            ClaimStatus::Superseded
444        );
445        // A disputed report can be directly confirmed by a clinician.
446        assert_eq!(
447            advance_claim(ClaimStatus::Disputed, ClaimEvent::Confirm),
448            ClaimStatus::ClinicianConfirmed
449        );
450        // Superseded is terminal: any event leaves it unchanged.
451        assert_eq!(
452            advance_claim(ClaimStatus::Superseded, ClaimEvent::Confirm),
453            ClaimStatus::Superseded
454        );
455        assert_eq!(
456            advance_claim(ClaimStatus::Superseded, ClaimEvent::Submit),
457            ClaimStatus::Superseded
458        );
459    }
460
461    #[test]
462    fn report_summary_round_trips() {
463        let mut report = ClinicalReport::new(
464            "Discharge summary",
465            ClinicalReportType::Discharge,
466            1_700_000_000,
467            "Discharged home.",
468        );
469        report.author_label = Some("Ward 3".into());
470        report.attachment_blob_hash = Some("hash123".into());
471        report.claim_status = ClaimStatus::Submitted;
472
473        let summary = clinical_report_summary(&report);
474        let v: serde_json::Value = serde_json::from_str(&summary).unwrap();
475        assert_eq!(v["title"], "Discharge summary");
476        assert_eq!(v["report_type"], "discharge");
477        assert_eq!(v["claim_status"], "submitted");
478        assert_eq!(v["author_label"], "Ward 3");
479        assert_eq!(v["has_attachment"], true);
480        assert_eq!(v["observed_at_unix"], 1_700_000_000u32);
481    }
482
483    #[test]
484    fn attachment_summary_round_trips() {
485        let meta = AttachmentMeta::new("scan.png", "image/png", 4096, "cafebabe");
486        let summary = clinical_attachment_summary(&meta);
487        let v: serde_json::Value = serde_json::from_str(&summary).unwrap();
488        assert_eq!(v["filename"], "scan.png");
489        assert_eq!(v["media_type"], "image/png");
490        assert_eq!(v["byte_len"], 4096u64);
491        assert_eq!(v["content_hash"], "cafebabe");
492    }
493
494    #[test]
495    fn report_type_defaults_to_other() {
496        assert_eq!(ClinicalReportType::default(), ClinicalReportType::Other);
497        assert_eq!(ClaimStatus::default(), ClaimStatus::Draft);
498    }
499}