Skip to main content

clm_rust_core/layer2/
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
236
237#[path = "okf_adapter_ops.rs"]
238mod okf_adapter_ops;
239#[allow(unused_imports)]
240pub use okf_adapter_ops::*;
241#[cfg(test)]
242#[path = "okf_adapter_tests.rs"]
243mod tests;
244