gitiverse-cob 0.2.0

Content-addressed Git-backed DAG CRDTs for repository governance, issues, and patches in gitiverse
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
use core::fmt;
use core::str::FromStr;
use std::collections::{BTreeMap, BTreeSet};

use gitiverse_core::ids::{ActorId, RepoId, serde_hex_bytes, serde_identity_key};
use gitiverse_git::canonical::canonical_json_bytes;
use gitiverse_git::{GitError, GitObjectKind, GitStore, Oid, validate_ref_name};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sha2::{Digest, Sha256};
use thiserror::Error;
use wire_mesh_core::ports::{CoreError, Identity};
use wire_mesh_wire::DecodeError;
use wire_mesh_wire::identity::IdentityKey;
use wire_mesh_wire::minicbor::{Decode, Decoder, Encode, Encoder};
use wire_mesh_wire::strict;
use wire_mesh_wire::value::CdeMapBuilder;

const OP_ID_BYTE_LEN: usize = 32;
const OP_ID_HEX_LEN: usize = OP_ID_BYTE_LEN * 2;

/// Failure returned by DAG CRDT verification, topological resolution, or persistence operations.
#[derive(Debug, Error)]
pub enum CobError {
    #[error("invalid operation id {0:?}")]
    InvalidOpId(String),
    #[error("canonical serialisation error: {0}")]
    Canonical(#[from] gitiverse_git::canonical::CanonicalError),
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("Git store error: {0}")]
    Git(#[from] GitError),
    #[error("cryptographic port error: {0}")]
    Crypto(#[from] CoreError),
    #[error("author key does not match claimed author actor id")]
    AuthorKeyMismatch,
    #[error("operation signature does not verify")]
    BadSignature,
    #[error("operation belongs to repo {found}, expected {expected}")]
    RepoMismatch { expected: RepoId, found: RepoId },
    #[error("operation has kind {found:?}, expected {expected:?}")]
    KindMismatch { expected: String, found: String },
    #[error("invalid operation: {0}")]
    InvalidOp(String),
    #[error("missing causal parent {parent} referenced by operation {op_id}")]
    MissingParent { op_id: OpId, parent: OpId },
    #[error(
        "invalid lamport clock on operation {op_id}: {lamport} must exceed parent lamport {parent_lamport}"
    )]
    InvalidLamport {
        op_id: OpId,
        lamport: u64,
        parent_lamport: u64,
    },
    #[error("cycle detected in operation DAG")]
    CycleDetected,
    #[error("actor {actor} is not authorised for operation {op_id}: {reason}")]
    Unauthorised {
        actor: ActorId,
        op_id: OpId,
        reason: String,
    },
    #[error("corrupted COB snapshot blob: expected blob object")]
    UnexpectedGitObjectKind,
}

/// Content-addressed 32-byte SHA-256 identifier of a signed [`DagOp`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OpId(pub [u8; OP_ID_BYTE_LEN]);

impl OpId {
    #[must_use]
    pub const fn from_bytes(bytes: [u8; OP_ID_BYTE_LEN]) -> Self {
        Self(bytes)
    }

    #[must_use]
    pub const fn as_bytes(&self) -> &[u8; OP_ID_BYTE_LEN] {
        &self.0
    }

    #[must_use]
    pub fn to_hex(&self) -> String {
        hex::encode(self.0)
    }

    pub fn from_hex(s: &str) -> Result<Self, CobError> {
        if s.len() != OP_ID_HEX_LEN
            || !s
                .bytes()
                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
        {
            return Err(CobError::InvalidOpId(s.to_owned()));
        }
        let bytes = hex::decode(s).map_err(|_| CobError::InvalidOpId(s.to_owned()))?;
        let arr: [u8; OP_ID_BYTE_LEN] = bytes
            .try_into()
            .map_err(|_| CobError::InvalidOpId(s.to_owned()))?;
        Ok(Self(arr))
    }
}

impl fmt::Display for OpId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_hex())
    }
}

