Skip to main content

clm_rust_core/
okf_adapter.rs

1//! OKF adapter grounding scaffold for Stage 6.
2//!
3//! This module provides an in-memory OKF directory-to-handle mapper that is
4//! safe for both native and WASM builds. It avoids direct filesystem access;
5//! instead the caller supplies a map of relative-path -> content.
6//!
7//! It implements the core stories from Sprint 139.6 Story 1:
8//! - Mount an OKF directory and register `.md` files as handles.
9//! - Parse `index.md` as a gluing manifest.
10//! - Parse `log.md` as a handle history trace.
11//! - Unmount with Before/After/Instead semantics.
12
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
17pub enum MountMode {
18    /// Keep old handle namespace before this mount.
19    Before,
20    /// Layer this mount after existing handles (overlay).
21    After,
22    /// Replace existing handles entirely.
23    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    /// Special MCard type tag for the gluing manifest (e.g., "okf/gluing_manifest").
50    pub gluing_manifest_type: Option<String>,
51    /// Special MCard type tag for the handle history (e.g., "okf/handle_history").
52    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
63/// Parse `index.md` content into a `GluingManifest`.
64///
65/// Recognizes lines like:
66/// - `schema: <name>`
67/// - `b-mcard: <expectation>`
68/// - `type: <name>`
69pub 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
88/// Parse `log.md` content into a list of handle history entries.
89///
90/// Recognizes lines like:
91/// - `<timestamp> <agent_did> <handle> <old_hash> -> <new_hash>`
92pub 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    /// Mount an OKF directory represented by an in-memory map of
115    /// relative-path -> content.
116    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    /// Unmount the OKF directory. Depending on mode this removes handles
160    /// (`Instead`) or marks them stale (`Before`/`After`).
161    ///
162    /// In the in-memory scaffold, `Before`/`After` keep the handles but flag
163    /// them as stale by prefixing their hash with `stale:`.
164    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    /// Re-mount an unchanged directory and verify hashes are unchanged.
181    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// ─────────────────────────────────────────────────────────────────────
195// Bidirectional Sync (Story 139.6.2)
196// ─────────────────────────────────────────────────────────────────────
197
198#[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    /// Sync disk files to MCard handles.
238    ///
239    /// Walks the provided files map, computes SHA-256 for each file,
240    /// and compares against the mount's registered handle hashes.
241    /// Returns sync events for created/updated/deleted files.
242    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        // Build a map of expected handles from the files map.
250        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        // Detect created and updated handles.
261        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        // Detect deleted handles (in mount but not on disk).
288        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            // Mark as stale rather than removing (preserves history).
305            let current = self.handles[&handle].clone();
306            self.handles.insert(handle, format!("stale:{}", current));
307        }
308
309        Ok(events)
310    }
311
312    /// Sync MCard handles to disk files.
313    ///
314    /// For each handle in the mount, if the handle's hash differs from
315    /// the file on disk, the file content should be updated. Returns
316    /// sync events for files that need updating.
317    ///
318    /// Since this module is filesystem-agnostic (works with in-memory
319    /// maps), this function returns the events that *would* be written.
320    /// The caller is responsible for actually writing files to disk.
321    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            // Convert handle back to relative path.
333            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                    // File doesn't exist on disk — would be created.
340                    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                    // File exists but hash differs — would be updated.
350                    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    /// Sync MCard handles to disk files (native mode — actually writes files).
366    ///
367    /// For each handle in the mount:
368    /// - If MCard content differs from file on disk: write new content to file.
369    /// - If handle has no corresponding file: create the file.
370    /// - If handle is stale: delete the file (configurable via `delete_stale`).
371    ///
372    /// This is the native-mode counterpart to `sync_mcard_to_disk` which only
373    /// returns events. This method requires a `content_resolver` callback to
374    /// fetch MCard content by hash from the content_memory pillar.
375    #[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                    // File doesn't exist on disk — create it.
409                    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                    // File exists but hash differs — update it.
426                    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    /// Bidirectional sync: first disk-to-MCard, then MCard-to-disk.
446    /// Detects conflicts where both sides changed since last sync.
447    pub fn sync_bidirectional(
448        &mut self,
449        files: &HashMap<String, String>,
450    ) -> Result<SyncReport, String> {
451        // Phase 1: Detect what changed on disk vs. current handles.
452        let disk_events = self.sync_disk_to_mcard(files)?;
453
454        // Phase 2: Detect what would need to go back to disk.
455        let mcard_events = self.sync_mcard_to_disk(files)?;
456
457        // Phase 3: Detect conflicts — handles where both disk and MCard
458        // changed. Since sync_disk_to_mcard already updated the handles,
459        // conflicts are cases where the old_hash (before sync) differed
460        // from both the disk hash and the new MCard hash.
461        let mut conflicts = Vec::new();
462        for event in &disk_events {
463            if event.event_type == SyncEventType::Updated {
464                // A conflict would be if the MCard side also had a pending
465                // update for the same handle. In our model, the MCard
466                // (content-addressed truth) wins.
467                let mcard_pending = mcard_events.iter().find(|e| e.handle == event.handle);
468                if let Some(me) = mcard_pending
469                    && 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        Ok(SyncReport {
481            disk_to_mcard_events: disk_events,
482            mcard_to_disk_events: mcard_events,
483            conflicts,
484        })
485    }
486
487    /// Format sync events as log.md entries.
488    pub fn format_log_md(events: &[SyncEvent], agent_did: &str) -> String {
489        let mut lines = Vec::new();
490        for event in events {
491            let arrow = match event.event_type {
492                SyncEventType::Deleted => "->",
493                _ => "->",
494            };
495            lines.push(format!(
496                "{} {} {} {} {} {}",
497                event.timestamp,
498                agent_did,
499                event.handle,
500                event.old_hash,
501                arrow,
502                event.new_hash,
503            ));
504        }
505        lines.join("\n")
506    }
507}
508
509fn now_iso() -> String {
510    // Use a simple timestamp for WASM compatibility.
511    // In native mode, chrono is available but for cross-platform
512    // consistency we use a simple counter-based approach.
513    #[cfg(feature = "native")]
514    {
515        chrono::Local::now().format("%Y-%m-%dT%H:%M:%S%z").to_string()
516    }
517    #[cfg(not(feature = "native"))]
518    {
519        "1970-01-01T00:00:00Z".to_string()
520    }
521}
522
523#[cfg(test)]
524mod tests {
525    use super::*;
526
527    #[cfg_attr(not(target_arch = "wasm32"), test)]
528    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
529    fn test_mount_registers_md_handles() {
530        let mut files = HashMap::new();
531        files.insert("README.md".to_string(), "# Hello".to_string());
532        files.insert("docs/arch.md".to_string(), "# Arch".to_string());
533        let mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
534        assert!(mount.handles.contains_key("README.md"));
535        assert!(mount.handles.contains_key("docs:arch.md"));
536        assert!(!mount.handles.contains_key("image.png"));
537    }
538
539    #[cfg_attr(not(target_arch = "wasm32"), test)]
540    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
541    fn test_index_md_gluing_manifest() {
542        let mut files = HashMap::new();
543        files.insert(
544            "index.md".to_string(),
545            "schema: a_mcard\nb-mcard: okf:README.md\ntype: okf/gluing_manifest\n".to_string(),
546        );
547        let mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
548        let manifest = mount.gluing_manifest.unwrap();
549        assert_eq!(manifest.schemas, vec!["a_mcard"]);
550        assert_eq!(manifest.b_mcard_expectations, vec!["okf:README.md"]);
551        assert_eq!(manifest.declared_types, vec!["okf/gluing_manifest"]);
552    }
553
554    #[cfg_attr(not(target_arch = "wasm32"), test)]
555    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
556    fn test_log_md_handle_history() {
557        let mut files = HashMap::new();
558        files.insert(
559            "log.md".to_string(),
560            "2026-01-01T00:00:00Z did:key:z1 handle:h1 abc -> def\n".to_string(),
561        );
562        let mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
563        assert_eq!(mount.handle_history.len(), 1);
564        let entry = &mount.handle_history[0];
565        assert_eq!(entry.handle, "handle:h1");
566        assert_eq!(entry.new_hash, "def");
567    }
568
569    #[cfg_attr(not(target_arch = "wasm32"), test)]
570    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
571    fn test_unmount_instead_removes_handles() {
572        let mut files = HashMap::new();
573        files.insert("README.md".to_string(), "# Hello".to_string());
574        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
575        mount.unmount().unwrap();
576        assert!(mount.handles.is_empty());
577    }
578
579    #[cfg_attr(not(target_arch = "wasm32"), test)]
580    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
581    fn test_unmount_before_marks_stale() {
582        let mut files = HashMap::new();
583        files.insert("README.md".to_string(), "# Hello".to_string());
584        let mut mount = OkfMount::mount("/okf", MountMode::Before, files).unwrap();
585        let original_hash = mount.handles["README.md"].clone();
586        mount.unmount().unwrap();
587        assert_eq!(mount.handles["README.md"], format!("stale:{}", original_hash));
588    }
589
590    #[cfg_attr(not(target_arch = "wasm32"), test)]
591    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
592    fn test_remount_is_idempotent() {
593        let mut files = HashMap::new();
594        files.insert("README.md".to_string(), "# Hello".to_string());
595        let mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
596        assert!(mount.is_idempotent_with(&files));
597    }
598
599    // ── Bidirectional Sync tests (Story 139.6.2) ──
600
601    #[cfg_attr(not(target_arch = "wasm32"), test)]
602    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
603    fn test_sync_disk_to_mcard_creates_new() {
604        let mut files = HashMap::new();
605        files.insert("README.md".to_string(), "# Hello".to_string());
606        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
607
608        // Add a new file
609        let mut updated_files = files.clone();
610        updated_files.insert("docs/new.md".to_string(), "# New".to_string());
611        let events = mount.sync_disk_to_mcard(&updated_files).unwrap();
612        assert_eq!(events.len(), 1);
613        assert_eq!(events[0].event_type, SyncEventType::Created);
614        assert_eq!(events[0].handle, "docs:new.md");
615    }
616
617    #[cfg_attr(not(target_arch = "wasm32"), test)]
618    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
619    fn test_sync_disk_to_mcard_updates_changed() {
620        let mut files = HashMap::new();
621        files.insert("README.md".to_string(), "# Hello".to_string());
622        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
623
624        // Modify the file
625        let mut updated_files = files.clone();
626        updated_files.insert("README.md".to_string(), "# Updated".to_string());
627        let events = mount.sync_disk_to_mcard(&updated_files).unwrap();
628        assert_eq!(events.len(), 1);
629        assert_eq!(events[0].event_type, SyncEventType::Updated);
630        assert_eq!(events[0].handle, "README.md");
631    }
632
633    #[cfg_attr(not(target_arch = "wasm32"), test)]
634    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
635    fn test_sync_disk_to_mcard_deletes_removed() {
636        let mut files = HashMap::new();
637        files.insert("README.md".to_string(), "# Hello".to_string());
638        files.insert("docs/gone.md".to_string(), "# Gone".to_string());
639        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
640
641        // Remove a file
642        let mut updated_files = files.clone();
643        updated_files.remove("docs/gone.md");
644        let events = mount.sync_disk_to_mcard(&updated_files).unwrap();
645        assert_eq!(events.len(), 1);
646        assert_eq!(events[0].event_type, SyncEventType::Deleted);
647        assert_eq!(events[0].handle, "docs:gone.md");
648    }
649
650    #[cfg_attr(not(target_arch = "wasm32"), test)]
651    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
652    fn test_sync_mcard_to_disk_detects_diff() {
653        let mut files = HashMap::new();
654        files.insert("README.md".to_string(), "# Hello".to_string());
655        let mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
656
657        // Simulate MCard handle being updated (not on disk)
658        let mut mount2 = mount.clone();
659        mount2.handles.insert("README.md".to_string(), sha256_hex("# Different"));
660
661        let events = mount2.sync_mcard_to_disk(&files).unwrap();
662        assert_eq!(events.len(), 1);
663        assert_eq!(events[0].event_type, SyncEventType::Updated);
664    }
665
666    #[cfg_attr(not(target_arch = "wasm32"), test)]
667    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
668    fn test_sync_bidirectional_no_changes() {
669        let mut files = HashMap::new();
670        files.insert("README.md".to_string(), "# Hello".to_string());
671        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
672        let report = mount.sync_bidirectional(&files).unwrap();
673        assert!(report.disk_to_mcard_events.is_empty());
674        assert!(report.mcard_to_disk_events.is_empty());
675        assert!(report.conflicts.is_empty());
676    }
677
678    #[cfg_attr(not(target_arch = "wasm32"), test)]
679    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
680    fn test_sync_bidirectional_with_disk_change() {
681        let mut files = HashMap::new();
682        files.insert("README.md".to_string(), "# Hello".to_string());
683        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
684
685        // Change on disk
686        let mut updated = files.clone();
687        updated.insert("README.md".to_string(), "# Updated on disk".to_string());
688        let report = mount.sync_bidirectional(&updated).unwrap();
689        assert_eq!(report.disk_to_mcard_events.len(), 1);
690        assert_eq!(report.disk_to_mcard_events[0].event_type, SyncEventType::Updated);
691    }
692
693    #[cfg_attr(not(target_arch = "wasm32"), test)]
694    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
695    fn test_format_log_md() {
696        let event = SyncEvent {
697            handle: "README.md".to_string(),
698            old_hash: "abc".to_string(),
699            new_hash: "def".to_string(),
700            event_type: SyncEventType::Updated,
701            timestamp: "2026-01-01T00:00:00Z".to_string(),
702        };
703        let log = OkfMount::format_log_md(&[event], "did:key:z123");
704        assert!(log.contains("README.md"));
705        assert!(log.contains("abc"));
706        assert!(log.contains("def"));
707        assert!(log.contains("did:key:z123"));
708    }
709
710    #[cfg_attr(not(target_arch = "wasm32"), test)]
711    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
712    fn test_round_trip_file_mcard_file() {
713        let content = "# Round Trip\nContent here.";
714        let hash = sha256_hex(content);
715        let mut files = HashMap::new();
716        files.insert("concept.md".to_string(), content.to_string());
717        let mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
718
719        // The handle hash should match the file hash
720        let handle_hash = mount.handles.get("concept.md").unwrap();
721        assert_eq!(*handle_hash, hash);
722
723        // Re-mounting should produce the same hash (idempotent)
724        assert!(mount.is_idempotent_with(&files));
725    }
726}