Skip to main content

qualia_client_core/wellfair/
live_share.rs

1//! Pending companion live-section requests and usage agreements (owner approval gate).
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::live_share::{LiveSectionDecision, LiveSectionRequest, UsageAgreement};
9
10use super::journal::{JournalEntry, WellfairJournal};
11use super::sanctuary::is_sanctuary_protected_kind;
12
13pub const LIVE_SHARE_REQUESTS_FILE: &str = "wellfair/live_share_requests.jsonl";
14pub const USAGE_AGREEMENTS_FILE: &str = "wellfair/usage_agreements.jsonl";
15pub const MAX_PENDING: usize = 64;
16
17#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
18#[serde(rename_all = "snake_case")]
19pub enum LiveShareRequestStatus {
20    Pending,
21    Approved,
22    Denied,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
26pub struct LiveShareRequestRecord {
27    pub request: LiveSectionRequest,
28    pub enqueued_at_unix: u64,
29    pub status: LiveShareRequestStatus,
30    /// Sanctuary-classified kinds present in the request (therapy_note, sanctuary_note, welfare_case).
31    pub classified_kinds: Vec<String>,
32    pub requires_owner_approval: bool,
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub approved: Option<bool>,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub projection_kinds: Option<Vec<String>>,
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub decided_at_unix: Option<u64>,
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub deny_reason: Option<String>,
41}
42
43impl LiveShareRequestRecord {
44    /// Constructs from request.
45    pub fn from_request(request: LiveSectionRequest, enqueued_at_unix: u64) -> Self {
46        let classified_kinds: Vec<String> = request
47            .requested_kinds
48            .iter()
49            .filter(|k| is_sanctuary_protected_kind(k))
50            .cloned()
51            .collect();
52        let requires_owner_approval = !classified_kinds.is_empty();
53        Self {
54            request,
55            enqueued_at_unix,
56            status: LiveShareRequestStatus::Pending,
57            classified_kinds,
58            requires_owner_approval,
59            approved: None,
60            projection_kinds: None,
61            decided_at_unix: None,
62            deny_reason: None,
63        }
64    }
65}
66
67pub struct LiveShareStore {
68    requests_path: PathBuf,
69    agreements_path: PathBuf,
70}
71
72impl LiveShareStore {
73    /// Opens.
74    pub fn open(storage_root: impl AsRef<Path>) -> std::io::Result<Self> {
75        let root = storage_root.as_ref();
76        let requests_path = root.join(LIVE_SHARE_REQUESTS_FILE);
77        let agreements_path = root.join(USAGE_AGREEMENTS_FILE);
78        for path in [&requests_path, &agreements_path] {
79            if let Some(parent) = path.parent() {
80                fs::create_dir_all(parent)?;
81            }
82            if !path.exists() {
83                OpenOptions::new().create(true).write(true).open(path)?;
84            }
85        }
86        Ok(Self {
87            requests_path,
88            agreements_path,
89        })
90    }
91
92    /// Enqueues a live-share request.
93    pub fn enqueue_request(
94        &self,
95        request: LiveSectionRequest,
96        now_unix: u64,
97    ) -> std::io::Result<LiveShareRequestRecord> {
98        let record = LiveShareRequestRecord::from_request(request, now_unix);
99        let line =
100            serde_json::to_string(&record).map_err(|e| std::io::Error::other(e.to_string()))?;
101        let mut file = OpenOptions::new().append(true).open(&self.requests_path)?;
102        writeln!(file, "{line}")?;
103        file.sync_all()?;
104        Ok(record)
105    }
106
107    /// Lists pending requests.
108    pub fn list_pending(&self, limit: usize) -> std::io::Result<Vec<LiveSectionRequest>> {
109        let all = self.load_requests()?;
110        let mut pending: Vec<LiveSectionRequest> = all
111            .into_iter()
112            .filter(|r| r.status == LiveShareRequestStatus::Pending)
113            .map(|r| r.request)
114            .collect();
115        let keep = limit.min(MAX_PENDING).min(pending.len());
116        if pending.len() > keep {
117            pending.drain(0..pending.len() - keep);
118        }
119        pending.reverse();
120        Ok(pending)
121    }
122
123    /// Gets request.
124    pub fn get_request(&self, request_id: &str) -> std::io::Result<Option<LiveShareRequestRecord>> {
125        Ok(self
126            .load_requests()?
127            .into_iter()
128            .find(|r| r.request.id == request_id))
129    }
130
131    /// Decides a pending live-share request (fails on double-decision).
132    pub fn decide(
133        &self,
134        request_id: &str,
135        approved: bool,
136        projection_kinds: &[String],
137        decided_at_unix: u64,
138        deny_reason: Option<&str>,
139    ) -> std::io::Result<LiveShareRequestRecord> {
140        let all = self.load_requests()?;
141        let mut found: Option<LiveShareRequestRecord> = None;
142        let mut rewritten = Vec::with_capacity(all.len());
143        for mut record in all {
144            if record.request.id == request_id {
145                if record.status != LiveShareRequestStatus::Pending {
146                    return Err(std::io::Error::other(format!(
147                        "live share request '{request_id}' already decided"
148                    )));
149                }
150                record.status = if approved {
151                    LiveShareRequestStatus::Approved
152                } else {
153                    LiveShareRequestStatus::Denied
154                };
155                record.approved = Some(approved);
156                record.projection_kinds = if approved {
157                    Some(projection_kinds.to_vec())
158                } else {
159                    Some(vec![])
160                };
161                record.decided_at_unix = Some(decided_at_unix);
162                record.deny_reason = deny_reason.map(str::to_string);
163                found = Some(record.clone());
164            }
165            rewritten.push(record);
166        }
167        let updated = found.ok_or_else(|| {
168            std::io::Error::new(
169                std::io::ErrorKind::NotFound,
170                format!("live share request '{request_id}' not found"),
171            )
172        })?;
173        self.rewrite_requests(&rewritten)?;
174        Ok(updated)
175    }
176
177    /// Saves usage-agreement.
178    pub fn save_usage_agreement(&self, agreement: &UsageAgreement) -> std::io::Result<()> {
179        let line =
180            serde_json::to_string(agreement).map_err(|e| std::io::Error::other(e.to_string()))?;
181        let mut file = OpenOptions::new()
182            .append(true)
183            .open(&self.agreements_path)?;
184        writeln!(file, "{line}")?;
185        file.sync_all()?;
186        Ok(())
187    }
188
189    /// Gets usage-agreement.
190    pub fn get_usage_agreement(&self, device_id: &str) -> std::io::Result<Option<UsageAgreement>> {
191        let file = fs::File::open(&self.agreements_path)?;
192        let reader = BufReader::new(file);
193        let mut latest: Option<UsageAgreement> = None;
194        for line in reader.lines() {
195            let line = line?;
196            if line.trim().is_empty() {
197                continue;
198            }
199            if let Ok(agreement) = serde_json::from_str::<UsageAgreement>(&line) {
200                if agreement.device_id == device_id {
201                    latest = Some(agreement);
202                }
203            }
204        }
205        Ok(latest)
206    }
207
208    fn load_requests(&self) -> std::io::Result<Vec<LiveShareRequestRecord>> {
209        let file = fs::File::open(&self.requests_path)?;
210        let reader = BufReader::new(file);
211        let mut records = Vec::new();
212        for line in reader.lines() {
213            let line = line?;
214            if line.trim().is_empty() {
215                continue;
216            }
217            if let Ok(record) = serde_json::from_str::<LiveShareRequestRecord>(&line) {
218                records.push(record);
219            }
220        }
221        Ok(records)
222    }
223
224    fn rewrite_requests(&self, records: &[LiveShareRequestRecord]) -> std::io::Result<()> {
225        let tmp = self.requests_path.with_extension("jsonl.tmp");
226        {
227            let mut file = OpenOptions::new()
228                .create(true)
229                .write(true)
230                .truncate(true)
231                .open(&tmp)?;
232            for record in records {
233                let line = serde_json::to_string(record)
234                    .map_err(|e| std::io::Error::other(e.to_string()))?;
235                writeln!(file, "{line}")?;
236            }
237            file.sync_all()?;
238        }
239        fs::rename(&tmp, &self.requests_path)?;
240        Ok(())
241    }
242}
243
244/// Fail-closed validation before owner approval: projection kinds must be requested,
245/// and sanctuary-classified kinds require an unlocked (non-decoy) sanctuary session.
246pub fn validate_live_share_decision(
247    record: &LiveShareRequestRecord,
248    approved: bool,
249    projection_kinds: &[String],
250    sanctuary_unlocked: bool,
251) -> Result<(), String> {
252    if !approved {
253        return Ok(());
254    }
255    for kind in projection_kinds {
256        if !record.request.requested_kinds.iter().any(|k| k == kind) {
257            return Err(format!(
258                "projection kind '{kind}' was not in the companion request (fail closed)"
259            ));
260        }
261        if is_sanctuary_protected_kind(kind) && !sanctuary_unlocked {
262            return Err(format!(
263                "sanctuary protected kind '{kind}' requires explicit owner approval after sanctuary unlock"
264            ));
265        }
266    }
267    Ok(())
268}
269
270/// `true` when sanctuary prefs allow classified projection (`enabled && !locked && !decoy_session`).
271pub fn sanctuary_allows_classified_projection(prefs: &super::sanctuary::SanctuaryPrefs) -> bool {
272    prefs.enabled && !prefs.locked && !prefs.decoy_session
273}
274
275/// Journal entry for a live-share request.
276pub fn live_share_request_journal_entry(
277    record: &LiveShareRequestRecord,
278    committed_unix: u32,
279) -> JournalEntry {
280    let sensitivity = if record.requires_owner_approval {
281        "Classified"
282    } else {
283        "Restricted"
284    };
285    JournalEntry {
286        id: format!("urn:wellfair:live_share_request:{}", record.request.id),
287        kind: "live_share_request".into(),
288        asserted_time_unix: record.enqueued_at_unix as u32,
289        asserted_instant: wellfare_core::record::InstantBridge::from_coarse(
290            record.enqueued_at_unix as u32,
291        ),
292        evidence_type: "SelfReported".into(),
293        sensitivity: sensitivity.into(),
294        blob_hash: None,
295        source: "wellfair:live_share".into(),
296        committed_unix,
297        summary: Some(
298            serde_json::json!({
299                "request_id": record.request.id,
300                "device_id": record.request.device_id,
301                "purpose": record.request.purpose,
302                "requested_kinds": record.request.requested_kinds,
303                "classified_kinds": record.classified_kinds,
304                "requires_owner_approval": record.requires_owner_approval,
305            })
306            .to_string(),
307        ),
308    }
309}
310
311/// Journal entry for a live-share decision.
312pub fn live_share_decision_journal_entry(
313    record: &LiveShareRequestRecord,
314    committed_unix: u32,
315) -> JournalEntry {
316    let approved = record.approved.unwrap_or(false);
317    let projection = record.projection_kinds.clone().unwrap_or_default();
318    JournalEntry {
319        id: format!("urn:wellfair:live_share_decision:{}", record.request.id),
320        kind: "live_share_decision".into(),
321        asserted_time_unix: record.decided_at_unix.unwrap_or(0) as u32,
322        asserted_instant: wellfare_core::record::InstantBridge::from_coarse(
323            record.decided_at_unix.unwrap_or(0) as u32,
324        ),
325        evidence_type: "SelfReported".into(),
326        sensitivity: if projection.iter().any(|k| is_sanctuary_protected_kind(k)) {
327            "Classified".into()
328        } else {
329            "Restricted".into()
330        },
331        blob_hash: None,
332        source: "wellfair:live_share".into(),
333        committed_unix,
334        summary: Some(
335            serde_json::json!({
336                "request_id": record.request.id,
337                "device_id": record.request.device_id,
338                "approved": approved,
339                "projection_kinds": projection,
340                "classified_kinds": record.classified_kinds,
341                "deny_reason": record.deny_reason,
342            })
343            .to_string(),
344        ),
345    }
346}
347
348/// Build the companion wire message after owner decision.
349pub fn live_section_decision_from_record(record: &LiveShareRequestRecord) -> LiveSectionDecision {
350    let decided_at = record.decided_at_unix.unwrap_or(0);
351    if record.approved.unwrap_or(false) {
352        LiveSectionDecision::approved(
353            &record.request.id,
354            record.projection_kinds.clone().unwrap_or_default(),
355            decided_at,
356        )
357    } else {
358        LiveSectionDecision::denied(
359            &record.request.id,
360            record
361                .deny_reason
362                .clone()
363                .unwrap_or_else(|| "owner denied live share request".into()),
364            decided_at,
365        )
366    }
367}
368
369/// Appends a live-share journal entry.
370pub fn append_live_share_journal(
371    storage_root: impl AsRef<Path>,
372    entry: &JournalEntry,
373) -> Result<(), String> {
374    WellfairJournal::open(storage_root.as_ref())
375        .map_err(|e| e.to_string())?
376        .append(entry)
377        .map_err(|e| e.to_string())
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383    use wellfare_core::live_share::LiveSectionRequest;
384
385    #[test]
386    fn enqueue_flags_classified_kinds() {
387        let dir = tempfile::tempdir().unwrap();
388        let store = LiveShareStore::open(dir.path()).unwrap();
389        let request = LiveSectionRequest::new(
390            "req-1",
391            "phone-1",
392            "Desktop",
393            "preview",
394            vec!["conditions".into(), "therapy_note".into()],
395            vec![],
396            300,
397        );
398        let record = store.enqueue_request(request, 1_700_000_000).unwrap();
399        assert!(record.requires_owner_approval);
400        assert_eq!(record.classified_kinds, vec!["therapy_note"]);
401        let pending = store.list_pending(8).unwrap();
402        assert_eq!(pending.len(), 1);
403        assert_eq!(pending[0].id, "req-1");
404    }
405
406    #[test]
407    fn usage_agreement_latest_per_device() {
408        let dir = tempfile::tempdir().unwrap();
409        let store = LiveShareStore::open(dir.path()).unwrap();
410        let first = UsageAgreement::new("phone-1", "vitals", vec!["sleep".into()], 100, 50);
411        let second = UsageAgreement::new(
412            "phone-1",
413            "vitals v2",
414            vec!["sleep".into(), "steps".into()],
415            200,
416            150,
417        );
418        store.save_usage_agreement(&first).unwrap();
419        store.save_usage_agreement(&second).unwrap();
420        let got = store.get_usage_agreement("phone-1").unwrap().unwrap();
421        assert_eq!(got.purpose, "vitals v2");
422    }
423}