impl FromStr for OpId {
    type Err = CobError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_hex(s)
    }
}

impl Serialize for OpId {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for OpId {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Self::from_str(&s).map_err(serde::de::Error::custom)
    }
}

impl Encode<()> for OpId {
    fn encode<W: wire_mesh_wire::minicbor::encode::Write>(
        &self,
        e: &mut Encoder<W>,
        _ctx: &mut (),
    ) -> Result<(), wire_mesh_wire::minicbor::encode::Error<W::Error>> {
        e.bytes(&self.0)?.ok()
    }
}

impl Decode<'_, ()> for OpId {
    fn decode(
        d: &mut Decoder<'_>,
        _ctx: &mut (),
    ) -> Result<Self, wire_mesh_wire::minicbor::decode::Error> {
        let bytes =
            strict::bytes_value(d).map_err(wire_mesh_wire::minicbor::decode::Error::custom)?;
        let arr: [u8; OP_ID_BYTE_LEN] = bytes.try_into().map_err(|v: Vec<u8>| {
            wire_mesh_wire::minicbor::decode::Error::custom(DecodeError::InvalidLength {
                field: "op-id",
                expected: OP_ID_BYTE_LEN,
                found: v.len(),
            })
        })?;
        Ok(Self(arr))
    }
}

/// Signed operation node in a content-addressed collaborative object DAG.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DagOp<T> {
    pub repo_id: RepoId,
    pub kind: String,
    pub author: ActorId,
    #[serde(with = "serde_identity_key")]
    pub author_key: IdentityKey,
    pub parents: Vec<OpId>,
    pub lamport: u64,
    pub timestamp: u64,
    pub payload: T,
    #[serde(with = "serde_hex_bytes")]
    pub signature: Vec<u8>,
}

impl<T: Serialize> DagOp<T> {
    /// Constructs and signs a new [`DagOp`] with canonically sorted, deduplicated parent links.
    pub async fn sign_new(
        repo_id: RepoId,
        kind: impl Into<String>,
        mut parents: Vec<OpId>,
        lamport: u64,
        timestamp: u64,
        payload: T,
        identity: &dyn Identity,
    ) -> Result<Self, CobError> {
        let kind = kind.into();
        if kind.is_empty() {
            return Err(CobError::InvalidOp("COB kind must not be empty".to_owned()));
        }
        if lamport == 0 {
            return Err(CobError::InvalidOp(
                "lamport clock must be at least 1".to_owned(),
            ));
        }
        parents.sort();
        parents.dedup();
        let mut op = Self {
            repo_id,
            kind,
            author: ActorId(*identity.device_id()),
            author_key: identity.identity_key().clone(),
            parents,
            lamport,
            timestamp,
            payload,
            signature: Vec::new(),
        };
        let signing = op.signing_bytes()?;
        op.signature = identity.sign(&signing).await?;
        Ok(op)
    }

    /// Computes the deterministic canonical signing input covering all semantic operation fields.
    pub fn signing_bytes(&self) -> Result<Vec<u8>, CobError> {
        let payload_json = canonical_json_bytes(&self.payload)?;
        let mut parents_buf = Vec::new();
        {
            let mut pe = Encoder::new(&mut parents_buf);
            let _ = pe.array(self.parents.len() as u64);
            for parent in &self.parents {
                let _ = parent.encode(&mut pe, &mut ());
            }
        }
        let mut builder = CdeMapBuilder::new();
        builder.push("domain", "gitiverse.cob.op-sign.v1");
        builder.push("repo-id", &self.repo_id);
        builder.push("kind", &self.kind.as_str());
        builder.push("author", &self.author);
        builder.push("author-key", &self.author_key);
        builder.push_raw(encoded_key("parents"), parents_buf);
        builder.push("lamport", &self.lamport);
        builder.push("timestamp", &self.timestamp);
        builder.push_bytes("payload", &payload_json);

        let mut buf = Vec::new();
        let mut enc = Encoder::new(&mut buf);
        let _ = builder.write(&mut enc);
        Ok(buf)
    }

