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
#![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()
}
}