1use std::path::Path;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use super::super::accessibility_prefs;
7use super::super::consent_store::ConsentGrantRecord;
8use super::super::export_package::{
9 build_export_package, export_policy_receipt, ExportReceipt, HealthExportPackage,
10};
11use super::super::graph_query::GraphCoverageRow;
12use super::super::host_state::WellfairHostSnapshot;
13use super::super::host_state::{
14 AccessibilityPreferences, ConsentGrantDraft, PolicyDecisionDto, SubmitOutcome,
15};
16use super::super::import_samsung::{
17 import_samsung_folder, ingest_companion_health_bundle, SamsungImportReport,
18};
19use super::super::journal::JournalEntry;
20use super::super::policy::{DecisionResult, PolicyDecisionService};
21use super::super::receipt::{receipt_from_decision, ReceiptRecord};
22use super::super::sanctuary::{apply_sanctuary_projection, load_prefs as load_sanctuary_prefs};
23use super::super::snapshot::build_host_snapshot;
24use super::super::sync_outbox::SyncOutboxEntry;
25use super::super::vault::VaultService;
26use ed25519_dalek::SigningKey;
27use qualia_core_db::key_vault::KeyVault;
28use sha2::{Digest, Sha256};
29use wellfare_core::companion_sync::CompanionHealthBundle;
30use wellfare_core::conditions::{
31 allergy_summary, build_allergy_envelope, build_condition_envelope, condition_summary,
32 AllergyReport, ConditionReport,
33};
34use wellfare_core::medication::{
35 self, AdministrationStatus, DietEntry, MedicationAdministration, MedicationCatalogEntry,
36};
37use wellfare_core::personal_records::{
38 build_disputed_diagnosis_envelope, build_housing_safety_envelope, disputed_diagnosis_summary,
39 housing_safety_summary, DisputedDiagnosisReport, HousingSafetyReport,
40};
41use wellfare_core::record::RecordEnvelope;
42
43use super::*;
44
45impl WebizenHostApi {
46 fn preserve_import_q42_artifact(&self, source: &str) -> Result<String, String> {
52 let source_file = self
53 .storage_root
54 .join(super::super::checkpoint_store::Q42_FILE);
55 if !source_file.is_file() {
56 return Err("Q42 checkpoint was not created for this import".to_string());
57 }
58 let artifact_dir = self.storage_root.join("wellfair/imports");
59 std::fs::create_dir_all(&artifact_dir)
60 .map_err(|err| format!("create Q42 import directory: {err}"))?;
61 let safe_source: String = source
62 .chars()
63 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
64 .collect();
65 let filename = format!("{}-{}.q42", safe_source, Self::now_unix());
66 let destination = artifact_dir.join(filename);
67 std::fs::copy(&source_file, &destination)
68 .map_err(|err| format!("write Q42 import artifact: {err}"))?;
69 Ok(destination.display().to_string())
70 }
71
72 pub fn new(
74 vault: VaultService,
75 policy: PolicyDecisionService,
76 signing_key: SigningKey,
77 owner_did: String,
78 author_did: String,
79 storage_root: std::path::PathBuf,
80 ) -> Self {
81 Self {
82 vault,
83 policy,
84 signing_key,
85 owner_did,
86 author_did,
87 storage_root,
88 }
89 }
90
91 pub fn save_accessibility(&self, prefs: &AccessibilityPreferences) -> Result<(), String> {
93 accessibility_prefs::save(&self.storage_root, prefs).map_err(|e| e.to_string())
94 }
95
96 pub fn load_accessibility(&self) -> AccessibilityPreferences {
98 accessibility_prefs::load(&self.storage_root)
99 }
100
101 pub fn snapshot_from_vault(
103 key_vault: &KeyVault,
104 owner_label: &str,
105 demo_mode: bool,
106 ) -> WellfairHostSnapshot {
107 build_host_snapshot(key_vault, true, owner_label, demo_mode)
108 }
109
110 pub fn build_snapshot(
112 &mut self,
113 key_vault: &KeyVault,
114 owner_label: &str,
115 ) -> WellfairHostSnapshot {
116 let mut snap = super::super::snapshot::build_host_snapshot_with_storage(
117 key_vault,
118 true,
119 owner_label,
120 false,
121 Some(&self.storage_root),
122 );
123 if let Ok(count) = self.vault.journal_count() {
124 snap.health_record_count = count as u32;
125 }
126 snap.graph_quin_count = self.vault.graph_quin_count() as u32;
127 if let Ok(pending) = self.vault.wal_buffered_quins() {
128 snap.pending_jobs = pending as u32;
129 snap.sync_state = if pending > 0 {
130 super::super::host_state::SyncQueueState::Queued
131 } else {
132 super::super::host_state::SyncQueueState::Idle
133 };
134 }
135 if let Some(hash) = self.vault.last_checkpoint_hash() {
136 snap.last_checkpoint_prefix = Some(hex::encode(&hash[..4]));
137 }
138 if let Ok(queued) = self.vault.outbox_queued_count() {
139 snap.pending_jobs = snap.pending_jobs.saturating_add(queued as u32);
140 if queued > 0 {
141 snap.sync_state = super::super::host_state::SyncQueueState::Queued;
142 }
143 }
144 snap
145 }
146
147 pub fn fetch_10d_asset_on_demand(&self, _asset_uri: &str) -> Result<Vec<u8>, String> {
149 Ok(Vec::new())
151 }
152
153 pub(crate) fn chora_storage_root(&self) -> &std::path::Path {
155 &self.storage_root
156 }
157
158 pub fn storage_root(&self) -> &std::path::Path {
161 &self.storage_root
162 }
163
164 pub fn owner_did_hash(&self) -> u64 {
166 qualia_core_db::q_hash(&self.owner_did)
167 }
168
169 pub(crate) fn chora_signing_key(&self) -> &SigningKey {
171 &self.signing_key
172 }
173
174 pub(crate) fn chora_owner_did(&self) -> &str {
176 &self.owner_did
177 }
178
179 pub(crate) fn now_unix() -> u64 {
181 SystemTime::now()
182 .duration_since(UNIX_EPOCH)
183 .map(|d| d.as_secs())
184 .unwrap_or(0)
185 }
186
187 pub fn evaluate_policy(
189 &self,
190 qapp_id: &str,
191 requested_scope: &str,
192 sensitivity: wellfare_core::record::SensitivityClass,
193 epistemic: wellfare_core::record::EpistemicStatus,
194 ) -> Result<PolicyDecisionDto, String> {
195 let now = Self::now_unix();
196 let grants = self
197 .vault
198 .list_active_consents(now)
199 .map_err(|e| e.to_string())?;
200 let decision = self.policy.evaluate_access(
201 qapp_id,
202 requested_scope,
203 sensitivity,
204 epistemic,
205 &grants,
206 now,
207 false,
208 );
209 Ok(decision.to_dto())
210 }
211
212 pub fn grant_consent(
214 &mut self,
215 draft: &ConsentGrantDraft,
216 scope: &str,
217 ) -> Result<ConsentGrantRecord, String> {
218 let grant = ConsentGrantRecord::from_draft(draft, scope);
219 self.vault
220 .append_consent(&grant)
221 .map_err(|e| e.to_string())?;
222 let ts = grant.granted_at_unix;
223 let decision = DecisionResult::Permit {
224 obligations: vec!["consent_granted".into(), "emit_wal_receipt".into()],
225 };
226 let receipt = receipt_from_decision(
227 "wellfair-shell",
228 &grant.id,
229 ts,
230 &decision,
231 self.vault.last_checkpoint_hash(),
232 );
233 self.vault
234 .append_receipt(&receipt)
235 .map_err(|e| e.to_string())?;
236 Ok(grant)
237 }
238
239 pub fn revoke_consent(&mut self, grant_id: &str) -> Result<bool, String> {
241 let revoked = self
242 .vault
243 .revoke_consent(grant_id)
244 .map_err(|e| e.to_string())?;
245 if revoked {
246 let ts = Self::now_unix() as u32;
247 let decision = DecisionResult::Deny {
248 reasons: vec!["consent_revoked".into()],
249 };
250 let receipt = receipt_from_decision(
251 "wellfair-shell",
252 grant_id,
253 ts,
254 &decision,
255 self.vault.last_checkpoint_hash(),
256 );
257 self.vault
258 .append_receipt(&receipt)
259 .map_err(|e| e.to_string())?;
260 }
261 Ok(revoked)
262 }
263
264 pub fn list_consents(&self) -> Result<Vec<ConsentGrantRecord>, String> {
266 self.vault
267 .list_active_consents(Self::now_unix())
268 .map_err(|e| e.to_string())
269 }
270
271 pub fn submit_record(
273 &mut self,
274 qapp_id: &str,
275 envelope: RecordEnvelope,
276 source: &str,
277 ) -> Result<usize, String> {
278 self.submit_record_with_summary(qapp_id, envelope, source, None)
279 }
280
281 pub fn submit_record_with_summary(
283 &mut self,
284 qapp_id: &str,
285 envelope: RecordEnvelope,
286 source: &str,
287 summary: Option<String>,
288 ) -> Result<usize, String> {
289 match self.submit_record_guarded(qapp_id, envelope, source, summary)? {
290 SubmitOutcome::Committed { quins } => Ok(quins),
291 SubmitOutcome::Suspended { .. } => {
292 Err("Policy requires guardian approval before write".into())
293 }
294 }
295 }
296
297 pub fn submit_record_guarded(
302 &mut self,
303 qapp_id: &str,
304 envelope: RecordEnvelope,
305 source: &str,
306 summary: Option<String>,
307 ) -> Result<SubmitOutcome, String> {
308 let now = Self::now_unix();
309 let grants = self
310 .vault
311 .list_active_consents(now)
312 .map_err(|e| e.to_string())?;
313 let is_proxy = envelope
314 .proxy_did
315 .as_deref()
316 .map(|p| p != envelope.owner_did)
317 .unwrap_or(false);
318 let decision = self.policy.evaluate_access(
319 qapp_id,
320 "write_record",
321 envelope.sensitivity,
322 envelope.epistemic_status,
323 &grants,
324 now,
325 is_proxy,
326 );
327
328 match &decision {
329 DecisionResult::Deny { reasons } => {
330 Err(format!("Policy denied: {}", reasons.join("; ")))
331 }
332 DecisionResult::Prompt { .. } => Err("Policy requires consent before write".into()),
333 DecisionResult::Suspend { required_approvals } => {
334 let proposal = self.escrow_proxy_write(&envelope, summary, *required_approvals)?;
335 let threshold = proposal.threshold;
336 Ok(SubmitOutcome::Suspended {
337 proposal_id: proposal.id,
338 threshold,
339 })
340 }
341 DecisionResult::Permit { .. } => {
342 let quins =
343 self.commit_permitted(qapp_id, &envelope, source, summary, &decision)?;
344 Ok(SubmitOutcome::Committed { quins })
345 }
346 }
347 }
348
349 pub(crate) fn commit_permitted(
351 &mut self,
352 qapp_id: &str,
353 envelope: &RecordEnvelope,
354 source: &str,
355 summary: Option<String>,
356 decision: &DecisionResult,
357 ) -> Result<usize, String> {
358 let principal_did = qualia_core_db::q_hash(&self.owner_did);
359 let committed = self
360 .vault
361 .commit_envelope(envelope, &self.signing_key, principal_did, source, summary)
362 .map_err(|e| e.to_string())?;
363 let ts = envelope.asserted_instant().to_unix_secs() as u32;
364 let receipt = receipt_from_decision(
365 qapp_id,
366 &envelope.id,
367 ts,
368 decision,
369 self.vault.last_checkpoint_hash(),
370 );
371 self.vault
372 .append_receipt(&receipt)
373 .map_err(|e| e.to_string())?;
374 Ok(committed)
375 }
376
377 pub fn finalize_batch(&mut self) -> Result<String, String> {
379 let hash = self.vault.checkpoint().map_err(|e| e.to_string())?;
380 Ok(hex::encode(hash))
381 }
382
383 pub fn list_health_records(&self, limit: usize) -> Result<Vec<JournalEntry>, String> {
385 let entries = self
386 .vault
387 .list_health_records(limit)
388 .map_err(|e| e.to_string())?;
389 let prefs = load_sanctuary_prefs(&self.storage_root);
390 Ok(apply_sanctuary_projection(&prefs, entries))
391 }
392
393 pub fn list_receipts(&self, limit: usize) -> Result<Vec<ReceiptRecord>, String> {
395 self.vault.list_receipts(limit).map_err(|e| e.to_string())
396 }
397
398 pub fn list_outbox(&self, limit: usize) -> Result<Vec<SyncOutboxEntry>, String> {
400 self.vault.list_outbox(limit).map_err(|e| e.to_string())
401 }
402
403 pub fn export_health_package(
405 &mut self,
406 limit: usize,
407 ) -> Result<(HealthExportPackage, ExportReceipt), String> {
408 self.finalize_batch().ok();
409 let entries = self.list_health_records(limit)?;
410 let exported_at = Self::now_unix() as u32;
411 let pkg = build_export_package(&entries, exported_at, self.vault.last_checkpoint_hash());
412 let receipt = export_policy_receipt(&pkg, exported_at);
413 self.vault
414 .append_receipt(&receipt)
415 .map_err(|e| e.to_string())?;
416 let export_receipt = ExportReceipt::from_package(&pkg);
417 Ok((pkg, export_receipt))
418 }
419
420 pub fn query_graph_coverage(&self, limit: usize) -> Result<Vec<GraphCoverageRow>, String> {
426 let rows = self
427 .vault
428 .graph_coverage(limit)
429 .map_err(|e| e.to_string())?;
430 let prefs = load_sanctuary_prefs(&self.storage_root);
431 if !prefs.enabled || !prefs.locked {
432 return Ok(rows);
433 }
434 Ok(rows
435 .into_iter()
436 .filter(|row| !super::super::sanctuary::is_sanctuary_protected_kind(&row.kind))
437 .collect())
438 }
439
440 pub(crate) fn payload_hash_hex(payload: &str) -> String {
442 hex::encode(Sha256::digest(payload.as_bytes()).as_slice())
443 }
444
445 pub fn add_condition(&mut self, report: &ConditionReport) -> Result<JournalEntry, String> {
447 let payload = serde_json::to_string(report).map_err(|e| e.to_string())?;
448 let hash = Self::payload_hash_hex(&payload);
449 let asserted = Self::now_unix() as u32;
450 let envelope = build_condition_envelope(
451 report,
452 &self.owner_did,
453 &self.author_did,
454 asserted,
455 Some(hash),
456 );
457 let summary = condition_summary(report);
458 self.submit_record_with_summary(QAPP_SHELL, envelope, SOURCE_PERSONAL, Some(summary))?;
459 let entries = self.list_health_records(1)?;
460 entries
461 .into_iter()
462 .next()
463 .ok_or_else(|| "condition committed but not found in journal".to_string())
464 }
465
466 pub fn add_disputed_diagnosis(
468 &mut self,
469 report: &DisputedDiagnosisReport,
470 ) -> Result<JournalEntry, String> {
471 let payload = serde_json::to_string(report).map_err(|e| e.to_string())?;
472 let hash = Self::payload_hash_hex(&payload);
473 let asserted = Self::now_unix() as u32;
474 let envelope = build_disputed_diagnosis_envelope(
475 report,
476 &self.owner_did,
477 &self.author_did,
478 asserted,
479 Some(hash),
480 );
481 let summary = disputed_diagnosis_summary(report);
482 self.submit_record_with_summary(QAPP_SHELL, envelope, SOURCE_PERSONAL, Some(summary))?;
483 self.list_health_records(1)?
484 .into_iter()
485 .next()
486 .ok_or_else(|| "disputed diagnosis committed but not found in journal".to_string())
487 }
488
489 pub fn add_housing_safety(
491 &mut self,
492 report: &HousingSafetyReport,
493 ) -> Result<JournalEntry, String> {
494 let payload = serde_json::to_string(report).map_err(|e| e.to_string())?;
495 let hash = Self::payload_hash_hex(&payload);
496 let asserted = Self::now_unix() as u32;
497 let envelope = build_housing_safety_envelope(
498 report,
499 &self.owner_did,
500 &self.author_did,
501 asserted,
502 Some(hash),
503 );
504 let summary = housing_safety_summary(report);
505 self.submit_record_with_summary(QAPP_SHELL, envelope, SOURCE_PERSONAL, Some(summary))?;
506 self.list_health_records(1)?
507 .into_iter()
508 .next()
509 .ok_or_else(|| "housing/safety committed but not found in journal".to_string())
510 }
511
512 pub fn add_allergy(&mut self, report: &AllergyReport) -> Result<JournalEntry, String> {
514 let payload = serde_json::to_string(report).map_err(|e| e.to_string())?;
515 let hash = Self::payload_hash_hex(&payload);
516 let asserted = Self::now_unix() as u32;
517 let envelope = build_allergy_envelope(
518 report,
519 &self.owner_did,
520 &self.author_did,
521 asserted,
522 Some(hash),
523 );
524 let summary = allergy_summary(report);
525 self.submit_record_with_summary(QAPP_SHELL, envelope, SOURCE_PERSONAL, Some(summary))?;
526 let entries = self.list_health_records(1)?;
527 entries
528 .into_iter()
529 .next()
530 .ok_or_else(|| "allergy committed but not found in journal".to_string())
531 }
532
533 pub fn graph_quin_count(&self) -> usize {
535 self.vault.graph_quin_count()
536 }
537
538 pub fn import_samsung_health_folder(&mut self, folder: &Path) -> SamsungImportReport {
540 let owner = self.owner_did.clone();
541 let author = self.author_did.clone();
542 let mut report = import_samsung_folder(self, folder, &owner, &author);
543 if report.records_committed > 0 {
544 if let Ok(hash) = self.finalize_batch() {
545 report.checkpoint_hash = Some(hash);
546 match self.preserve_import_q42_artifact("device-export") {
547 Ok(path) => report.q42_artifact_path = Some(path),
548 Err(err) => report.errors.push(err),
549 }
550 }
551 }
552 report
553 }
554
555 pub fn ingest_companion_health_bundle(
557 &mut self,
558 bundle: &CompanionHealthBundle,
559 ) -> SamsungImportReport {
560 let owner = self.owner_did.clone();
561 let author = self.author_did.clone();
562 let mut report = ingest_companion_health_bundle(self, bundle, &owner, &author);
563 if report.records_committed > 0 {
564 if let Ok(hash) = self.finalize_batch() {
565 report.checkpoint_hash = Some(hash);
566 match self.preserve_import_q42_artifact("phone-companion") {
567 Ok(path) => report.q42_artifact_path = Some(path),
568 Err(err) => report.errors.push(err),
569 }
570 }
571 }
572 report
573 }
574
575 const QAPP_MEDICATION: &'static str = "wellfair-medication";
576
577 pub fn add_medication(
579 &mut self,
580 name: &str,
581 dose: &str,
582 route: &str,
583 schedule_times: Vec<String>,
584 ) -> Result<JournalEntry, String> {
585 let now = Self::now_unix() as u32;
586 let entry = MedicationCatalogEntry {
587 id: medication::new_medication_id(name, now),
588 name: name.to_string(),
589 dose: dose.to_string(),
590 route: route.to_string(),
591 schedule_times,
592 prescriber: None,
593 ceased_at_unix: None,
594 ceased_at_instant: None,
595 created_at_unix: now,
596 created_at_instant: None,
597 };
598 let packed = medication::medication_envelope(&entry, &self.owner_did, &self.author_did);
599 self.submit_record_with_summary(
600 Self::QAPP_MEDICATION,
601 packed.envelope,
602 "wellfair-medication:ui",
603 Some(packed.summary),
604 )?;
605 self.finalize_batch().ok();
606 self.list_health_records(1)?
607 .into_iter()
608 .next()
609 .ok_or_else(|| "medication committed but journal empty".into())
610 }
611
612 pub fn record_administration(
614 &mut self,
615 medication_id: &str,
616 medication_name: &str,
617 status: AdministrationStatus,
618 notes: Option<String>,
619 ) -> Result<JournalEntry, String> {
620 let now = Self::now_unix() as u32;
621 let admin = MedicationAdministration {
622 id: medication::new_administration_id(medication_id, now),
623 medication_id: medication_id.to_string(),
624 medication_name: medication_name.to_string(),
625 status,
626 administered_at_unix: now,
627 administered_at_instant: None,
628 notes,
629 };
630 let packed = medication::administration_envelope(&admin, &self.owner_did, &self.author_did);
631 self.submit_record_with_summary(
632 Self::QAPP_MEDICATION,
633 packed.envelope,
634 "wellfair-medication:ui",
635 Some(packed.summary),
636 )?;
637 self.finalize_batch().ok();
638 self.list_health_records(1)?
639 .into_iter()
640 .next()
641 .ok_or_else(|| "administration committed but journal empty".into())
642 }
643
644 pub fn add_diet_entry(
646 &mut self,
647 description: &str,
648 meal_type: &str,
649 calories_kcal: Option<u32>,
650 ) -> Result<JournalEntry, String> {
651 let now = Self::now_unix() as u32;
652 let diet = DietEntry {
653 id: medication::new_diet_id(description, now),
654 description: description.to_string(),
655 meal_type: meal_type.to_string(),
656 calories_kcal,
657 logged_at_unix: now,
658 logged_at_instant: None,
659 };
660 let packed = medication::diet_envelope(&diet, &self.owner_did, &self.author_did);
661 self.submit_record_with_summary(
662 Self::QAPP_MEDICATION,
663 packed.envelope,
664 "wellfair-medication:ui",
665 Some(packed.summary),
666 )?;
667 self.finalize_batch().ok();
668 self.list_health_records(1)?
669 .into_iter()
670 .next()
671 .ok_or_else(|| "diet entry committed but journal empty".into())
672 }
673
674 pub fn list_journal_by_kind(
676 &self,
677 kind: &str,
678 limit: usize,
679 ) -> Result<Vec<JournalEntry>, String> {
680 Ok(self
681 .list_health_records(limit)?
682 .into_iter()
683 .filter(|e| e.kind == kind)
684 .collect())
685 }
686
687 pub fn compute_anatomy_view(
693 &self,
694 lens: &str,
695 convergence_threshold: usize,
696 ) -> Result<super::super::anatomy_view::AnatomyViewReport, String> {
697 let conditions = self.list_journal_by_kind("condition", 256)?;
698 let medications = self.list_journal_by_kind("medication", 256)?;
699 let diet = self.list_journal_by_kind("diet", 256)?;
700 let state = self.get_physiological_state();
701 Ok(super::super::anatomy_view::build_report_from_journal(
702 &conditions,
703 &medications,
704 &diet,
705 super::super::anatomy_view::parse_lens(lens),
706 convergence_threshold,
707 state,
708 ))
709 }
710
711 pub fn compute_body_scene(
717 &self,
718 azimuth_deg: f64,
719 elevation_deg: f64,
720 ) -> Result<webizen_render::scene_contract::RenderScene, String> {
721 let report = self.compute_anatomy_view("person", 2)?;
722 let fit = self.body_fit();
723 Ok(super::super::anatomy_render::body_scene_with_fit(
724 &report,
725 azimuth_deg,
726 elevation_deg,
727 &fit,
728 ))
729 }
730}