use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MountMode {
Before,
After,
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>,
pub gluing_manifest_type: Option<String>,
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('/', ":")
}
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)
}
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 {
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,
})
}
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(())
}
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
}
}
#[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 {
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();
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);
}
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());
}
_ => {}
}
}
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(),
});
let current = self.handles[&handle].clone();
self.handles.insert(handle, format!("stale:{}", current));
}
Ok(events)
}
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;
}
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 => {
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 => {
events.push(SyncEvent {
handle: handle.clone(),
old_hash: dh,
new_hash: mcard_hash.clone(),
event_type: SyncEventType::Updated,
timestamp: now.clone(),
});
}
_ => {}
}
}
Ok(events)
}
#[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 => {
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 => {
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)
}
pub fn sync_bidirectional(
&mut self,
files: &HashMap<String, String>,
) -> Result<SyncReport, String> {
let disk_events = self.sync_disk_to_mcard(files)?;
let mcard_events = self.sync_mcard_to_disk(files)?;
let mut conflicts = Vec::new();
for event in &disk_events {
if event.event_type == SyncEventType::Updated {
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,
})
}
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 {
#[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::*;
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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"));
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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"]);
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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");
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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());
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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));
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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));
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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();
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");
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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();
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");
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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();
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");
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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();
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);
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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());
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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();
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);
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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"));
}
#[cfg_attr(not(target_arch = "wasm32"), test)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_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();
let handle_hash = mount.handles.get("concept.md").unwrap();
assert_eq!(*handle_hash, hash);
assert!(mount.is_idempotent_with(&files));
}
}