Skip to main content

qualia_client_core/wellfair/
journal.rs

1//! Append-only WellFair record journal (human-readable projection over WAL commits).
2
3use std::fs::{self, OpenOptions};
4use std::io::{BufRead, BufReader, Write};
5use std::path::{Path, PathBuf};
6
7use serde::{Deserialize, Serialize};
8use wellfare_core::conditions::journal_kind_for_record_id;
9use wellfare_core::record::{InstantBridge, RecordEnvelope};
10
11pub const JOURNAL_FILE: &str = "wellfair/journal.jsonl";
12pub const MAX_LIST: usize = 256;
13
14#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
15pub struct JournalEntry {
16    pub id: String,
17    pub kind: String,
18    pub asserted_time_unix: u32,
19    /// High-resolution asserted instant (T71 one-clock migration).
20    /// Backward-compatible: derived from `asserted_time_unix` on deserialization
21    /// if absent. Eventually `asserted_time_unix` will be deprecated.
22    #[serde(default, skip_serializing_if = "InstantBridge::is_zero")]
23    pub asserted_instant: InstantBridge,
24    pub evidence_type: String,
25    pub sensitivity: String,
26    pub blob_hash: Option<String>,
27    pub source: String,
28    pub committed_unix: u32,
29    /// Compact JSON projection for UI dashboards (sleep duration, weight kg, etc.).
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub summary: Option<String>,
32}
33
34impl JournalEntry {
35    /// Constructs from envelope.
36    pub fn from_envelope(
37        envelope: &RecordEnvelope,
38        source: &str,
39        committed_unix: u32,
40        summary: Option<String>,
41    ) -> Self {
42        let kind = infer_kind(&envelope.id);
43        let instant = envelope.asserted_instant();
44        Self {
45            id: envelope.id.clone(),
46            kind,
47            asserted_time_unix: instant.to_unix_secs() as u32,
48            asserted_instant: instant,
49            evidence_type: format!("{:?}", envelope.evidence_type),
50            sensitivity: format!("{:?}", envelope.sensitivity),
51            blob_hash: envelope.blob_hash.clone(),
52            source: source.to_string(),
53            committed_unix,
54            summary,
55        }
56    }
57}
58
59fn infer_kind(record_id: &str) -> String {
60    journal_kind_for_record_id(record_id).to_string()
61}
62
63pub struct WellfairJournal {
64    path: PathBuf,
65}
66
67impl WellfairJournal {
68    /// Opens.
69    pub fn open(storage_root: impl AsRef<Path>) -> std::io::Result<Self> {
70        let path = storage_root.as_ref().join(JOURNAL_FILE);
71        if let Some(parent) = path.parent() {
72            fs::create_dir_all(parent)?;
73        }
74        if !path.exists() {
75            OpenOptions::new().create(true).write(true).open(&path)?;
76        }
77        Ok(Self { path })
78    }
79
80    /// Appends.
81    pub fn append(&self, entry: &JournalEntry) -> std::io::Result<()> {
82        let line =
83            serde_json::to_string(entry).map_err(|e| std::io::Error::other(e.to_string()))?;
84        let mut file = OpenOptions::new().append(true).open(&self.path)?;
85        writeln!(file, "{line}")?;
86        file.sync_all()?;
87        Ok(())
88    }
89
90    /// Lists recent entries.
91    pub fn list_recent(&self, limit: usize) -> std::io::Result<Vec<JournalEntry>> {
92        let file = fs::File::open(&self.path)?;
93        let reader = BufReader::new(file);
94        let mut entries = Vec::new();
95        for line in reader.lines() {
96            let line = line?;
97            if line.trim().is_empty() {
98                continue;
99            }
100            if let Ok(entry) = serde_json::from_str::<JournalEntry>(&line) {
101                entries.push(entry);
102            }
103        }
104        let keep = limit.min(MAX_LIST);
105        if entries.len() > keep {
106            entries.drain(0..entries.len() - keep);
107        }
108        entries.reverse();
109        Ok(entries)
110    }
111
112    /// Count.
113    pub fn count(&self) -> std::io::Result<usize> {
114        let file = fs::File::open(&self.path)?;
115        Ok(BufReader::new(file)
116            .lines()
117            .filter(|l| l.as_ref().map(|s| !s.trim().is_empty()).unwrap_or(false))
118            .count())
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125    use wellfare_core::record::{EpistemicStatus, EvidenceType, RecordEnvelope, SensitivityClass};
126
127    #[test]
128    fn journal_round_trip() {
129        let dir = tempfile::tempdir().unwrap();
130        let journal = WellfairJournal::open(dir.path()).unwrap();
131        let envelope = RecordEnvelope {
132            id: "urn:wellfair:weight:abc".into(),
133            owner_did: "did:wf:owner".into(),
134            author_did: "did:wf:owner".into(),
135            proxy_did: None,
136            epistemic_status: EpistemicStatus::Asserted,
137            evidence_type: EvidenceType::DeviceMeasured,
138            sensitivity: SensitivityClass::Restricted,
139            asserted_time_unix: 1_700_000_000,
140            asserted_instant: None,
141            valid_time_start_unix: None,
142            valid_time_start_instant: None,
143            valid_time_end_unix: None,
144            valid_time_end_instant: None,
145            predecessor_id: None,
146            blob_hash: Some("deadbeef".into()),
147            tombstone: false,
148        };
149        let entry =
150            JournalEntry::from_envelope(&envelope, "companion:phone-1", 1_700_000_100, None);
151        journal.append(&entry).unwrap();
152        let listed = journal.list_recent(10).unwrap();
153        assert_eq!(listed.len(), 1);
154        assert_eq!(listed[0].kind, "weight");
155        // T71: the asserted_instant should be populated from the bridge
156        assert_eq!(listed[0].asserted_instant.to_unix_secs(), 1_700_000_000);
157    }
158
159    #[test]
160    fn journal_backward_compat_missing_instant() {
161        // An old journal entry without `asserted_instant` should still deserialize
162        let json = r#"{"id":"test","kind":"weight","asserted_time_unix":1700000000,"evidence_type":"DeviceMeasured","sensitivity":"Restricted","blob_hash":null,"source":"test","committed_unix":1700000100,"summary":null}"#;
163        let entry: JournalEntry = serde_json::from_str(json).unwrap();
164        assert_eq!(entry.asserted_time_unix, 1_700_000_000);
165        // asserted_instant defaults to zero (backward compat)
166        assert!(entry.asserted_instant.is_zero());
167    }
168}