converge-core 2.0.0

Converge Agent OS - correctness-first, context-driven multi-agent runtime
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
// Copyright 2024-2026 Reflective Labs
// SPDX-License-Identifier: MIT

//! Integrity primitives for Converge.
//!
//! This module provides cryptographic and causal ordering primitives that can
//! be used alongside the core Context and Fact types to add integrity features:
//!
//! - **Lamport Clock**: Provides causal ordering of events without wall clocks
//! - **Content Hash**: SHA-256 hash of content for tamper detection
//! - **Merkle Root**: Cryptographic commitment to a set of facts for audit verification
//!
//! # Example
//!
//! ```
//! use converge_core::integrity::{LamportClock, ContentHash, MerkleRoot};
//!
//! // Lamport clock for causal ordering
//! let mut clock = LamportClock::new();
//! let t1 = clock.tick(); // Event 1
//! let t2 = clock.tick(); // Event 2 (causally after Event 1)
//!
//! // Content hash for integrity
//! let hash = ContentHash::compute("important data");
//! assert!(hash.verify("important data"));
//!
//! // Merkle root for audit trail
//! let hashes = vec![
//!     ContentHash::compute("fact 1"),
//!     ContentHash::compute("fact 2"),
//! ];
//! let root = MerkleRoot::compute(&hashes);
//! ```

use serde::{Deserialize, Serialize};

use crate::context::{Context, ContextKey, Fact};

// ============================================================================
// Lamport Clock
// ============================================================================

/// A Lamport logical clock for causal ordering of events.
///
/// Lamport clocks provide a partial ordering of events in a distributed system
/// without requiring synchronized wall clocks. The key property is:
/// if event A happened-before event B, then `clock(A) < clock(B)`.
///
/// # Example
///
/// ```
/// use converge_core::integrity::LamportClock;
///
/// let mut clock = LamportClock::new();
/// assert_eq!(clock.time(), 0);
///
/// clock.tick();
/// assert_eq!(clock.time(), 1);
///
/// // When receiving a message with clock=5, update to max+1
/// clock.update(5);
/// assert_eq!(clock.time(), 6);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
pub struct LamportClock {
    time: u64,
}

impl LamportClock {
    /// Creates a new Lamport clock initialized to 0.
    #[must_use]
    pub const fn new() -> Self {
        Self { time: 0 }
    }

    /// Returns the current logical time.
    #[must_use]
    pub const fn time(&self) -> u64 {
        self.time
    }

    /// Increments the clock and returns the new time.
    /// Called before any local event (e.g., creating a fact).
    pub fn tick(&mut self) -> u64 {
        self.time += 1;
        self.time
    }

    /// Updates the clock based on a received timestamp.
    /// Sets clock to `max(local, received) + 1`.
    /// Called when receiving facts from another source.
    pub fn update(&mut self, received: u64) -> u64 {
        self.time = self.time.max(received) + 1;
        self.time
    }
}

// ============================================================================
// Content Hash
// ============================================================================

/// Error type for ContentHash operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContentHashError {
    /// Invalid hexadecimal character.
    InvalidHex,
    /// Invalid string length.
    InvalidLength,
}

impl std::fmt::Display for ContentHashError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidHex => write!(f, "invalid hexadecimal character"),
            Self::InvalidLength => write!(f, "invalid string length (expected 64 hex chars)"),
        }
    }
}

impl std::error::Error for ContentHashError {}

/// A hash of content for integrity verification.
///
/// Content hashes enable:
/// - Tamper detection: any change to content changes the hash
/// - Efficient comparison: compare 32 bytes instead of full content
/// - Merkle tree construction: hashes combine into a tree
///
/// # Deprecation Notice
///
/// In converge-core v2.0.0, SHA-256 was replaced with a non-cryptographic stub
/// (FNV-1a) to eliminate the sha2 dependency. For cryptographic hashing, use
/// `converge-runtime` with a `Fingerprint` implementation.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ContentHash(pub [u8; 32]);