    /// Computes the content-addressed [`OpId`] of this signed operation.
    pub fn op_id(&self) -> Result<OpId, CobError> {
        let signing = self.signing_bytes()?;
        let mut builder = CdeMapBuilder::new();
        builder.push("domain", "gitiverse.cob.op-id.v1");
        builder.push_bytes("signing", &signing);
        builder.push_bytes("signature", &self.signature);
        let mut buf = Vec::new();
        let mut enc = Encoder::new(&mut buf);
        let _ = builder.write(&mut enc);
        let digest = Sha256::digest(&buf);
        Ok(OpId(digest.into()))
    }

    /// Validates structural invariants, self-certifying key derivation, and cryptographic signature.
    pub async fn verify(
        &self,
        identity: &dyn Identity,
        expected_repo_id: Option<&RepoId>,
        expected_kind: Option<&str>,
    ) -> Result<OpId, CobError> {
        if let Some(expected) = expected_repo_id
            && &self.repo_id != expected
        {
            return Err(CobError::RepoMismatch {
                expected: *expected,
                found: self.repo_id,
            });
        }
        if let Some(expected) = expected_kind
            && self.kind != expected
        {
            return Err(CobError::KindMismatch {
                expected: expected.to_owned(),
                found: self.kind.clone(),
            });
        }
        self.validate_structure()?;
        if ActorId(identity.derive_device_id(&self.author_key.public_key)) != self.author {
            return Err(CobError::AuthorKeyMismatch);
        }
        let signing = self.signing_bytes()?;
        let ok = identity
            .verify(&self.author_key, &signing, &self.signature)
            .await?;
        if !ok {
            return Err(CobError::BadSignature);
        }
        self.op_id()
    }

    pub(crate) fn validate_structure(&self) -> Result<(), CobError> {
        if self.kind.is_empty() {
            return Err(CobError::InvalidOp("COB kind must not be empty".to_owned()));
        }
        if self.lamport == 0 {
            return Err(CobError::InvalidOp(
                "lamport clock must be at least 1".to_owned(),
            ));
        }
        if !self.parents.windows(2).all(|pair| pair[0] < pair[1]) {
            return Err(CobError::InvalidOp(
                "operation parents must be strictly ascending and unique".to_owned(),
            ));
        }
        Ok(())
    }
}

fn encoded_key(key: &str) -> Vec<u8> {
    let mut buf = Vec::new();
    let _ = Encoder::new(&mut buf).str(key);
    buf
}

/// Generic content-addressed DAG CRDT store with deterministic `(lamport, OpId)` topological folding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Dag<T> {
    ops: BTreeMap<OpId, DagOp<T>>,
}

impl<T> Default for Dag<T> {
    fn default() -> Self {
        Self {
            ops: BTreeMap::new(),
        }
    }
}

