clm-kernel 0.0.12

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
#![allow(unused_imports)]
use super::*;

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")
    }
}

pub(super) 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()
    }
}