impl ContentHash {
    /// Computes a hash of the given content.
    ///
    /// # Deprecation Notice
    ///
    /// This method currently uses a stub implementation (FNV-1a hash padded to 32 bytes).
    /// For cryptographic hashing, use `converge-runtime` with a `Fingerprint` implementation.
    #[deprecated(
        since = "2.0.0",
        note = "Use converge-runtime with Fingerprint trait for cryptographic hashing"
    )]
    #[must_use]
    pub fn compute(content: &str) -> Self {
        // Stub: FNV-1a hash (non-cryptographic, but deterministic)
        let mut hash = 0xcbf2_9ce4_8422_2325_u64; // FNV offset basis
        for byte in content.as_bytes() {
            hash ^= u64::from(*byte);
            hash = hash.wrapping_mul(0x0100_0000_01b3); // FNV prime
        }
        // Pad to 32 bytes (repeat the 8-byte hash 4 times)
        let bytes = hash.to_le_bytes();
        let mut result = [0u8; 32];
        for i in 0..4 {
            result[i * 8..(i + 1) * 8].copy_from_slice(&bytes);
        }
        Self(result)
    }

    /// Computes the hash of a Fact (combines key, id, and content).
    ///
    /// # Deprecation Notice
    ///
    /// This method currently uses a stub implementation. For cryptographic hashing,
    /// use `converge-runtime` with a `Fingerprint` implementation.
    #[deprecated(
        since = "2.0.0",
        note = "Use converge-runtime with Fingerprint trait for cryptographic hashing"
    )]
    #[must_use]
    pub fn compute_fact(fact: &Fact) -> Self {
        let combined = format!("{:?}|{}|{}", fact.key, fact.id, fact.content);
        #[allow(deprecated)]
        Self::compute(&combined)
    }

    /// Combines two hashes (for Merkle tree internal nodes).
    ///
    /// # Deprecation Notice
    ///
    /// This method currently uses a stub implementation (FNV-1a on concatenated hashes).
    /// For cryptographic hash combination, use `converge-runtime` with a `Fingerprint` implementation.
    #[deprecated(
        since = "2.0.0",
        note = "Use converge-runtime with Fingerprint trait for cryptographic hashing"
    )]
    #[must_use]
    pub fn combine(left: &Self, right: &Self) -> Self {
        // Hash the concatenation of both hashes using FNV-1a
        let mut hash = 0xcbf2_9ce4_8422_2325_u64;
        for byte in left.0.iter().chain(right.0.iter()) {
            hash ^= u64::from(*byte);
            hash = hash.wrapping_mul(0x0100_0000_01b3);
        }
        let bytes = hash.to_le_bytes();
        let mut result = [0u8; 32];
        for i in 0..4 {
            result[i * 8..(i + 1) * 8].copy_from_slice(&bytes);
        }
        Self(result)
    }

    /// Verifies that this hash matches the given content.
    #[must_use]
    pub fn verify(&self, content: &str) -> bool {
        #[allow(deprecated)]
        let computed = Self::compute(content);
        *self == computed
    }

    /// Returns the hash as a hex string.
    #[must_use]
    pub fn to_hex(&self) -> String {
        self.0.iter().map(|b| format!("{b:02x}")).collect()
    }

    /// Creates a `ContentHash` from a hex string.
    ///
    /// # Errors
    ///
    /// Returns an error if the string is not valid hex or wrong length.
    pub fn from_hex(s: &str) -> Result<Self, ContentHashError> {
        if s.len() != 64 {
            return Err(ContentHashError::InvalidLength);
        }
        let mut result = [0u8; 32];
        for (i, chunk) in s.as_bytes().chunks(2).enumerate() {
            let high = Self::hex_char_to_nibble(chunk[0])?;
            let low = Self::hex_char_to_nibble(chunk[1])?;
            result[i] = (high << 4) | low;
        }
        Ok(Self(result))
    }

    fn hex_char_to_nibble(c: u8) -> Result<u8, ContentHashError> {
        match c {
            b'0'..=b'9' => Ok(c - b'0'),
            b'a'..=b'f' => Ok(c - b'a' + 10),
            b'A'..=b'F' => Ok(c - b'A' + 10),
            _ => Err(ContentHashError::InvalidHex),
        }
    }
}

