clm-kernel 0.0.7

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! 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>,
}


#[path = "okf_adapter_ops.rs"]
mod okf_adapter_ops;
#[allow(unused_imports)]
pub use okf_adapter_ops::*;
#[cfg(test)]
#[path = "okf_adapter_tests.rs"]
mod tests;