1use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
17pub enum MountMode {
18 Before,
20 After,
22 Instead,
24}
25
26#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
27pub struct GluingManifest {
28 pub schemas: Vec<String>,
29 pub b_mcard_expectations: Vec<String>,
30 pub declared_types: Vec<String>,
31}
32
33#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
34pub struct HandleHistoryEntry {
35 pub handle: String,
36 pub old_hash: String,
37 pub new_hash: String,
38 pub timestamp: String,
39 pub agent_did: String,
40}
41
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub struct OkfMount {
44 pub mount_path: String,
45 pub mode: MountMode,
46 pub handles: HashMap<String, String>,
47 pub gluing_manifest: Option<GluingManifest>,
48 pub handle_history: Vec<HandleHistoryEntry>,
49 pub gluing_manifest_type: Option<String>,
51 pub handle_history_type: Option<String>,
53}
54
55fn sha256_hex(input: &str) -> String {
56 crate::hash::raw_hash_string(input)
57}
58
59fn to_handle_name(relative_path: &str) -> String {
60 relative_path.replace('/', ":")
61}
62
63pub fn parse_index_md(content: &str) -> Result<GluingManifest, String> {
70 let mut manifest = GluingManifest::default();
71 for line in content.lines() {
72 let line = line.trim();
73 if line.starts_with("schema:") {
74 manifest.schemas.push(line.strip_prefix("schema:").unwrap().trim().to_string());
75 } else if line.starts_with("b-mcard:") {
76 manifest
77 .b_mcard_expectations
78 .push(line.strip_prefix("b-mcard:").unwrap().trim().to_string());
79 } else if line.starts_with("type:") {
80 manifest
81 .declared_types
82 .push(line.strip_prefix("type:").unwrap().trim().to_string());
83 }
84 }
85 Ok(manifest)
86}
87
88pub fn parse_log_md(content: &str) -> Result<Vec<HandleHistoryEntry>, String> {
93 let mut entries = Vec::new();
94 for line in content.lines() {
95 let line = line.trim();
96 if line.is_empty() {
97 continue;
98 }
99 let parts: Vec<&str> = line.split_whitespace().collect();
100 if parts.len() >= 6 && parts[4] == "->" {
101 entries.push(HandleHistoryEntry {
102 timestamp: parts[0].to_string(),
103 agent_did: parts[1].to_string(),
104 handle: parts[2].to_string(),
105 old_hash: parts[3].to_string(),
106 new_hash: parts[5].to_string(),
107 });
108 }
109 }
110 Ok(entries)
111}
112
113impl OkfMount {
114 pub fn mount(
117 mount_path: &str,
118 mode: MountMode,
119 files: HashMap<String, String>,
120 ) -> Result<Self, String> {
121 let mut handles = HashMap::new();
122 let mut gluing_manifest = None;
123 let mut handle_history = Vec::new();
124
125 for (relative_path, content) in files {
126 if !relative_path.ends_with(".md") {
127 continue;
128 }
129 let hash = sha256_hex(&content);
130 let handle = to_handle_name(&relative_path);
131
132 if relative_path == "index.md" {
133 gluing_manifest = Some(parse_index_md(&content)?);
134 } else if relative_path == "log.md" {
135 handle_history = parse_log_md(&content)?;
136 }
137
138 handles.insert(handle, hash);
139 }
140
141 let gluing_manifest_type = gluing_manifest.as_ref().map(|_| "okf/gluing_manifest".to_string());
142 let handle_history_type = if !handle_history.is_empty() {
143 Some("okf/handle_history".to_string())
144 } else {
145 None
146 };
147
148 Ok(OkfMount {
149 mount_path: mount_path.to_string(),
150 mode,
151 handles,
152 gluing_manifest,
153 handle_history,
154 gluing_manifest_type,
155 handle_history_type,
156 })
157 }
158
159 pub fn unmount(&mut self) -> Result<(), String> {
165 match self.mode {
166 MountMode::Instead => {
167 self.handles.clear();
168 }
169 MountMode::Before | MountMode::After => {
170 for hash in self.handles.values_mut() {
171 if !hash.starts_with("stale:") {
172 *hash = format!("stale:{}", hash);
173 }
174 }
175 }
176 }
177 Ok(())
178 }
179
180 pub fn is_idempotent_with(&self, files: &HashMap<String, String>) -> bool {
182 let remounted = match Self::mount(&self.mount_path, self.mode, files.clone()) {
183 Ok(m) => m,
184 Err(_) => return false,
185 };
186 remounted.handles == self.handles
187 && remounted.gluing_manifest == self.gluing_manifest
188 && remounted.handle_history == self.handle_history
189 && remounted.gluing_manifest_type == self.gluing_manifest_type
190 && remounted.handle_history_type == self.handle_history_type
191 }
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
199pub enum SyncEventType {
200 Created,
201 Updated,
202 Deleted,
203}
204
205#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
206pub struct SyncEvent {
207 pub handle: String,
208 pub old_hash: String,
209 pub new_hash: String,
210 pub event_type: SyncEventType,
211 pub timestamp: String,
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
215pub enum ConflictResolution {
216 McardWins,
217 DiskWins,
218 NoConflict,
219}
220
221#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
222pub struct SyncConflict {
223 pub handle: String,
224 pub disk_hash: String,
225 pub mcard_hash: String,
226 pub resolution: ConflictResolution,
227}
228
229#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
230pub struct SyncReport {
231 pub disk_to_mcard_events: Vec<SyncEvent>,
232 pub mcard_to_disk_events: Vec<SyncEvent>,
233 pub conflicts: Vec<SyncConflict>,
234}
235
236impl OkfMount {
237 pub fn sync_disk_to_mcard(
243 &mut self,
244 files: &HashMap<String, String>,
245 ) -> Result<Vec<SyncEvent>, String> {
246 let now = now_iso();
247 let mut events = Vec::new();
248
249 let mut disk_handles: HashMap<String, String> = HashMap::new();
251 for (relative_path, content) in files {
252 if !relative_path.ends_with(".md") {
253 continue;
254 }
255 let handle = to_handle_name(relative_path);
256 let hash = sha256_hex(content);
257 disk_handles.insert(handle, hash);
258 }
259
260 for (handle, disk_hash) in &disk_handles {
262 match self.handles.get(handle) {
263 None => {
264 events.push(SyncEvent {
265 handle: handle.clone(),
266 old_hash: String::new(),
267 new_hash: disk_hash.clone(),
268 event_type: SyncEventType::Created,
269 timestamp: now.clone(),
270 });
271 self.handles.insert(handle.clone(), disk_hash.clone());
272 }
273 Some(existing) if *existing != *disk_hash && !existing.starts_with("stale:") => {
274 events.push(SyncEvent {
275 handle: handle.clone(),
276 old_hash: existing.clone(),
277 new_hash: disk_hash.clone(),
278 event_type: SyncEventType::Updated,
279 timestamp: now.clone(),
280 });
281 self.handles.insert(handle.clone(), disk_hash.clone());
282 }
283 _ => {}
284 }
285 }
286
287 let deleted_handles: Vec<String> = self
289 .handles
290 .keys()
291 .filter(|h| !disk_handles.contains_key(*h))
292 .filter(|h| !self.handles[*h].starts_with("stale:"))
293 .cloned()
294 .collect();
295 for handle in deleted_handles {
296 let old_hash = self.handles[&handle].clone();
297 events.push(SyncEvent {
298 handle: handle.clone(),
299 old_hash,
300 new_hash: String::new(),
301 event_type: SyncEventType::Deleted,
302 timestamp: now.clone(),
303 });
304 let current = self.handles[&handle].clone();
306 self.handles.insert(handle, format!("stale:{}", current));
307 }
308
309 Ok(events)
310 }
311
312 pub fn sync_mcard_to_disk(
322 &self,
323 files: &HashMap<String, String>,
324 ) -> Result<Vec<SyncEvent>, String> {
325 let now = now_iso();
326 let mut events = Vec::new();
327
328 for (handle, mcard_hash) in &self.handles {
329 if mcard_hash.starts_with("stale:") {
330 continue;
331 }
332 let relative_path = handle.replace(':', "/");
334 let disk_content = files.get(&relative_path);
335 let disk_hash = disk_content.map(|c| sha256_hex(c));
336
337 match disk_hash {
338 None => {
339 events.push(SyncEvent {
341 handle: handle.clone(),
342 old_hash: String::new(),
343 new_hash: mcard_hash.clone(),
344 event_type: SyncEventType::Created,
345 timestamp: now.clone(),
346 });
347 }
348 Some(dh) if dh != *mcard_hash => {
349 events.push(SyncEvent {
351 handle: handle.clone(),
352 old_hash: dh,
353 new_hash: mcard_hash.clone(),
354 event_type: SyncEventType::Updated,
355 timestamp: now.clone(),
356 });
357 }
358 _ => {}
359 }
360 }
361
362 Ok(events)
363 }
364
365 #[cfg(feature = "native")]
376 pub fn sync_mcard_to_disk_write(
377 &self,
378 mount_root: &std::path::Path,
379 content_resolver: &dyn Fn(&str) -> Option<String>,
380 delete_stale: bool,
381 ) -> Result<Vec<SyncEvent>, String> {
382 let now = now_iso();
383 let mut events = Vec::new();
384
385 for (handle, mcard_hash) in &self.handles {
386 let relative_path = handle.replace(':', "/");
387 let file_path = mount_root.join(&relative_path);
388
389 if mcard_hash.starts_with("stale:") {
390 if delete_stale && file_path.exists() {
391 let _ = std::fs::remove_file(&file_path);
392 events.push(SyncEvent {
393 handle: handle.clone(),
394 old_hash: mcard_hash.clone(),
395 new_hash: String::new(),
396 event_type: SyncEventType::Deleted,
397 timestamp: now.clone(),
398 });
399 }
400 continue;
401 }
402
403 let disk_content = std::fs::read_to_string(&file_path).ok();
404 let disk_hash = disk_content.as_ref().map(|c| sha256_hex(c));
405
406 match disk_hash {
407 None => {
408 if let Some(content) = content_resolver(mcard_hash) {
410 if let Some(parent) = file_path.parent() {
411 let _ = std::fs::create_dir_all(parent);
412 }
413 std::fs::write(&file_path, &content)
414 .map_err(|e| format!("Failed to write {}: {}", file_path.display(), e))?;
415 events.push(SyncEvent {
416 handle: handle.clone(),
417 old_hash: String::new(),
418 new_hash: mcard_hash.clone(),
419 event_type: SyncEventType::Created,
420 timestamp: now.clone(),
421 });
422 }
423 }
424 Some(dh) if dh != *mcard_hash => {
425 if let Some(content) = content_resolver(mcard_hash) {
427 std::fs::write(&file_path, &content)
428 .map_err(|e| format!("Failed to update {}: {}", file_path.display(), e))?;
429 events.push(SyncEvent {
430 handle: handle.clone(),
431 old_hash: dh,
432 new_hash: mcard_hash.clone(),
433 event_type: SyncEventType::Updated,
434 timestamp: now.clone(),
435 });
436 }
437 }
438 _ => {}
439 }
440 }
441
442 Ok(events)
443 }
444
445 pub fn sync_bidirectional(
448 &mut self,
449 files: &HashMap<String, String>,
450 ) -> Result<SyncReport, String> {
451 let disk_events = self.sync_disk_to_mcard(files)?;
453
454 let mcard_events = self.sync_mcard_to_disk(files)?;
456
457 let mut conflicts = Vec::new();
462 for event in &disk_events {
463 if event.event_type == SyncEventType::Updated {
464 let mcard_pending = mcard_events.iter().find(|e| e.handle == event.handle);
468 if let Some(me) = mcard_pending {
469 if me.event_type == SyncEventType::Updated {
470 conflicts.push(SyncConflict {
471 handle: event.handle.clone(),
472 disk_hash: event.new_hash.clone(),
473 mcard_hash: me.new_hash.clone(),
474 resolution: ConflictResolution::McardWins,
475 });
476 }
477 }
478 }
479 }
480
481 Ok(SyncReport {
482 disk_to_mcard_events: disk_events,
483 mcard_to_disk_events: mcard_events,
484 conflicts,
485 })
486 }
487
488 pub fn format_log_md(events: &[SyncEvent], agent_did: &str) -> String {
490 let mut lines = Vec::new();
491 for event in events {
492 let arrow = match event.event_type {
493 SyncEventType::Deleted => "->",
494 _ => "->",
495 };
496 lines.push(format!(
497 "{} {} {} {} {} {}",
498 event.timestamp,
499 agent_did,
500 event.handle,
501 event.old_hash,
502 arrow,
503 event.new_hash,
504 ));
505 }
506 lines.join("\n")
507 }
508}
509
510fn now_iso() -> String {
511 #[cfg(feature = "native")]
515 {
516 chrono::Local::now().format("%Y-%m-%dT%H:%M:%S%z").to_string()
517 }
518 #[cfg(not(feature = "native"))]
519 {
520 "1970-01-01T00:00:00Z".to_string()
521 }
522}
523
524#[cfg(test)]
525mod tests {
526 use super::*;
527
528 #[cfg_attr(not(target_arch = "wasm32"), test)]
529 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
530 fn test_mount_registers_md_handles() {
531 let mut files = HashMap::new();
532 files.insert("README.md".to_string(), "# Hello".to_string());
533 files.insert("docs/arch.md".to_string(), "# Arch".to_string());
534 let mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
535 assert!(mount.handles.contains_key("README.md"));
536 assert!(mount.handles.contains_key("docs:arch.md"));
537 assert!(!mount.handles.contains_key("image.png"));
538 }
539
540 #[cfg_attr(not(target_arch = "wasm32"), test)]
541 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
542 fn test_index_md_gluing_manifest() {
543 let mut files = HashMap::new();
544 files.insert(
545 "index.md".to_string(),
546 "schema: a_mcard\nb-mcard: okf:README.md\ntype: okf/gluing_manifest\n".to_string(),
547 );
548 let mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
549 let manifest = mount.gluing_manifest.unwrap();
550 assert_eq!(manifest.schemas, vec!["a_mcard"]);
551 assert_eq!(manifest.b_mcard_expectations, vec!["okf:README.md"]);
552 assert_eq!(manifest.declared_types, vec!["okf/gluing_manifest"]);
553 }
554
555 #[cfg_attr(not(target_arch = "wasm32"), test)]
556 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
557 fn test_log_md_handle_history() {
558 let mut files = HashMap::new();
559 files.insert(
560 "log.md".to_string(),
561 "2026-01-01T00:00:00Z did:key:z1 handle:h1 abc -> def\n".to_string(),
562 );
563 let mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
564 assert_eq!(mount.handle_history.len(), 1);
565 let entry = &mount.handle_history[0];
566 assert_eq!(entry.handle, "handle:h1");
567 assert_eq!(entry.new_hash, "def");
568 }
569
570 #[cfg_attr(not(target_arch = "wasm32"), test)]
571 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
572 fn test_unmount_instead_removes_handles() {
573 let mut files = HashMap::new();
574 files.insert("README.md".to_string(), "# Hello".to_string());
575 let mut mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
576 mount.unmount().unwrap();
577 assert!(mount.handles.is_empty());
578 }
579
580 #[cfg_attr(not(target_arch = "wasm32"), test)]
581 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
582 fn test_unmount_before_marks_stale() {
583 let mut files = HashMap::new();
584 files.insert("README.md".to_string(), "# Hello".to_string());
585 let mut mount = OkfMount::mount("/okf", MountMode::Before, files).unwrap();
586 let original_hash = mount.handles["README.md"].clone();
587 mount.unmount().unwrap();
588 assert_eq!(mount.handles["README.md"], format!("stale:{}", original_hash));
589 }
590
591 #[cfg_attr(not(target_arch = "wasm32"), test)]
592 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
593 fn test_remount_is_idempotent() {
594 let mut files = HashMap::new();
595 files.insert("README.md".to_string(), "# Hello".to_string());
596 let mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
597 assert!(mount.is_idempotent_with(&files));
598 }
599
600 #[cfg_attr(not(target_arch = "wasm32"), test)]
603 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
604 fn test_sync_disk_to_mcard_creates_new() {
605 let mut files = HashMap::new();
606 files.insert("README.md".to_string(), "# Hello".to_string());
607 let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
608
609 let mut updated_files = files.clone();
611 updated_files.insert("docs/new.md".to_string(), "# New".to_string());
612 let events = mount.sync_disk_to_mcard(&updated_files).unwrap();
613 assert_eq!(events.len(), 1);
614 assert_eq!(events[0].event_type, SyncEventType::Created);
615 assert_eq!(events[0].handle, "docs:new.md");
616 }
617
618 #[cfg_attr(not(target_arch = "wasm32"), test)]
619 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
620 fn test_sync_disk_to_mcard_updates_changed() {
621 let mut files = HashMap::new();
622 files.insert("README.md".to_string(), "# Hello".to_string());
623 let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
624
625 let mut updated_files = files.clone();
627 updated_files.insert("README.md".to_string(), "# Updated".to_string());
628 let events = mount.sync_disk_to_mcard(&updated_files).unwrap();
629 assert_eq!(events.len(), 1);
630 assert_eq!(events[0].event_type, SyncEventType::Updated);
631 assert_eq!(events[0].handle, "README.md");
632 }
633
634 #[cfg_attr(not(target_arch = "wasm32"), test)]
635 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
636 fn test_sync_disk_to_mcard_deletes_removed() {
637 let mut files = HashMap::new();
638 files.insert("README.md".to_string(), "# Hello".to_string());
639 files.insert("docs/gone.md".to_string(), "# Gone".to_string());
640 let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
641
642 let mut updated_files = files.clone();
644 updated_files.remove("docs/gone.md");
645 let events = mount.sync_disk_to_mcard(&updated_files).unwrap();
646 assert_eq!(events.len(), 1);
647 assert_eq!(events[0].event_type, SyncEventType::Deleted);
648 assert_eq!(events[0].handle, "docs:gone.md");
649 }
650
651 #[cfg_attr(not(target_arch = "wasm32"), test)]
652 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
653 fn test_sync_mcard_to_disk_detects_diff() {
654 let mut files = HashMap::new();
655 files.insert("README.md".to_string(), "# Hello".to_string());
656 let mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
657
658 let mut mount2 = mount.clone();
660 mount2.handles.insert("README.md".to_string(), sha256_hex("# Different"));
661
662 let events = mount2.sync_mcard_to_disk(&files).unwrap();
663 assert_eq!(events.len(), 1);
664 assert_eq!(events[0].event_type, SyncEventType::Updated);
665 }
666
667 #[cfg_attr(not(target_arch = "wasm32"), test)]
668 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
669 fn test_sync_bidirectional_no_changes() {
670 let mut files = HashMap::new();
671 files.insert("README.md".to_string(), "# Hello".to_string());
672 let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
673 let report = mount.sync_bidirectional(&files).unwrap();
674 assert!(report.disk_to_mcard_events.is_empty());
675 assert!(report.mcard_to_disk_events.is_empty());
676 assert!(report.conflicts.is_empty());
677 }
678
679 #[cfg_attr(not(target_arch = "wasm32"), test)]
680 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
681 fn test_sync_bidirectional_with_disk_change() {
682 let mut files = HashMap::new();
683 files.insert("README.md".to_string(), "# Hello".to_string());
684 let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
685
686 let mut updated = files.clone();
688 updated.insert("README.md".to_string(), "# Updated on disk".to_string());
689 let report = mount.sync_bidirectional(&updated).unwrap();
690 assert_eq!(report.disk_to_mcard_events.len(), 1);
691 assert_eq!(report.disk_to_mcard_events[0].event_type, SyncEventType::Updated);
692 }
693
694 #[cfg_attr(not(target_arch = "wasm32"), test)]
695 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
696 fn test_format_log_md() {
697 let event = SyncEvent {
698 handle: "README.md".to_string(),
699 old_hash: "abc".to_string(),
700 new_hash: "def".to_string(),
701 event_type: SyncEventType::Updated,
702 timestamp: "2026-01-01T00:00:00Z".to_string(),
703 };
704 let log = OkfMount::format_log_md(&[event], "did:key:z123");
705 assert!(log.contains("README.md"));
706 assert!(log.contains("abc"));
707 assert!(log.contains("def"));
708 assert!(log.contains("did:key:z123"));
709 }
710
711 #[cfg_attr(not(target_arch = "wasm32"), test)]
712 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
713 fn test_round_trip_file_mcard_file() {
714 let content = "# Round Trip\nContent here.";
715 let hash = sha256_hex(content);
716 let mut files = HashMap::new();
717 files.insert("concept.md".to_string(), content.to_string());
718 let mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
719
720 let handle_hash = mount.handles.get("concept.md").unwrap();
722 assert_eq!(*handle_hash, hash);
723
724 assert!(mount.is_idempotent_with(&files));
726 }
727}