impl std::fmt::Display for ContentHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", &self.to_hex()[..16]) // Short form for display
    }
}

// ============================================================================
// Merkle Tree
// ============================================================================

/// A Merkle tree root hash representing the integrity of a set of facts.
///
/// The Merkle root changes if any fact is added, modified, or reordered.
/// This enables:
/// - Tamper detection: compare roots to verify integrity
/// - Efficient sync: different roots mean different states
/// - Audit proofs: prove a fact exists without revealing all facts
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MerkleRoot(pub ContentHash);

impl MerkleRoot {
    /// Computes the Merkle root from a list of content hashes.
    ///
    /// Uses a standard binary Merkle tree construction.
    /// Empty list returns a hash of empty string.
    /// Single element is combined with itself (Bitcoin-style).
    #[allow(deprecated)]
    #[must_use]
    pub fn compute(hashes: &[ContentHash]) -> Self {
        if hashes.is_empty() {
            return Self(ContentHash::compute(""));
        }

        let mut current_level: Vec<ContentHash> = hashes.to_vec();

        // Keep combining until we reach a single root
        // For a single element, we still iterate once to combine it with itself
        loop {
            if current_level.len() == 1 {
                // If we started with 1 element, combine with itself
                // If we reduced to 1 element through combinations, we're done
                if hashes.len() == 1 {
                    return Self(ContentHash::combine(&current_level[0], &current_level[0]));
                }
                return Self(current_level.into_iter().next().unwrap());
            }

            let mut next_level = Vec::new();

            for chunk in current_level.chunks(2) {
                let combined = if chunk.len() == 2 {
                    ContentHash::combine(&chunk[0], &chunk[1])
                } else {
                    // Odd number: duplicate the last hash
                    ContentHash::combine(&chunk[0], &chunk[0])
                };
                next_level.push(combined);
            }

            current_level = next_level;
        }
    }

    /// Computes the Merkle root from a Context's facts.
    ///
    /// Facts are hashed in deterministic order (by key, then by position).
    #[allow(deprecated)]
    #[must_use]
    pub fn from_context(ctx: &Context) -> Self {
        let mut all_hashes: Vec<ContentHash> = Vec::new();
        let mut keys: Vec<_> = ctx.all_keys();
        keys.sort();

        for key in keys {
            for fact in ctx.get(key) {
                all_hashes.push(ContentHash::compute_fact(fact));
            }
        }

        Self::compute(&all_hashes)
    }

    /// Returns the root hash as a hex string.
    #[must_use]
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }
}

// ============================================================================
// Tracked Context
// ============================================================================

/// A wrapper around Context that tracks integrity metadata.
///
/// This provides optional integrity tracking without modifying the core types.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrackedContext {
    /// The underlying context.
    pub context: Context,
    /// Lamport clock for causal ordering.
    pub clock: LamportClock,
    /// Cached Merkle root (invalidated on changes).
    merkle_root: Option<MerkleRoot>,
    /// Hash of each fact (by key and index).
    fact_hashes: Vec<(ContextKey, String, ContentHash)>,
}

impl TrackedContext {
    /// Creates a new tracked context wrapping an existing context.
    #[must_use]
    pub fn new(context: Context) -> Self {
        let mut tracked = Self {
            context,
            clock: LamportClock::new(),
            merkle_root: None,
            fact_hashes: Vec::new(),
        };
        tracked.recompute_hashes();
        tracked
    }

    /// Creates an empty tracked context.
    #[must_use]
    pub fn empty() -> Self {
        Self::new(Context::new())
    }