impl<T: Serialize> Dag<T> {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.ops.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.ops.is_empty()
    }

    #[must_use]
    pub fn get(&self, id: &OpId) -> Option<&DagOp<T>> {
        self.ops.get(id)
    }

    #[must_use]
    pub fn contains(&self, id: &OpId) -> bool {
        self.ops.contains_key(id)
    }

    /// Returns all operations indexed by their content-addressed [`OpId`].
    #[must_use]
    pub fn ops(&self) -> &BTreeMap<OpId, DagOp<T>> {
        &self.ops
    }

    /// Computes the next valid Lamport timestamp above all specified `parents`.
    #[must_use]
    pub fn next_lamport(&self, parents: &[OpId]) -> u64 {
        parents
            .iter()
            .filter_map(|p| self.ops.get(p).map(|op| op.lamport))
            .max()
            .unwrap_or(0)
            + 1
    }

    /// Verifies and idempotently inserts `op` into the DAG.
    pub async fn insert_verified(
        &mut self,
        op: DagOp<T>,
        identity: &dyn Identity,
        expected_repo_id: Option<&RepoId>,
        expected_kind: Option<&str>,
    ) -> Result<OpId, CobError> {
        let id = op.verify(identity, expected_repo_id, expected_kind).await?;
        self.ops.entry(id).or_insert(op);
        Ok(id)
    }

    /// Inserts an operation whose signature was already checked (or for local construction/tests), still enforcing structural validity and idempotence.
    pub fn insert_unchecked(&mut self, op: DagOp<T>) -> Result<OpId, CobError> {
        op.validate_structure()?;
        let id = op.op_id()?;
        self.ops.entry(id).or_insert(op);
        Ok(id)
    }

    /// Returns the causal tips (operations with zero children in this DAG), sorted deterministically.
    #[must_use]
    pub fn tips(&self) -> Vec<OpId> {
        let mut referenced = BTreeSet::new();
        for op in self.ops.values() {
            for parent in &op.parents {
                referenced.insert(*parent);
            }
        }
        self.ops
            .keys()
            .copied()
            .filter(|id| !referenced.contains(id))
            .collect()
    }

    /// Validates causal completeness, Lamport monotonicity, and acyclicity, returning operations in deterministic `(lamport, OpId)` topological order.
    pub fn topological_order(&self) -> Result<Vec<(OpId, &DagOp<T>)>, CobError> {
        let mut in_degree: BTreeMap<OpId, usize> = BTreeMap::new();
        let mut children: BTreeMap<OpId, Vec<OpId>> = BTreeMap::new();

        for (id, op) in &self.ops {
            op.validate_structure()?;
            for parent_id in &op.parents {
                let Some(parent_op) = self.ops.get(parent_id) else {
                    return Err(CobError::MissingParent {
                        op_id: *id,
                        parent: *parent_id,
                    });
                };
                if op.lamport <= parent_op.lamport {
                    return Err(CobError::InvalidLamport {
                        op_id: *id,
                        lamport: op.lamport,
                        parent_lamport: parent_op.lamport,
                    });
                }
                children.entry(*parent_id).or_default().push(*id);
            }
            in_degree.insert(*id, op.parents.len());
        }

        // Kahn's algorithm ordered by `(lamport, OpId)` guarantees identical output on every replica regardless of arrival order.
        let mut ready: BTreeSet<(u64, OpId)> = BTreeSet::new();
        for (id, deg) in &in_degree {
            if *deg == 0
                && let Some(op) = self.ops.get(id)
            {
                ready.insert((op.lamport, *id));
            }
        }

        let mut ordered = Vec::with_capacity(self.ops.len());
        while let Some((_, id)) = ready.pop_first() {
            let Some(op) = self.ops.get(&id) else {
                continue;
            };
            ordered.push((id, op));
            if let Some(kids) = children.get(&id) {
                for kid_id in kids {
                    if let Some(deg) = in_degree.get_mut(kid_id) {
                        *deg -= 1;
                        if *deg == 0
                            && let Some(kid_op) = self.ops.get(kid_id)
                        {
                            ready.insert((kid_op.lamport, *kid_id));
                        }
                    }
                }
            }
        }

        if ordered.len() != self.ops.len() {
            return Err(CobError::CycleDetected);
        }
        Ok(ordered)
    }

    /// Folds the DAG in deterministic causal topological order, passing each operation and its transitive causal ancestor set to `step`.
    pub fn fold<S, F>(&self, mut state: S, mut step: F) -> Result<S, CobError>
    where
        F: FnMut(&mut S, OpId, &DagOp<T>, &BTreeSet<OpId>) -> Result<(), CobError>,
    {
        let ordered = self.topological_order()?;
        let mut ancestors: BTreeMap<OpId, BTreeSet<OpId>> = BTreeMap::new();
        for (id, op) in ordered {
            let mut op_ancestors = BTreeSet::new();
            for parent_id in &op.parents {
                op_ancestors.insert(*parent_id);
                if let Some(parent_ancestors) = ancestors.get(parent_id) {
                    op_ancestors.extend(parent_ancestors.iter().copied());
                }
            }
            step(&mut state, id, op, &op_ancestors)?;
            ancestors.insert(id, op_ancestors);
        }
        Ok(state)
    }
}

