clm-kernel 0.0.6

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! OKF adapter grounding scaffold for Stage 6.
//!
//! This module provides an in-memory OKF directory-to-handle mapper that is
//! safe for both native and WASM builds. It avoids direct filesystem access;
//! instead the caller supplies a map of relative-path -> content.
//!
//! It implements the core stories from Sprint 139.6 Story 1:
//! - Mount an OKF directory and register `.md` files as handles.
//! - Parse `index.md` as a gluing manifest.
//! - Parse `log.md` as a handle history trace.
//! - Unmount with Before/After/Instead semantics.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MountMode {
    /// Keep old handle namespace before this mount.
    Before,
    /// Layer this mount after existing handles (overlay).
    After,
    /// Replace existing handles entirely.
    Instead,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct GluingManifest {
    pub schemas: Vec<String>,
    pub b_mcard_expectations: Vec<String>,
    pub declared_types: Vec<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct HandleHistoryEntry {
    pub handle: String,
    pub old_hash: String,
    pub new_hash: String,
    pub timestamp: String,
    pub agent_did: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OkfMount {
    pub mount_path: String,
    pub mode: MountMode,
    pub handles: HashMap<String, String>,
    pub gluing_manifest: Option<GluingManifest>,
    pub handle_history: Vec<HandleHistoryEntry>,
    /// Special MCard type tag for the gluing manifest (e.g., "okf/gluing_manifest").
    pub gluing_manifest_type: Option<String>,
    /// Special MCard type tag for the handle history (e.g., "okf/handle_history").
    pub handle_history_type: Option<String>,
}

fn sha256_hex(input: &str) -> String {
    crate::hash::raw_hash_string(input)
}

fn to_handle_name(relative_path: &str) -> String {
    relative_path.replace('/', ":")
}

/// Parse `index.md` content into a `GluingManifest`.
///
/// Recognizes lines like:
/// - `schema: <name>`
/// - `b-mcard: <expectation>`
/// - `type: <name>`
pub fn parse_index_md(content: &str) -> Result<GluingManifest, String> {
    let mut manifest = GluingManifest::default();
    for line in content.lines() {
        let line = line.trim();
        if line.starts_with("schema:") {
            manifest.schemas.push(line.strip_prefix("schema:").unwrap().trim().to_string());
        } else if line.starts_with("b-mcard:") {
            manifest
                .b_mcard_expectations
                .push(line.strip_prefix("b-mcard:").unwrap().trim().to_string());
        } else if line.starts_with("type:") {
            manifest
                .declared_types
                .push(line.strip_prefix("type:").unwrap().trim().to_string());
        }
    }
    Ok(manifest)
}

/// Parse `log.md` content into a list of handle history entries.
///
/// Recognizes lines like:
/// - `<timestamp> <agent_did> <handle> <old_hash> -> <new_hash>`
pub fn parse_log_md(content: &str) -> Result<Vec<HandleHistoryEntry>, String> {
    let mut entries = Vec::new();
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 6 && parts[4] == "->" {
            entries.push(HandleHistoryEntry {
                timestamp: parts[0].to_string(),
                agent_did: parts[1].to_string(),
                handle: parts[2].to_string(),
                old_hash: parts[3].to_string(),
                new_hash: parts[5].to_string(),
            });
        }
    }
    Ok(entries)
}

impl OkfMount {
    /// Mount an OKF directory represented by an in-memory map of
    /// relative-path -> content.
    pub fn mount(
        mount_path: &str,
        mode: MountMode,
        files: HashMap<String, String>,
    ) -> Result<Self, String> {
        let mut handles = HashMap::new();
        let mut gluing_manifest = None;
        let mut handle_history = Vec::new();

        for (relative_path, content) in files {
            if !relative_path.ends_with(".md") {
                continue;
            }
            let hash = sha256_hex(&content);
            let handle = to_handle_name(&relative_path);

            if relative_path == "index.md" {
                gluing_manifest = Some(parse_index_md(&content)?);
            } else if relative_path == "log.md" {
                handle_history = parse_log_md(&content)?;
            }

            handles.insert(handle, hash);
        }

        let gluing_manifest_type = gluing_manifest.as_ref().map(|_| "okf/gluing_manifest".to_string());
        let handle_history_type = if !handle_history.is_empty() {
            Some("okf/handle_history".to_string())
        } else {
            None
        };

        Ok(OkfMount {
            mount_path: mount_path.to_string(),
            mode,
            handles,
            gluing_manifest,
            handle_history,
            gluing_manifest_type,
            handle_history_type,
        })
    }

    /// Unmount the OKF directory. Depending on mode this removes handles
    /// (`Instead`) or marks them stale (`Before`/`After`).
    ///
    /// In the in-memory scaffold, `Before`/`After` keep the handles but flag
    /// them as stale by prefixing their hash with `stale:`.
    pub fn unmount(&mut self) -> Result<(), String> {
        match self.mode {
            MountMode::Instead => {
                self.handles.clear();
            }
            MountMode::Before | MountMode::After => {
                for hash in self.handles.values_mut() {
                    if !hash.starts_with("stale:") {
                        *hash = format!("stale:{}", hash);
                    }
                }
            }
        }
        Ok(())
    }

    /// Re-mount an unchanged directory and verify hashes are unchanged.
    pub fn is_idempotent_with(&self, files: &HashMap<String, String>) -> bool {
        let remounted = match Self::mount(&self.mount_path, self.mode, files.clone()) {
            Ok(m) => m,
            Err(_) => return false,
        };
        remounted.handles == self.handles
            && remounted.gluing_manifest == self.gluing_manifest
            && remounted.handle_history == self.handle_history
            && remounted.gluing_manifest_type == self.gluing_manifest_type
            && remounted.handle_history_type == self.handle_history_type
    }
}

// ─────────────────────────────────────────────────────────────────────
// Bidirectional Sync (Story 139.6.2)
// ─────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SyncEventType {
    Created,
    Updated,
    Deleted,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SyncEvent {
    pub handle: String,
    pub old_hash: String,
    pub new_hash: String,
    pub event_type: SyncEventType,
    pub timestamp: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConflictResolution {
    McardWins,
    DiskWins,
    NoConflict,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SyncConflict {
    pub handle: String,
    pub disk_hash: String,
    pub mcard_hash: String,
    pub resolution: ConflictResolution,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct SyncReport {
    pub disk_to_mcard_events: Vec<SyncEvent>,
    pub mcard_to_disk_events: Vec<SyncEvent>,
    pub conflicts: Vec<SyncConflict>,
}

impl OkfMount {
    /// Sync disk files to MCard handles.
    ///
    /// Walks the provided files map, computes SHA-256 for each file,
    /// and compares against the mount's registered handle hashes.
    /// Returns sync events for created/updated/deleted files.
    pub fn sync_disk_to_mcard(
        &mut self,
        files: &HashMap<String, String>,
    ) -> Result<Vec<SyncEvent>, String> {
        let now = now_iso();
        let mut events = Vec::new();

        // Build a map of expected handles from the files map.
        let mut disk_handles: HashMap<String, String> = HashMap::new();
        for (relative_path, content) in files {
            if !relative_path.ends_with(".md") {
                continue;
            }
            let handle = to_handle_name(relative_path);
            let hash = sha256_hex(content);
            disk_handles.insert(handle, hash);
        }

        // Detect created and updated handles.
        for (handle, disk_hash) in &disk_handles {
            match self.handles.get(handle) {
                None => {
                    events.push(SyncEvent {
                        handle: handle.clone(),
                        old_hash: String::new(),
                        new_hash: disk_hash.clone(),
                        event_type: SyncEventType::Created,
                        timestamp: now.clone(),
                    });
                    self.handles.insert(handle.clone(), disk_hash.clone());
                }
                Some(existing) if *existing != *disk_hash && !existing.starts_with("stale:") => {
                    events.push(SyncEvent {
                        handle: handle.clone(),
                        old_hash: existing.clone(),
                        new_hash: disk_hash.clone(),
                        event_type: SyncEventType::Updated,
                        timestamp: now.clone(),
                    });
                    self.handles.insert(handle.clone(), disk_hash.clone());
                }
                _ => {}
            }
        }

        // Detect deleted handles (in mount but not on disk).
        let deleted_handles: Vec<String> = self
            .handles
            .keys()
            .filter(|h| !disk_handles.contains_key(*h))
            .filter(|h| !self.handles[*h].starts_with("stale:"))
            .cloned()
            .collect();
        for handle in deleted_handles {
            let old_hash = self.handles[&handle].clone();
            events.push(SyncEvent {
                handle: handle.clone(),
                old_hash,
                new_hash: String::new(),
                event_type: SyncEventType::Deleted,
                timestamp: now.clone(),
            });
            // Mark as stale rather than removing (preserves history).
            let current = self.handles[&handle].clone();
            self.handles.insert(handle, format!("stale:{}", current));
        }

        Ok(events)
    }

    /// Sync MCard handles to disk files.
    ///
    /// For each handle in the mount, if the handle's hash differs from
    /// the file on disk, the file content should be updated. Returns
    /// sync events for files that need updating.
    ///
    /// Since this module is filesystem-agnostic (works with in-memory
    /// maps), this function returns the events that *would* be written.
    /// The caller is responsible for actually writing files to disk.
    pub fn sync_mcard_to_disk(
        &self,
        files: &HashMap<String, String>,
    ) -> Result<Vec<SyncEvent>, String> {
        let now = now_iso();
        let mut events = Vec::new();

        for (handle, mcard_hash) in &self.handles {
            if mcard_hash.starts_with("stale:") {
                continue;
            }
            // Convert handle back to relative path.
            let relative_path = handle.replace(':', "/");
            let disk_content = files.get(&relative_path);
            let disk_hash = disk_content.map(|c| sha256_hex(c));

            match disk_hash {
                None => {
                    // File doesn't exist on disk — would be created.
                    events.push(SyncEvent {
                        handle: handle.clone(),
                        old_hash: String::new(),
                        new_hash: mcard_hash.clone(),
                        event_type: SyncEventType::Created,
                        timestamp: now.clone(),
                    });
                }
                Some(dh) if dh != *mcard_hash => {
                    // File exists but hash differs — would be updated.
                    events.push(SyncEvent {
                        handle: handle.clone(),
                        old_hash: dh,
                        new_hash: mcard_hash.clone(),
                        event_type: SyncEventType::Updated,
                        timestamp: now.clone(),
                    });
                }
                _ => {}
            }
        }

        Ok(events)
    }

    /// Sync MCard handles to disk files (native mode — actually writes files).
    ///
    /// For each handle in the mount:
    /// - If MCard content differs from file on disk: write new content to file.
    /// - If handle has no corresponding file: create the file.
    /// - If handle is stale: delete the file (configurable via `delete_stale`).
    ///
    /// This is the native-mode counterpart to `sync_mcard_to_disk` which only
    /// returns events. This method requires a `content_resolver` callback to
    /// fetch MCard content by hash from the content_memory pillar.
    #[cfg(feature = "native")]
    pub fn sync_mcard_to_disk_write(
        &self,
        mount_root: &std::path::Path,
        content_resolver: &dyn Fn(&str) -> Option<String>,
        delete_stale: bool,
    ) -> Result<Vec<SyncEvent>, String> {
        let now = now_iso();
        let mut events = Vec::new();

        for (handle, mcard_hash) in &self.handles {
            let relative_path = handle.replace(':', "/");
            let file_path = mount_root.join(&relative_path);

            if mcard_hash.starts_with("stale:") {
                if delete_stale && file_path.exists() {
                    let _ = std::fs::remove_file(&file_path);
                    events.push(SyncEvent {
                        handle: handle.clone(),
                        old_hash: mcard_hash.clone(),
                        new_hash: String::new(),
                        event_type: SyncEventType::Deleted,
                        timestamp: now.clone(),
                    });
                }
                continue;
            }

            let disk_content = std::fs::read_to_string(&file_path).ok();
            let disk_hash = disk_content.as_ref().map(|c| sha256_hex(c));

            match disk_hash {
                None => {
                    // File doesn't exist on disk — create it.
                    if let Some(content) = content_resolver(mcard_hash) {
                        if let Some(parent) = file_path.parent() {
                            let _ = std::fs::create_dir_all(parent);
                        }
                        std::fs::write(&file_path, &content)
                            .map_err(|e| format!("Failed to write {}: {}", file_path.display(), e))?;
                        events.push(SyncEvent {
                            handle: handle.clone(),
                            old_hash: String::new(),
                            new_hash: mcard_hash.clone(),
                            event_type: SyncEventType::Created,
                            timestamp: now.clone(),
                        });
                    }
                }
                Some(dh) if dh != *mcard_hash => {
                    // File exists but hash differs — update it.
                    if let Some(content) = content_resolver(mcard_hash) {
                        std::fs::write(&file_path, &content)
                            .map_err(|e| format!("Failed to update {}: {}", file_path.display(), e))?;
                        events.push(SyncEvent {
                            handle: handle.clone(),
                            old_hash: dh,
                            new_hash: mcard_hash.clone(),
                            event_type: SyncEventType::Updated,
                            timestamp: now.clone(),
                        });
                    }
                }
                _ => {}
            }
        }

        Ok(events)
    }

    /// Bidirectional sync: first disk-to-MCard, then MCard-to-disk.
    /// Detects conflicts where both sides changed since last sync.
    pub fn sync_bidirectional(
        &mut self,
        files: &HashMap<String, String>,
    ) -> Result<SyncReport, String> {
        // Phase 1: Detect what changed on disk vs. current handles.
        let disk_events = self.sync_disk_to_mcard(files)?;

        // Phase 2: Detect what would need to go back to disk.
        let mcard_events = self.sync_mcard_to_disk(files)?;

        // Phase 3: Detect conflicts — handles where both disk and MCard
        // changed. Since sync_disk_to_mcard already updated the handles,
        // conflicts are cases where the old_hash (before sync) differed
        // from both the disk hash and the new MCard hash.
        let mut conflicts = Vec::new();
        for event in &disk_events {
            if event.event_type == SyncEventType::Updated {
                // A conflict would be if the MCard side also had a pending
                // update for the same handle. In our model, the MCard
                // (content-addressed truth) wins.
                let mcard_pending = mcard_events.iter().find(|e| e.handle == event.handle);
                if let Some(me) = mcard_pending
                    && me.event_type == SyncEventType::Updated {
                        conflicts.push(SyncConflict {
                            handle: event.handle.clone(),
                            disk_hash: event.new_hash.clone(),
                            mcard_hash: me.new_hash.clone(),
                            resolution: ConflictResolution::McardWins,
                        });
                    }
            }
        }

        Ok(SyncReport {
            disk_to_mcard_events: disk_events,
            mcard_to_disk_events: mcard_events,
            conflicts,
        })
    }

    /// Format sync events as log.md entries.
    pub fn format_log_md(events: &[SyncEvent], agent_did: &str) -> String {
        let mut lines = Vec::new();
        for event in events {
            let arrow = match event.event_type {
                SyncEventType::Deleted => "->",
                _ => "->",
            };
            lines.push(format!(
                "{} {} {} {} {} {}",
                event.timestamp,
                agent_did,
                event.handle,
                event.old_hash,
                arrow,
                event.new_hash,
            ));
        }
        lines.join("\n")
    }
}

fn now_iso() -> String {
    // Use a simple timestamp for WASM compatibility.
    // In native mode, chrono is available but for cross-platform
    // consistency we use a simple counter-based approach.
    #[cfg(feature = "native")]
    {
        chrono::Local::now().format("%Y-%m-%dT%H:%M:%S%z").to_string()
    }
    #[cfg(not(feature = "native"))]
    {
        "1970-01-01T00:00:00Z".to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mount_registers_md_handles() {
        let mut files = HashMap::new();
        files.insert("README.md".to_string(), "# Hello".to_string());
        files.insert("docs/arch.md".to_string(), "# Arch".to_string());
        let mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
        assert!(mount.handles.contains_key("README.md"));
        assert!(mount.handles.contains_key("docs:arch.md"));
        assert!(!mount.handles.contains_key("image.png"));
    }

    #[test]
    fn test_index_md_gluing_manifest() {
        let mut files = HashMap::new();
        files.insert(
            "index.md".to_string(),
            "schema: a_mcard\nb-mcard: okf:README.md\ntype: okf/gluing_manifest\n".to_string(),
        );
        let mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
        let manifest = mount.gluing_manifest.unwrap();
        assert_eq!(manifest.schemas, vec!["a_mcard"]);
        assert_eq!(manifest.b_mcard_expectations, vec!["okf:README.md"]);
        assert_eq!(manifest.declared_types, vec!["okf/gluing_manifest"]);
    }

    #[test]
    fn test_log_md_handle_history() {
        let mut files = HashMap::new();
        files.insert(
            "log.md".to_string(),
            "2026-01-01T00:00:00Z did:key:z1 handle:h1 abc -> def\n".to_string(),
        );
        let mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
        assert_eq!(mount.handle_history.len(), 1);
        let entry = &mount.handle_history[0];
        assert_eq!(entry.handle, "handle:h1");
        assert_eq!(entry.new_hash, "def");
    }

    #[test]
    fn test_unmount_instead_removes_handles() {
        let mut files = HashMap::new();
        files.insert("README.md".to_string(), "# Hello".to_string());
        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files).unwrap();
        mount.unmount().unwrap();
        assert!(mount.handles.is_empty());
    }

    #[test]
    fn test_unmount_before_marks_stale() {
        let mut files = HashMap::new();
        files.insert("README.md".to_string(), "# Hello".to_string());
        let mut mount = OkfMount::mount("/okf", MountMode::Before, files).unwrap();
        let original_hash = mount.handles["README.md"].clone();
        mount.unmount().unwrap();
        assert_eq!(mount.handles["README.md"], format!("stale:{}", original_hash));
    }

    #[test]
    fn test_remount_is_idempotent() {
        let mut files = HashMap::new();
        files.insert("README.md".to_string(), "# Hello".to_string());
        let mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
        assert!(mount.is_idempotent_with(&files));
    }

    // ── Bidirectional Sync tests (Story 139.6.2) ──

    #[test]
    fn test_sync_disk_to_mcard_creates_new() {
        let mut files = HashMap::new();
        files.insert("README.md".to_string(), "# Hello".to_string());
        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();

        // Add a new file
        let mut updated_files = files.clone();
        updated_files.insert("docs/new.md".to_string(), "# New".to_string());
        let events = mount.sync_disk_to_mcard(&updated_files).unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, SyncEventType::Created);
        assert_eq!(events[0].handle, "docs:new.md");
    }

    #[test]
    fn test_sync_disk_to_mcard_updates_changed() {
        let mut files = HashMap::new();
        files.insert("README.md".to_string(), "# Hello".to_string());
        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();

        // Modify the file
        let mut updated_files = files.clone();
        updated_files.insert("README.md".to_string(), "# Updated".to_string());
        let events = mount.sync_disk_to_mcard(&updated_files).unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, SyncEventType::Updated);
        assert_eq!(events[0].handle, "README.md");
    }

    #[test]
    fn test_sync_disk_to_mcard_deletes_removed() {
        let mut files = HashMap::new();
        files.insert("README.md".to_string(), "# Hello".to_string());
        files.insert("docs/gone.md".to_string(), "# Gone".to_string());
        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();

        // Remove a file
        let mut updated_files = files.clone();
        updated_files.remove("docs/gone.md");
        let events = mount.sync_disk_to_mcard(&updated_files).unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, SyncEventType::Deleted);
        assert_eq!(events[0].handle, "docs:gone.md");
    }

    #[test]
    fn test_sync_mcard_to_disk_detects_diff() {
        let mut files = HashMap::new();
        files.insert("README.md".to_string(), "# Hello".to_string());
        let mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();

        // Simulate MCard handle being updated (not on disk)
        let mut mount2 = mount.clone();
        mount2.handles.insert("README.md".to_string(), sha256_hex("# Different"));

        let events = mount2.sync_mcard_to_disk(&files).unwrap();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, SyncEventType::Updated);
    }

    #[test]
    fn test_sync_bidirectional_no_changes() {
        let mut files = HashMap::new();
        files.insert("README.md".to_string(), "# Hello".to_string());
        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();
        let report = mount.sync_bidirectional(&files).unwrap();
        assert!(report.disk_to_mcard_events.is_empty());
        assert!(report.mcard_to_disk_events.is_empty());
        assert!(report.conflicts.is_empty());
    }

    #[test]
    fn test_sync_bidirectional_with_disk_change() {
        let mut files = HashMap::new();
        files.insert("README.md".to_string(), "# Hello".to_string());
        let mut mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();

        // Change on disk
        let mut updated = files.clone();
        updated.insert("README.md".to_string(), "# Updated on disk".to_string());
        let report = mount.sync_bidirectional(&updated).unwrap();
        assert_eq!(report.disk_to_mcard_events.len(), 1);
        assert_eq!(report.disk_to_mcard_events[0].event_type, SyncEventType::Updated);
    }

    #[test]
    fn test_format_log_md() {
        let event = SyncEvent {
            handle: "README.md".to_string(),
            old_hash: "abc".to_string(),
            new_hash: "def".to_string(),
            event_type: SyncEventType::Updated,
            timestamp: "2026-01-01T00:00:00Z".to_string(),
        };
        let log = OkfMount::format_log_md(&[event], "did:key:z123");
        assert!(log.contains("README.md"));
        assert!(log.contains("abc"));
        assert!(log.contains("def"));
        assert!(log.contains("did:key:z123"));
    }

    #[test]
    fn test_round_trip_file_mcard_file() {
        let content = "# Round Trip\nContent here.";
        let hash = sha256_hex(content);
        let mut files = HashMap::new();
        files.insert("concept.md".to_string(), content.to_string());
        let mount = OkfMount::mount("/okf", MountMode::Instead, files.clone()).unwrap();

        // The handle hash should match the file hash
        let handle_hash = mount.handles.get("concept.md").unwrap();
        assert_eq!(*handle_hash, hash);

        // Re-mounting should produce the same hash (idempotent)
        assert!(mount.is_idempotent_with(&files));
    }
}