    /// Returns the current Lamport clock time.
    #[must_use]
    pub fn clock_time(&self) -> u64 {
        self.clock.time()
    }

    /// Ticks the clock and returns the new time.
    pub fn tick(&mut self) -> u64 {
        self.clock.tick()
    }

    /// Computes and returns the Merkle root.
    #[must_use]
    pub fn merkle_root(&mut self) -> &MerkleRoot {
        if self.merkle_root.is_none() {
            self.merkle_root = Some(MerkleRoot::from_context(&self.context));
        }
        self.merkle_root.as_ref().unwrap()
    }

    /// Verifies the integrity of all facts.
    ///
    /// Returns `true` if all recorded hashes match current fact content.
    #[allow(deprecated)]
    #[must_use]
    pub fn verify_integrity(&self) -> bool {
        for (key, id, expected_hash) in &self.fact_hashes {
            if let Some(fact) = self.context.get(*key).iter().find(|f| &f.id == id) {
                if ContentHash::compute_fact(fact) != *expected_hash {
                    return false;
                }
            } else {
                return false; // Fact missing
            }
        }
        true
    }

    /// Recomputes all fact hashes.
    #[allow(deprecated)]
    fn recompute_hashes(&mut self) {
        self.fact_hashes.clear();
        for key in self.context.all_keys() {
            for fact in self.context.get(key) {
                let hash = ContentHash::compute_fact(fact);
                self.fact_hashes.push((key, fact.id.clone(), hash));
            }
        }
        self.merkle_root = None; // Invalidate cached root
    }

    /// Adds a fact to the underlying context and updates tracking.
    ///
    /// # Errors
    ///
    /// Returns an error if the fact conflicts with an existing fact.
    #[allow(deprecated)]
    pub fn add_fact(&mut self, fact: Fact) -> Result<bool, crate::error::ConvergeError> {
        let key = fact.key;
        let id = fact.id.clone();
        let hash = ContentHash::compute_fact(&fact);

        let changed = self.context.add_fact(fact)?;

        if changed {
            self.fact_hashes.push((key, id, hash));
            self.merkle_root = None; // Invalidate cached root
            self.clock.tick();
        }

        Ok(changed)
    }
}