/// Shared last-writer-wins register keyed by `(lamport, OpId)` for Strong Eventual Consistency.
#[derive(Debug, Clone)]
pub(crate) struct Lww<T> {
    pub(crate) clock: (u64, OpId),
    pub(crate) value: T,
}

impl<T> Lww<T> {
    pub(crate) fn new(lamport: u64, op_id: OpId, value: T) -> Self {
        Self {
            clock: (lamport, op_id),
            value,
        }
    }

    pub(crate) fn update(&mut self, lamport: u64, op_id: OpId, value: T) {
        let candidate = (lamport, op_id);
        if candidate > self.clock {
            self.clock = candidate;
            self.value = value;
        }
    }
}

pub(crate) fn require_root<'a, T>(
    state: &'a mut Option<T>,
    kind: &str,
    op_id: OpId,
) -> Result<&'a mut T, CobError> {
    state.as_mut().ok_or_else(|| {
        CobError::InvalidOp(format!("{kind} operation {op_id} arrived before root op"))
    })
}

/// Builds the canonical Git reference path `refs/cobs/<kind>/<id>` after validation.
pub fn cob_ref_name(kind: &str, id: &str) -> Result<String, CobError> {
    if kind.is_empty()
        || id.is_empty()
        || kind.contains('/')
        || id.contains('/')
        || kind.contains("..")
        || id.contains("..")
    {
        return Err(CobError::InvalidOp(format!(
            "invalid COB ref components kind={kind:?}, id={id:?}"
        )));
    }
    let ref_name = format!("refs/cobs/{kind}/{id}");
    validate_ref_name(&ref_name)?;
    Ok(ref_name)
}

#[derive(Debug, Serialize)]
struct CobBlobWriteEnvelope<'a, T> {
    version: u32,
    ops: Vec<&'a DagOp<T>>,
}

#[derive(Debug, Deserialize)]
struct CobBlobEnvelope<T> {
    version: u32,
    ops: Vec<DagOp<T>>,
}

/// Persists `dag` as a canonical JSON blob in `store` and updates `refs/cobs/<kind>/<id>` using CAS against `expected_old_oid`.
pub async fn save_dag_to_git<T: Serialize>(
    store: &dyn GitStore,
    kind: &str,
    id: &str,
    dag: &Dag<T>,
    expected_old_oid: Option<&Oid>,
) -> Result<Oid, CobError> {
    let ref_name = cob_ref_name(kind, id)?;
    let ops: Vec<&DagOp<T>> = dag.ops().values().collect();
    let envelope = CobBlobWriteEnvelope { version: 1, ops };
    let blob_bytes = canonical_json_bytes(&envelope)?;
    let blob_oid = store.write_blob(&blob_bytes).await?;
    store
        .update_ref_cas(&ref_name, Some(&blob_oid), expected_old_oid)
        .await?;
    Ok(blob_oid)
}

