weave-crdt 0.2.8

CRDT-based coordination for multi-agent code editing. Entity-level claims, conflict detection, and version tracking.
Documentation
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
use std::collections::HashMap;

use automerge::{ObjType, ReadDoc, Value, transaction::Transactable};
use serde::Serialize;

use crate::error::{Result, WeaveError};
use crate::merge::VersionVector;
use crate::state::{now_ms, EntityStateDoc};

// ── Result types ──

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum ClaimResult {
    Claimed,
    AlreadyOwnedBySelf,
    AlreadyClaimed { by: String },
}

#[derive(Debug, Clone, Serialize)]
pub struct EntityStatus {
    pub entity_id: String,
    pub name: String,
    pub entity_type: String,
    pub file_path: String,
    pub content_hash: String,
    pub claimed_by: Option<String>,
    pub claimed_at: Option<u64>,
    pub last_modified_by: Option<String>,
    pub last_modified_at: Option<u64>,
    pub version: u64,
    pub version_vector: VersionVector,
    pub merge_state: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct AgentStatus {
    pub agent_id: String,
    pub name: String,
    pub status: String,
    pub branch: String,
    pub last_seen: u64,
    pub working_on: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct PotentialConflict {
    pub entity_id: String,
    pub entity_name: String,
    pub file_path: String,
    pub agents: Vec<String>,
}

// ── Helper to read a string field from an automerge map ──

pub(crate) fn get_str(doc: &automerge::AutoCommit, obj: &automerge::ObjId, key: &str) -> Option<String> {
    match doc.get(obj, key) {
        Ok(Some((Value::Scalar(v), _))) => {
            if let automerge::ScalarValue::Str(s) = v.as_ref() {
                Some(s.to_string())
            } else {
                None
            }
        }
        _ => None,
    }
}

pub(crate) fn get_u64(doc: &automerge::AutoCommit, obj: &automerge::ObjId, key: &str) -> Option<u64> {
    match doc.get(obj, key) {
        Ok(Some((Value::Scalar(v), _))) => match v.as_ref() {
            automerge::ScalarValue::Uint(n) => Some(*n),
            automerge::ScalarValue::Int(n) => Some(*n as u64),
            _ => None,
        },
        _ => None,
    }
}

// ── Operations ──

/// Claim an entity for an agent. Advisory lock — doesn't prevent edits.
pub fn claim_entity(
    state: &mut EntityStateDoc,
    agent_id: &str,
    entity_id: &str,
) -> Result<ClaimResult> {
    let entities = state.entities_id()?;

    // Check if entity exists in state
    let entity_obj = match state.doc.get(&entities, entity_id)? {
        Some((_, id)) => id,
        None => return Err(WeaveError::EntityNotFound(entity_id.to_string())),
    };

    // Check current claim
    let current_claim = get_str(&state.doc, &entity_obj, "claimed_by");
    if let Some(ref owner) = current_claim {
        if owner == agent_id {
            return Ok(ClaimResult::AlreadyOwnedBySelf);
        }
        return Ok(ClaimResult::AlreadyClaimed { by: owner.clone() });
    }

    // Set claim
    let ts = now_ms();
    state.doc.put(&entity_obj, "claimed_by", agent_id)?;
    state.doc.put(&entity_obj, "claimed_at", ts as i64)?;

    // Log operation
    log_operation(state, agent_id, entity_id, "claim")?;

    Ok(ClaimResult::Claimed)
}

/// Release an entity claim.
pub fn release_entity(
    state: &mut EntityStateDoc,
    agent_id: &str,
    entity_id: &str,
) -> Result<()> {
    let entities = state.entities_id()?;

    let entity_obj = match state.doc.get(&entities, entity_id)? {
        Some((_, id)) => id,
        None => return Err(WeaveError::EntityNotFound(entity_id.to_string())),
    };

    // Only release if this agent owns it
    let current_claim = get_str(&state.doc, &entity_obj, "claimed_by");
    if current_claim.as_deref() == Some(agent_id) {
        state.doc.delete(&entity_obj, "claimed_by")?;
        state.doc.delete(&entity_obj, "claimed_at")?;
        log_operation(state, agent_id, entity_id, "release")?;
    }

    Ok(())
}

/// Record that an agent modified an entity.
pub fn record_modification(
    state: &mut EntityStateDoc,
    agent_id: &str,
    entity_id: &str,
    content_hash: &str,
) -> Result<()> {
    let entities = state.entities_id()?;

    let entity_obj = match state.doc.get(&entities, entity_id)? {
        Some((_, id)) => id,
        None => return Err(WeaveError::EntityNotFound(entity_id.to_string())),
    };

    let ts = now_ms();

    // Read current version vector, increment agent's counter
    let vv = read_version_vector(&state.doc, &entity_obj);
    let mut new_vv = vv;
    new_vv.increment(agent_id);

    // Write version vector back
    write_version_vector(&mut state.doc, &entity_obj, &new_vv)?;

    // Keep scalar version in sync (total of VV)
    let version = new_vv.total();

    state.doc.put(&entity_obj, "content_hash", content_hash)?;
    state
        .doc
        .put(&entity_obj, "last_modified_by", agent_id)?;
    state
        .doc
        .put(&entity_obj, "last_modified_at", ts as i64)?;
    state.doc.put(&entity_obj, "version", version as i64)?;

    log_operation(state, agent_id, entity_id, "modify")?;

    Ok(())
}

/// Get the status of an entity.
pub fn get_entity_status(state: &EntityStateDoc, entity_id: &str) -> Result<EntityStatus> {
    let entities = state.entities_id()?;

    let entity_obj = match state.doc.get(&entities, entity_id)? {
        Some((_, id)) => id,
        None => return Err(WeaveError::EntityNotFound(entity_id.to_string())),
    };

    let vv = read_version_vector(&state.doc, &entity_obj);
    let version = {
        let vv_total = vv.total();
        let stored = get_u64(&state.doc, &entity_obj, "version").unwrap_or(0);
        // Use whichever is larger for backward compat
        vv_total.max(stored)
    };

    Ok(EntityStatus {
        entity_id: entity_id.to_string(),
        name: get_str(&state.doc, &entity_obj, "name").unwrap_or_default(),
        entity_type: get_str(&state.doc, &entity_obj, "type").unwrap_or_default(),
        file_path: get_str(&state.doc, &entity_obj, "file_path").unwrap_or_default(),
        content_hash: get_str(&state.doc, &entity_obj, "content_hash").unwrap_or_default(),
        claimed_by: get_str(&state.doc, &entity_obj, "claimed_by"),
        claimed_at: get_u64(&state.doc, &entity_obj, "claimed_at"),
        last_modified_by: get_str(&state.doc, &entity_obj, "last_modified_by"),
        last_modified_at: get_u64(&state.doc, &entity_obj, "last_modified_at"),
        version,
        version_vector: vv,
        merge_state: get_str(&state.doc, &entity_obj, "merge_state")
            .unwrap_or_else(|| "clean".to_string()),
    })
}

/// Get all entities for a given file path.
pub fn get_entities_for_file(state: &EntityStateDoc, file_path: &str) -> Result<Vec<EntityStatus>> {
    let entities = state.entities_id()?;
    let mut result = Vec::new();

    for key in state.doc.keys(&entities) {
        let entity_obj = match state.doc.get(&entities, key.as_str())? {
            Some((_, id)) => id,
            None => continue,
        };
        let fp = get_str(&state.doc, &entity_obj, "file_path").unwrap_or_default();
        if fp == file_path {
            let vv = read_version_vector(&state.doc, &entity_obj);
            let version = {
                let vv_total = vv.total();
                let stored = get_u64(&state.doc, &entity_obj, "version").unwrap_or(0);
                vv_total.max(stored)
            };
            result.push(EntityStatus {
                entity_id: key.clone(),
                name: get_str(&state.doc, &entity_obj, "name").unwrap_or_default(),
                entity_type: get_str(&state.doc, &entity_obj, "type").unwrap_or_default(),
                file_path: fp,
                content_hash: get_str(&state.doc, &entity_obj, "content_hash").unwrap_or_default(),
                claimed_by: get_str(&state.doc, &entity_obj, "claimed_by"),
                claimed_at: get_u64(&state.doc, &entity_obj, "claimed_at"),
                last_modified_by: get_str(&state.doc, &entity_obj, "last_modified_by"),
                last_modified_at: get_u64(&state.doc, &entity_obj, "last_modified_at"),
                version,
                version_vector: vv,
                merge_state: get_str(&state.doc, &entity_obj, "merge_state")
                    .unwrap_or_else(|| "clean".to_string()),
            });
        }
    }

    Ok(result)
}

/// Get the status of an agent.
pub fn get_agent_status(state: &EntityStateDoc, agent_id: &str) -> Result<AgentStatus> {
    let agents = state.agents_id()?;

    let agent_obj = match state.doc.get(&agents, agent_id)? {
        Some((_, id)) => id,
        None => return Err(WeaveError::AgentNotFound(agent_id.to_string())),
    };

    // Read working_on list
    let working_on = match state.doc.get(&agent_obj, "working_on")? {
        Some((_, list_id)) => {
            let len = state.doc.length(&list_id);
            let mut items = Vec::new();
            for i in 0..len {
                if let Ok(Some((Value::Scalar(v), _))) = state.doc.get(&list_id, i) {
                    if let automerge::ScalarValue::Str(s) = v.as_ref() {
                        items.push(s.to_string());
                    }
                }
            }
            items
        }
        None => Vec::new(),
    };

    Ok(AgentStatus {
        agent_id: agent_id.to_string(),
        name: get_str(&state.doc, &agent_obj, "name").unwrap_or_default(),
        status: get_str(&state.doc, &agent_obj, "status").unwrap_or("unknown".to_string()),
        branch: get_str(&state.doc, &agent_obj, "branch").unwrap_or_default(),
        last_seen: get_u64(&state.doc, &agent_obj, "last_seen").unwrap_or(0),
        working_on,
    })
}

/// Register an agent in the state.
pub fn register_agent(
    state: &mut EntityStateDoc,
    agent_id: &str,
    name: &str,
    branch: &str,
) -> Result<()> {
    let agents = state.agents_id()?;

    let agent_obj = state.doc.put_object(&agents, agent_id, ObjType::Map)?;
    state.doc.put(&agent_obj, "name", name)?;
    state.doc.put(&agent_obj, "status", "active")?;
    state.doc.put(&agent_obj, "branch", branch)?;
    state.doc.put(&agent_obj, "last_seen", now_ms() as i64)?;
    state
        .doc
        .put_object(&agent_obj, "working_on", ObjType::List)?;

    Ok(())
}

/// Update agent heartbeat and working_on list.
pub fn agent_heartbeat(
    state: &mut EntityStateDoc,
    agent_id: &str,
    working_on: &[String],
) -> Result<()> {
    let agents = state.agents_id()?;

    let agent_obj = match state.doc.get(&agents, agent_id)? {
        Some((_, id)) => id,
        None => return Err(WeaveError::AgentNotFound(agent_id.to_string())),
    };

    state.doc.put(&agent_obj, "last_seen", now_ms() as i64)?;
    state.doc.put(&agent_obj, "status", "active")?;

    // Replace working_on list
    let list_id = state
        .doc
        .put_object(&agent_obj, "working_on", ObjType::List)?;
    for (i, entity_id) in working_on.iter().enumerate() {
        state
            .doc
            .insert(&list_id, i, entity_id.as_str())?;
    }

    Ok(())
}

/// Clean up stale agents: release their claims and mark inactive.
pub fn cleanup_stale_agents(state: &mut EntityStateDoc, timeout_ms: u64) -> Result<Vec<String>> {
    let now = now_ms();
    let agents = state.agents_id()?;
    let mut stale = Vec::new();

    // Collect stale agent IDs
    let agent_keys: Vec<String> = state.doc.keys(&agents).collect();
    for key in &agent_keys {
        let agent_obj = match state.doc.get(&agents, key.as_str())? {
            Some((_, id)) => id,
            None => continue,
        };
        let last_seen = get_u64(&state.doc, &agent_obj, "last_seen").unwrap_or(0);
        if now - last_seen > timeout_ms {
            stale.push(key.clone());
        }
    }

    // Release claims and mark inactive
    for agent_id in &stale {
        // Mark agent as stale
        let agent_obj = match state.doc.get(&agents, agent_id.as_str())? {
            Some((_, id)) => id,
            None => continue,
        };
        state.doc.put(&agent_obj, "status", "stale")?;

        // Release all entity claims held by this agent
        let entities = state.entities_id()?;
        let entity_keys: Vec<String> = state.doc.keys(&entities).collect();
        for ek in &entity_keys {
            let entity_obj = match state.doc.get(&entities, ek.as_str())? {
                Some((_, id)) => id,
                None => continue,
            };
            if get_str(&state.doc, &entity_obj, "claimed_by").as_deref() == Some(agent_id.as_str())
            {
                state.doc.delete(&entity_obj, "claimed_by")?;
                state.doc.delete(&entity_obj, "claimed_at")?;
            }
        }
    }

    Ok(stale)
}

/// Detect entities being touched/claimed by multiple agents.
pub fn detect_potential_conflicts(state: &EntityStateDoc) -> Result<Vec<PotentialConflict>> {
    let entities = state.entities_id()?;
    let agents = state.agents_id()?;
    let mut conflicts = Vec::new();

    // Build map: entity_id → set of agents working on it
    let mut entity_agents: std::collections::HashMap<String, Vec<String>> =
        std::collections::HashMap::new();

    // From agent working_on lists
    let agent_keys: Vec<String> = state.doc.keys(&agents).collect();
    for ak in &agent_keys {
        let agent_obj = match state.doc.get(&agents, ak.as_str())? {
            Some((_, id)) => id,
            None => continue,
        };
        let agent_status = get_str(&state.doc, &agent_obj, "status").unwrap_or_default();
        if agent_status == "stale" {
            continue;
        }
        if let Ok(Some((_, list_id))) = state.doc.get(&agent_obj, "working_on") {
            let len = state.doc.length(&list_id);
            for i in 0..len {
                if let Ok(Some((Value::Scalar(v), _))) = state.doc.get(&list_id, i) {
                    if let automerge::ScalarValue::Str(s) = v.as_ref() {
                        entity_agents
                            .entry(s.to_string())
                            .or_default()
                            .push(ak.clone());
                    }
                }
            }
        }
    }

    // Also check claimed_by
    let entity_keys: Vec<String> = state.doc.keys(&entities).collect();
    for ek in &entity_keys {
        let entity_obj = match state.doc.get(&entities, ek.as_str())? {
            Some((_, id)) => id,
            None => continue,
        };
        if let Some(claimed_by) = get_str(&state.doc, &entity_obj, "claimed_by") {
            let agents_list = entity_agents.entry(ek.clone()).or_default();
            if !agents_list.contains(&claimed_by) {
                agents_list.push(claimed_by);
            }
        }
    }

    // Report entities with multiple agents
    for (entity_id, agent_list) in &entity_agents {
        if agent_list.len() > 1 {
            // Look up entity details
            let entity_obj = match state.doc.get(&entities, entity_id.as_str())? {
                Some((_, id)) => id,
                None => continue,
            };
            conflicts.push(PotentialConflict {
                entity_id: entity_id.clone(),
                entity_name: get_str(&state.doc, &entity_obj, "name").unwrap_or_default(),
                file_path: get_str(&state.doc, &entity_obj, "file_path").unwrap_or_default(),
                agents: agent_list.clone(),
            });
        }
    }

    Ok(conflicts)
}

/// Upsert an entity into the CRDT state (used during sync).
pub fn upsert_entity(
    state: &mut EntityStateDoc,
    entity_id: &str,
    name: &str,
    entity_type: &str,
    file_path: &str,
    content_hash: &str,
) -> Result<()> {
    let entities = state.entities_id()?;

    match state.doc.get(&entities, entity_id)? {
        Some((_, id)) => {
            // Update existing: only update mutable fields, preserve claims + content
            state.doc.put(&id, "name", name)?;
            state.doc.put(&id, "type", entity_type)?;
            state.doc.put(&id, "file_path", file_path)?;
            state.doc.put(&id, "content_hash", content_hash)?;
        }
        None => {
            // Create new with all v2 fields
            let id = state.doc.put_object(&entities, entity_id, ObjType::Map)?;
            state.doc.put(&id, "name", name)?;
            state.doc.put(&id, "type", entity_type)?;
            state.doc.put(&id, "file_path", file_path)?;
            state.doc.put(&id, "content_hash", content_hash)?;
            state.doc.put(&id, "version", 0_i64)?;
            state.doc.put(&id, "last_modified_at", now_ms() as i64)?;
            state.doc.put_object(&id, "version_vector", ObjType::Map)?;
            state.doc.put(&id, "content", "")?;
            state.doc.put(&id, "base_content", "")?;
            state.doc.put(&id, "merge_state", "clean")?;
        }
    };

    Ok(())
}

/// Set an agent's last_seen timestamp (for testing stale cleanup).
#[cfg(any(test, feature = "test-helpers"))]
pub fn set_agent_last_seen(
    state: &mut EntityStateDoc,
    agent_id: &str,
    last_seen: u64,
) -> Result<()> {
    let agents = state.agents_id()?;
    let agent_obj = match state.doc.get(&agents, agent_id)? {
        Some((_, id)) => id,
        None => return Err(WeaveError::AgentNotFound(agent_id.to_string())),
    };
    state.doc.put(&agent_obj, "last_seen", last_seen as i64)?;
    Ok(())
}

// ── Version vector helpers ──

/// Read a version vector from an entity's version_vector map.
pub(crate) fn read_version_vector(doc: &automerge::AutoCommit, entity_obj: &automerge::ObjId) -> VersionVector {
    let vv_obj = match doc.get(entity_obj, "version_vector") {
        Ok(Some((_, id))) => id,
        _ => return VersionVector::new(),
    };

    let mut map = HashMap::new();
    for key in doc.keys(&vv_obj) {
        if let Some(val) = get_u64(doc, &vv_obj, &key) {
            map.insert(key, val);
        }
    }
    VersionVector::from_map(map)
}

/// Write a version vector to an entity's version_vector map.
pub(crate) fn write_version_vector(
    doc: &mut automerge::AutoCommit,
    entity_obj: &automerge::ObjId,
    vv: &VersionVector,
) -> Result<()> {
    let vv_obj = doc.put_object(entity_obj, "version_vector", ObjType::Map)?;
    for (agent_id, &count) in vv.counters() {
        doc.put(&vv_obj, agent_id.as_str(), count as i64)?;
    }
    Ok(())
}

// ── Internal helpers ──

fn log_operation(
    state: &mut EntityStateDoc,
    agent_id: &str,
    entity_id: &str,
    op: &str,
) -> Result<()> {
    let operations = state.operations_id()?;
    let len = state.doc.length(&operations);
    let entry = state
        .doc
        .insert_object(&operations, len, ObjType::Map)?;
    state.doc.put(&entry, "agent", agent_id)?;
    state.doc.put(&entry, "entity_id", entity_id)?;
    state.doc.put(&entry, "op", op)?;
    state.doc.put(&entry, "timestamp", now_ms() as i64)?;
    Ok(())
}