impl Default for TrackedContext {
    fn default() -> Self {
        Self::empty()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // =========================================================================
    // Lamport Clock Tests
    // =========================================================================

    #[test]
    fn lamport_clock_starts_at_zero() {
        let clock = LamportClock::new();
        assert_eq!(clock.time(), 0);
    }

    #[test]
    fn lamport_clock_tick_increments() {
        let mut clock = LamportClock::new();
        assert_eq!(clock.tick(), 1);
        assert_eq!(clock.tick(), 2);
        assert_eq!(clock.tick(), 3);
    }

    #[test]
    fn lamport_clock_update_takes_max_plus_one() {
        let mut clock = LamportClock::new();
        clock.tick(); // 1
        clock.tick(); // 2

        // Received message with clock=5, should become 6
        assert_eq!(clock.update(5), 6);

        // Received message with clock=3, should become 7 (max(6,3)+1)
        assert_eq!(clock.update(3), 7);
    }

    // =========================================================================
    // Content Hash Tests
    // =========================================================================

    #[test]
    #[allow(deprecated)]
    fn content_hash_is_deterministic() {
        let h1 = ContentHash::compute("hello world");
        let h2 = ContentHash::compute("hello world");
        assert_eq!(h1, h2);
    }

    #[test]
    #[allow(deprecated)]
    fn content_hash_changes_with_content() {
        let h1 = ContentHash::compute("hello");
        let h2 = ContentHash::compute("world");
        assert_ne!(h1, h2);
    }

    #[test]
    #[allow(deprecated)]
    fn content_hash_verify_works() {
        let hash = ContentHash::compute("test");
        assert!(hash.verify("test"));
        assert!(!hash.verify("modified"));
    }

    #[test]
    #[allow(deprecated)]
    fn content_hash_hex_roundtrip() {
        let original = ContentHash::compute("test content");
        let hex = original.to_hex();
        let restored = ContentHash::from_hex(&hex).unwrap();
        assert_eq!(original, restored);
    }

    // =========================================================================
    // Merkle Tree Tests
    // =========================================================================

    #[test]
    #[allow(deprecated)]
    fn merkle_root_empty_list() {
        let root = MerkleRoot::compute(&[]);
        let empty_hash = ContentHash::compute("");
        assert_eq!(root.0, empty_hash);
    }

    #[test]
    #[allow(deprecated)]
    fn merkle_root_single_element() {
        let h = ContentHash::compute("only element");
        let root = MerkleRoot::compute(std::slice::from_ref(&h));
        let expected = ContentHash::combine(&h, &h);
        assert_eq!(root.0, expected);
    }

    #[test]
    #[allow(deprecated)]
    fn merkle_root_two_elements() {
        let h1 = ContentHash::compute("first");
        let h2 = ContentHash::compute("second");
        let root = MerkleRoot::compute(&[h1.clone(), h2.clone()]);
        let expected = ContentHash::combine(&h1, &h2);
        assert_eq!(root.0, expected);
    }

    #[test]
    #[allow(deprecated)]
    fn merkle_root_is_deterministic() {
        let hashes = vec![
            ContentHash::compute("a"),
            ContentHash::compute("b"),
            ContentHash::compute("c"),
        ];
        let root1 = MerkleRoot::compute(&hashes);
        let root2 = MerkleRoot::compute(&hashes);
        assert_eq!(root1, root2);
    }

    #[test]
    #[allow(deprecated)]
    fn merkle_root_changes_with_different_content() {
        let hashes1 = vec![ContentHash::compute("a"), ContentHash::compute("b")];
        let hashes2 = vec![ContentHash::compute("a"), ContentHash::compute("c")];
        let root1 = MerkleRoot::compute(&hashes1);
        let root2 = MerkleRoot::compute(&hashes2);
        assert_ne!(root1, root2);
    }

    // =========================================================================
    // Tracked Context Tests
    // =========================================================================

    #[test]
    fn tracked_context_starts_empty() {
        let tracked = TrackedContext::empty();
        assert_eq!(tracked.clock_time(), 0);
        assert!(!tracked.context.has(ContextKey::Seeds));
    }

    #[test]
    fn tracked_context_ticks_on_add() {
        let mut tracked = TrackedContext::empty();
        assert_eq!(tracked.clock_time(), 0);

        tracked
            .add_fact(Fact::new(ContextKey::Seeds, "s1", "seed"))
            .unwrap();
        assert_eq!(tracked.clock_time(), 1);

        tracked
            .add_fact(Fact::new(ContextKey::Seeds, "s2", "seed2"))
            .unwrap();
        assert_eq!(tracked.clock_time(), 2);
    }

    #[test]
    fn tracked_context_computes_merkle_root() {
        let mut tracked = TrackedContext::empty();
        tracked
            .add_fact(Fact::new(ContextKey::Seeds, "s1", "first"))
            .unwrap();
        tracked
            .add_fact(Fact::new(ContextKey::Seeds, "s2", "second"))
            .unwrap();

        let root1 = tracked.merkle_root().clone();

        // Adding another fact changes the root
        tracked
            .add_fact(Fact::new(ContextKey::Seeds, "s3", "third"))
            .unwrap();
        let root2 = tracked.merkle_root().clone();

        assert_ne!(root1, root2);
    }

    #[test]
    fn tracked_context_verifies_integrity() {
        let mut tracked = TrackedContext::empty();
        tracked
            .add_fact(Fact::new(ContextKey::Seeds, "s1", "test"))
            .unwrap();

        assert!(tracked.verify_integrity());
    }
}