/// Loads and cryptographically verifies a [`Dag`] stored at `refs/cobs/<kind>/<id>` from `store`.
pub async fn load_dag_from_git<T>(
    store: &dyn GitStore,
    kind: &str,
    id: &str,
    identity: &dyn Identity,
    expected_repo_id: Option<&RepoId>,
) -> Result<Option<(Oid, Dag<T>)>, CobError>
where
    T: Serialize + for<'de> Deserialize<'de>,
{
    let ref_name = cob_ref_name(kind, id)?;
    let Some(oid) = store.resolve_ref(&ref_name).await? else {
        return Ok(None);
    };
    let obj = store.read_object(&oid).await?;
    if obj.kind != GitObjectKind::Blob {
        return Err(CobError::UnexpectedGitObjectKind);
    }
    let envelope: CobBlobEnvelope<T> = serde_json::from_slice(&obj.bytes)?;
    if envelope.version != 1 {
        return Err(CobError::InvalidOp(format!(
            "unsupported COB snapshot version {}",
            envelope.version
        )));
    }
    let mut dag = Dag::new();
    for op in envelope.ops {
        dag.insert_verified(op, identity, expected_repo_id, Some(kind))
            .await?;
    }
    Ok(Some((oid, dag)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use gitiverse_git::CliGitStore;
    use wire_mesh_core::adapters::NodeIdentity;

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    struct SamplePayload(String);

    #[tokio::test]
    async fn signed_dag_op_verifies_and_persists_to_bare_git_store() {
        let dir = tempfile::tempdir().unwrap();
        let store = CliGitStore::init_bare_at(dir.path()).await.unwrap();
        let alice = NodeIdentity::generate_ed25519();
        let bob = NodeIdentity::generate_es256();
        let repo_id = RepoId::from_bytes([0x77; 32]);

        let op1 = DagOp::sign_new(
            repo_id,
            "sample",
            vec![],
            1,
            100,
            SamplePayload("root".to_owned()),
            &alice,
        )
        .await
        .unwrap();
        let id1 = op1.op_id().unwrap();

        let op2 = DagOp::sign_new(
            repo_id,
            "sample",
            vec![id1],
            2,
            200,
            SamplePayload("child".to_owned()),
            &bob,
        )
        .await
        .unwrap();
        let id2 = op2.op_id().unwrap();

        let mut dag = Dag::new();
        dag.insert_verified(op2, &alice, Some(&repo_id), Some("sample"))
            .await
            .unwrap();
        dag.insert_verified(op1, &bob, Some(&repo_id), Some("sample"))
            .await
            .unwrap();
        assert_eq!(dag.tips(), vec![id2]);

        let blob_oid = save_dag_to_git(&store, "sample", &id1.to_hex(), &dag, None)
            .await
            .unwrap();

        let (loaded_oid, loaded_dag) = load_dag_from_git::<SamplePayload>(
            &store,
            "sample",
            &id1.to_hex(),
            &alice,
            Some(&repo_id),
        )
        .await
        .unwrap()
        .unwrap();
        assert_eq!(loaded_oid, blob_oid);
        assert_eq!(loaded_dag, dag);
    }

    #[tokio::test]
    async fn tampered_op_and_missing_parent_and_lamport_regression_fail() {
        let alice = NodeIdentity::generate_ed25519();
        let repo_id = RepoId::from_bytes([0x12; 32]);
        let mut op = DagOp::sign_new(
            repo_id,
            "sample",
            vec![],
            1,
            100,
            SamplePayload("hello".to_owned()),
            &alice,
        )
        .await
        .unwrap();
        let root_id = op.op_id().unwrap();
        op.payload = SamplePayload("tampered".to_owned());
        assert!(matches!(
            op.verify(&alice, Some(&repo_id), Some("sample")).await,
            Err(CobError::BadSignature)
        ));

        let orphan = DagOp::sign_new(
            repo_id,
            "sample",
            vec![root_id],
            2,
            101,
            SamplePayload("orphan".to_owned()),
            &alice,
        )
        .await
        .unwrap();
        let mut dag = Dag::new();
        dag.insert_unchecked(orphan).unwrap();
        assert!(matches!(
            dag.topological_order(),
            Err(CobError::MissingParent { .. })
        ));

        let valid_root = DagOp::sign_new(
            repo_id,
            "sample",
            vec![],
            5,
            100,
            SamplePayload("root".to_owned()),
            &alice,
        )
        .await
        .unwrap();
        let valid_root_id = valid_root.op_id().unwrap();
        let regressed = DagOp::sign_new(
            repo_id,
            "sample",
            vec![valid_root_id],
            5,
            101,
            SamplePayload("bad clock".to_owned()),
            &alice,
        )
        .await
        .unwrap();
        let mut bad_clock_dag = Dag::new();
        bad_clock_dag.insert_unchecked(valid_root).unwrap();
        bad_clock_dag.insert_unchecked(regressed).unwrap();
        assert!(matches!(
            bad_clock_dag.topological_order(),
            Err(CobError::InvalidLamport { .. })
        ));
    }
}