Skip to main content

cbcl_core/
store.rs

1//! Message store with G-Set CRDT semantics (REQ-300, REQ-309, ADR-008).
2//!
3//! Provides [`HashIndex`] for O(1) lookup and [`ThreadedMessageStore`] for
4//! append-only, deduplicated, per-thread message storage.
5//!
6//! The store is a join-semilattice (REQ-300): messages are the elements,
7//! `:caused-by` links form the covers relation (REQ-301), fan-in is join,
8//! and causal closure computes the principal ideal.
9//!
10//! Also provides [`CausalClosureBundle`] for transferring verifiable subsets
11//! of the message store (REQ-311, REQ-212).
12
13#![forbid(unsafe_code)]
14
15use crate::attest::AttestError;
16use crate::envelope::{verify_opened, OpenedEnvelope, OpenedError, RedactedEnvelope};
17use crate::message::{CausedBy, Message};
18use crate::protocol::{CausalProtocol, CausalViolation, VerificationResult};
19use crate::r4::Signer;
20use crate::sexpr::{Atom, SExpr};
21use crate::typed_addr::FieldId;
22use alloc::string::String;
23use alloc::vec;
24use alloc::vec::Vec;
25use core::fmt;
26use hashbrown::{HashMap, HashSet};
27
28/// Content-addressed hash identifying a message (SHA-256 hex string).
29#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
31pub struct ContentHash(pub String);
32
33/// Thread identifier scoping causal chains (ADR-008).
34#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
36pub struct ThreadId(pub String);
37
38/// Thread-scoped hash index for O(1) message lookup (REQ-309).
39///
40/// Each entry maps a [`ContentHash`] to its owning [`ThreadId`] and position
41/// index within that thread. Lookups enforce thread isolation per ADR-008:
42/// a lookup for hash H in thread T returns `None` if H belongs to thread T'.
43///
44/// Memory budget: <= 64 bytes per entry (NFR-303).
45#[derive(Debug, Clone)]
46pub struct HashIndex {
47    map: HashMap<ContentHash, (ThreadId, usize)>,
48}
49
50impl HashIndex {
51    /// Creates an empty hash index.
52    pub fn new() -> Self {
53        Self {
54            map: HashMap::new(),
55        }
56    }
57
58    /// Creates an empty hash index with pre-allocated capacity.
59    pub fn with_capacity(capacity: usize) -> Self {
60        Self {
61            map: HashMap::with_capacity(capacity),
62        }
63    }
64
65    /// Inserts a content hash mapped to a thread and position index.
66    ///
67    /// Returns `true` if the entry was newly inserted, `false` if the hash
68    /// already existed (duplicate — entry is not overwritten).
69    pub fn insert(&mut self, hash: ContentHash, thread: ThreadId, index: usize) -> bool {
70        use hashbrown::hash_map::Entry;
71        match self.map.entry(hash) {
72            Entry::Vacant(e) => {
73                e.insert((thread, index));
74                true
75            }
76            Entry::Occupied(_) => false,
77        }
78    }
79
80    /// Looks up a content hash, enforcing thread isolation (ADR-008).
81    ///
82    /// Returns `Some(index)` only if the hash exists AND belongs to the given thread.
83    /// Returns `None` if the hash is absent or belongs to a different thread.
84    pub fn lookup(&self, hash: &ContentHash, thread: &ThreadId) -> Option<usize> {
85        self.map
86            .get(hash)
87            .and_then(|(t, idx)| if t == thread { Some(*idx) } else { None })
88    }
89
90    /// Checks whether a content hash exists in the given thread (ADR-008).
91    ///
92    /// Returns `true` only if the hash exists AND belongs to the given thread.
93    pub fn contains(&self, hash: &ContentHash, thread: &ThreadId) -> bool {
94        self.lookup(hash, thread).is_some()
95    }
96
97    /// Rebuilds the index from an iterator of `(ContentHash, ThreadId, usize)` triples.
98    ///
99    /// Clears the existing index and repopulates from the iterator.
100    /// Duplicates in the iterator are silently skipped (first wins).
101    pub fn rebuild<I>(&mut self, iter: I)
102    where
103        I: IntoIterator<Item = (ContentHash, ThreadId, usize)>,
104    {
105        self.map.clear();
106        for (hash, thread, index) in iter {
107            self.insert(hash, thread, index);
108        }
109    }
110
111    /// Returns the number of entries in the index.
112    pub fn len(&self) -> usize {
113        self.map.len()
114    }
115
116    /// Returns `true` if the index contains no entries.
117    pub fn is_empty(&self) -> bool {
118        self.map.is_empty()
119    }
120}
121
122impl Default for HashIndex {
123    fn default() -> Self {
124        Self::new()
125    }
126}
127
128/// Trait for an append-only message store with G-Set CRDT semantics (REQ-300).
129// Opaque native repeat facts; construction computes positions, never accepts ranks.
130pub use crate::repeat::{MaterializedPositions, PositionContext, PositionMetadata};
131
132pub trait MessageStore {
133    /// Optional independently admitted or snapshot-attested native position cache.
134    /// Implementations must bind installation to the same code/root/thread. The
135    /// resolver checks that binding again; default None preserves legacy behavior.
136    fn materialized_positions(&self) -> Option<&MaterializedPositions> {
137        None
138    }
139
140    /// Look up a message by content hash across all threads.
141    fn lookup(&self, hash: &ContentHash) -> Option<&Message>;
142
143    /// Look up a message by content hash within a specific thread (ADR-008).
144    fn lookup_in_thread(&self, hash: &ContentHash, thread: &ThreadId) -> Option<&Message>;
145
146    /// Check whether a content hash exists in the given thread.
147    fn contains(&self, hash: &ContentHash, thread: &ThreadId) -> bool;
148
149    /// Append a message to a thread. Returns `false` if the hash already exists
150    /// (deduplication per REQ-310). Returns `true` if newly inserted.
151    fn append(&mut self, hash: ContentHash, thread: ThreadId, message: Message) -> bool;
152
153    /// Returns the frontier (leaf messages) of a thread — messages not referenced
154    /// by any other message's `:caused-by` in the same thread.
155    fn frontier(&self, thread: &ThreadId) -> Vec<&ContentHash>;
156
157    /// Returns the causal closure (principal ideal) of a message — all messages
158    /// reachable by transitively following `:caused-by` links back to root(s).
159    fn causal_closure(&self, hash: &ContentHash, thread: &ThreadId) -> Vec<ContentHash>;
160
161    /// Look up a redacted envelope by the content hash of the message it
162    /// redacts, scoped to the envelope's *authenticated* thread (SPEC-015
163    /// REQ-702).
164    ///
165    /// This is the safety-level seam: `protocol::verify_causal` falls back
166    /// to it when a `:caused-by` reference has no full message, reading
167    /// only the envelope's authenticated performative type. The
168    /// completion-level occupant fan-in (`projection.rs`, REQ-618)
169    /// deliberately never consults it (REQ-703).
170    ///
171    /// Default: no envelope shelf (stores predating SPEC-015 change
172    /// nothing and keep their exact v1 behaviour).
173    fn envelope_in_thread(
174        &self,
175        hash: &ContentHash,
176        thread: &ThreadId,
177    ) -> Option<&RedactedEnvelope> {
178        let _ = (hash, thread);
179        None
180    }
181
182    /// Look up an opened envelope by the typed content root of the message
183    /// it opens, scoped to the envelope's *authenticated* Thread opening
184    /// (SPEC-017 REQ-813).
185    ///
186    /// The Stage-3 native-openings counterpart of [`Self::envelope_in_thread`]:
187    /// `protocol::verify_causal` falls back to it for the safety-level
188    /// predecessor type when a `:caused-by` reference has no full message,
189    /// reading only the envelope's authenticated Performative opening. The
190    /// completion-level occupant fan-in (`projection.rs`, REQ-703) never
191    /// consults it — that boundary is preserved exactly as for redacted
192    /// envelopes.
193    ///
194    /// Default: no opened shelf (stores that never accept opened envelopes
195    /// keep their exact behaviour).
196    fn opened_in_thread(&self, hash: &ContentHash, thread: &ThreadId) -> Option<&OpenedEnvelope> {
197        let _ = (hash, thread);
198        None
199    }
200}
201
202/// Per-thread append-only message store with G-Set CRDT semantics (REQ-300).
203///
204/// Uses [`HashIndex`] for O(1) lookup (REQ-309) and deduplication (REQ-310).
205/// Maintains a frontier set per thread for efficient leaf queries.
206#[derive(Debug, Clone)]
207pub struct ThreadedMessageStore {
208    /// Per-thread message storage: `ThreadId -> Vec<(ContentHash, Message)>`.
209    threads: HashMap<ThreadId, Vec<(ContentHash, Message)>>,
210    /// Global hash index for O(1) lookup.
211    index: HashIndex,
212    /// Per-thread set of hashes referenced by some message's `:caused-by`.
213    referenced: HashMap<ThreadId, HashSet<ContentHash>>,
214    /// Redacted-envelope shelf (SPEC-015 REQ-702), keyed by the content
215    /// hash of the redacted message. Thread placement is the envelope's
216    /// authenticated thread field, checked at lookup — an envelope can
217    /// never be filed under a thread its signature does not vouch for.
218    envelopes: HashMap<ContentHash, RedactedEnvelope>,
219    /// Opened-envelope shelf (SPEC-017 REQ-813), keyed by the typed content
220    /// root of the opened message. Thread placement is the envelope's
221    /// authenticated Thread opening, checked at lookup — as for the redacted
222    /// shelf, an opened envelope can never be filed under a thread its
223    /// signature and opening do not vouch for.
224    opened: HashMap<ContentHash, OpenedEnvelope>,
225}
226
227impl ThreadedMessageStore {
228    /// Creates an empty message store.
229    pub fn new() -> Self {
230        Self {
231            threads: HashMap::new(),
232            index: HashIndex::new(),
233            referenced: HashMap::new(),
234            envelopes: HashMap::new(),
235            opened: HashMap::new(),
236        }
237    }
238
239    /// Accept a redacted envelope (SPEC-015 REQ-702).
240    ///
241    /// Verifies the envelope's R4 v2 attestation from its own fields first
242    /// (`signer` embodies verification for the envelope's sender key), then
243    /// places it in the thread its *authenticated* thread field names —
244    /// there is deliberately no thread parameter, so cross-thread injection
245    /// of a genuine envelope is a signature failure at the source, not a
246    /// policy question. An unverifiable envelope is never stored.
247    ///
248    /// Returns `Ok(true)` if newly shelved, `Ok(false)` if an envelope for
249    /// this content hash is already present (G-Set dedup, as for messages).
250    pub fn append_envelope(
251        &mut self,
252        envelope: RedactedEnvelope,
253        signer: &dyn Signer,
254    ) -> Result<bool, AttestError> {
255        envelope.verify(signer)?;
256        use hashbrown::hash_map::Entry;
257        match self
258            .envelopes
259            .entry(ContentHash(envelope.header.content_hash.clone()))
260        {
261            Entry::Vacant(e) => {
262                e.insert(envelope);
263                Ok(true)
264            }
265            Entry::Occupied(_) => Ok(false),
266        }
267    }
268
269    /// Accept an opened envelope (SPEC-017 REQ-813).
270    ///
271    /// Verifies the v3 root-signature and every field-opening from the
272    /// envelope's own fields first (`signer` embodies verification for the
273    /// sender key), then shelves it under its typed root, placed in the
274    /// thread its *authenticated* Thread opening names. As with
275    /// [`Self::append_envelope`] there is deliberately no thread parameter,
276    /// so cross-thread injection of a genuine envelope is a signature/opening
277    /// failure at the source, not a policy question; an envelope that does
278    /// not open its Thread leaf cannot be placed (fail closed).
279    ///
280    /// Returns `Ok(true)` if newly shelved, `Ok(false)` if an opened
281    /// envelope for this root is already present (G-Set dedup).
282    pub fn append_opened(
283        &mut self,
284        envelope: OpenedEnvelope,
285        signer: &dyn Signer,
286    ) -> Result<bool, OpenedError> {
287        verify_opened(&envelope, signer)?;
288        // Thread placement is by an *authenticated* opening; an envelope
289        // whose Thread leaf is not opened has no place to go.
290        if envelope.thread().is_none() {
291            return Err(OpenedError::MissingField {
292                field: FieldId::Thread,
293            });
294        }
295        use hashbrown::hash_map::Entry;
296        match self.opened.entry(ContentHash(envelope.root.clone())) {
297            Entry::Vacant(e) => {
298                e.insert(envelope);
299                Ok(true)
300            }
301            Entry::Occupied(_) => Ok(false),
302        }
303    }
304}
305
306impl Default for ThreadedMessageStore {
307    fn default() -> Self {
308        Self::new()
309    }
310}
311
312impl MessageStore for ThreadedMessageStore {
313    fn lookup(&self, hash: &ContentHash) -> Option<&Message> {
314        // Look up in the global index (ignoring thread isolation)
315        let (thread, idx) = self.index.map.get(hash)?;
316        self.threads
317            .get(thread)
318            .and_then(|msgs| msgs.get(*idx).map(|(_, m)| m))
319    }
320
321    fn lookup_in_thread(&self, hash: &ContentHash, thread: &ThreadId) -> Option<&Message> {
322        let idx = self.index.lookup(hash, thread)?;
323        self.threads
324            .get(thread)
325            .and_then(|msgs| msgs.get(idx).map(|(_, m)| m))
326    }
327
328    fn contains(&self, hash: &ContentHash, thread: &ThreadId) -> bool {
329        self.index.contains(hash, thread)
330    }
331
332    fn append(&mut self, hash: ContentHash, thread: ThreadId, message: Message) -> bool {
333        let thread_msgs = self.threads.entry(thread.clone()).or_default();
334        let idx = thread_msgs.len();
335
336        if !self.index.insert(hash.clone(), thread.clone(), idx) {
337            return false; // duplicate
338        }
339
340        // Track caused-by references for frontier computation
341        if let Some(cb) = message.caused_by() {
342            let refs = self.referenced.entry(thread.clone()).or_default();
343            match cb {
344                CausedBy::Begin => {}
345                CausedBy::Single(h) => {
346                    refs.insert(ContentHash(h.clone()));
347                }
348                CausedBy::Multiple(hs) => {
349                    for h in hs {
350                        refs.insert(ContentHash(h.clone()));
351                    }
352                }
353            }
354        }
355
356        thread_msgs.push((hash, message));
357        true
358    }
359
360    fn frontier(&self, thread: &ThreadId) -> Vec<&ContentHash> {
361        let Some(msgs) = self.threads.get(thread) else {
362            return Vec::new();
363        };
364        let empty = HashSet::new();
365        let refs = self.referenced.get(thread).unwrap_or(&empty);
366        msgs.iter()
367            .map(|(h, _)| h)
368            .filter(|h| !refs.contains(*h))
369            .collect()
370    }
371
372    fn causal_closure(&self, hash: &ContentHash, thread: &ThreadId) -> Vec<ContentHash> {
373        let mut result = Vec::new();
374        let mut visited = HashSet::new();
375        let mut stack = Vec::new();
376
377        if self.index.contains(hash, thread) {
378            stack.push(hash.clone());
379        }
380
381        while let Some(current) = stack.pop() {
382            if !visited.insert(current.clone()) {
383                continue;
384            }
385            result.push(current.clone());
386
387            // Look up the message and follow its caused-by links
388            if let Some(msg) = self.lookup_in_thread(&current, thread) {
389                if let Some(cb) = msg.caused_by() {
390                    match cb {
391                        CausedBy::Begin => {}
392                        CausedBy::Single(h) => {
393                            let ch = ContentHash(h.clone());
394                            if !visited.contains(&ch) {
395                                stack.push(ch);
396                            }
397                        }
398                        CausedBy::Multiple(hs) => {
399                            for h in hs {
400                                let ch = ContentHash(h.clone());
401                                if !visited.contains(&ch) {
402                                    stack.push(ch);
403                                }
404                            }
405                        }
406                    }
407                }
408            }
409        }
410
411        result
412    }
413
414    fn envelope_in_thread(
415        &self,
416        hash: &ContentHash,
417        thread: &ThreadId,
418    ) -> Option<&RedactedEnvelope> {
419        // Thread scoping is by the envelope's authenticated field (REQ-702):
420        // the shelf never records a caller-chosen thread to compare against.
421        self.envelopes
422            .get(hash)
423            .filter(|e| e.header.thread == thread.0)
424    }
425
426    fn opened_in_thread(&self, hash: &ContentHash, thread: &ThreadId) -> Option<&OpenedEnvelope> {
427        // Thread scoping is by the envelope's authenticated Thread opening
428        // (REQ-813): the shelf holds no caller-chosen thread to compare.
429        self.opened
430            .get(hash)
431            .filter(|e| e.thread() == Some(thread.0.as_str()))
432    }
433}
434
435// ================================================================
436// Causal Closure Bundle (REQ-311, REQ-212, CON-304)
437// ================================================================
438
439/// Error during causal closure extraction.
440#[derive(Debug, Clone, PartialEq, Eq)]
441#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
442pub enum ClosureError {
443    /// Target message not found in the store.
444    TargetNotFound,
445    /// Store is incomplete — some `:caused-by` hashes are missing.
446    IncompleteStore { missing_hashes: Vec<ContentHash> },
447}
448
449impl fmt::Display for ClosureError {
450    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451        match self {
452            Self::TargetNotFound => write!(f, "target message not found in store"),
453            Self::IncompleteStore { missing_hashes } => {
454                write!(f, "incomplete store, missing hashes: ")?;
455                for (i, h) in missing_hashes.iter().enumerate() {
456                    if i > 0 {
457                        write!(f, ", ")?;
458                    }
459                    write!(f, "{}", h.0)?;
460                }
461                Ok(())
462            }
463        }
464    }
465}
466
467/// Error during bundle verification.
468#[derive(Debug, Clone, PartialEq, Eq)]
469#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
470pub enum BundleVerificationError {
471    /// A message's content hash does not match its computed hash.
472    HashMismatch {
473        hash: ContentHash,
474        expected: ContentHash,
475        computed: ContentHash,
476    },
477    /// A `:caused-by` hash does not resolve within the bundle.
478    DanglingReference { caused_by: String },
479    /// A causal link violates the protocol declaration.
480    CausalViolation(CausalViolation),
481}
482
483impl fmt::Display for BundleVerificationError {
484    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
485        match self {
486            Self::HashMismatch {
487                hash,
488                expected,
489                computed,
490            } => write!(
491                f,
492                "hash mismatch for {}: expected {}, computed {}",
493                hash.0, expected.0, computed.0
494            ),
495            Self::DanglingReference { caused_by } => {
496                write!(f, "dangling :caused-by reference: {caused_by}")
497            }
498            Self::CausalViolation(v) => write!(f, "causal violation: {v}"),
499        }
500    }
501}
502
503/// Result of merging a bundle into a store.
504#[derive(Debug, Clone, PartialEq, Eq)]
505pub struct MergeResult {
506    /// Number of messages newly added to the store.
507    pub added: usize,
508    /// Number of messages already present (deduplicated).
509    pub deduplicated: usize,
510}
511
512/// A transferable, verifiable subset of the message store (REQ-311, CON-304).
513///
514/// Contains the principal ideal ↓target — all messages reachable by following
515/// `:caused-by` links from the target back to root(s). Messages are stored in
516/// topological order (predecessors before successors).
517#[derive(Debug, Clone, PartialEq, Eq)]
518#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
519pub struct CausalClosureBundle {
520    /// The target message this bundle is the causal closure of.
521    pub target: ContentHash,
522    /// The thread this bundle belongs to.
523    pub thread: ThreadId,
524    /// All messages in ↓target, topologically sorted (predecessors first).
525    /// Each entry is `(content_hash, message)`.
526    pub messages: Vec<(ContentHash, Message)>,
527}
528
529impl CausalClosureBundle {
530    /// Extract the causal closure (principal ideal ↓target) from a store (REQ-311).
531    ///
532    /// Performs a DAG traversal following `:caused-by` links from `target` back
533    /// to root(s). The resulting bundle is topologically sorted: every message
534    /// appears after all of its predecessors.
535    pub fn extract<S: MessageStore>(
536        target: &ContentHash,
537        thread: &ThreadId,
538        store: &S,
539    ) -> Result<Self, ClosureError> {
540        // Verify target exists
541        let target_msg = store
542            .lookup_in_thread(target, thread)
543            .ok_or(ClosureError::TargetNotFound)?;
544
545        // Phase 1: DFS to collect all hashes in the closure
546        let mut visited = HashSet::new();
547        let mut stack = vec![target.clone()];
548        let mut hash_to_msg: Vec<(ContentHash, Message)> = Vec::new();
549        let mut missing = Vec::new();
550
551        // We need the target message; clone it here
552        let _ = target_msg; // used only to verify existence above
553
554        while let Some(current) = stack.pop() {
555            if !visited.insert(current.clone()) {
556                continue;
557            }
558
559            let msg = match store.lookup_in_thread(&current, thread) {
560                Some(m) => m,
561                None => {
562                    missing.push(current);
563                    continue;
564                }
565            };
566
567            hash_to_msg.push((current.clone(), msg.clone()));
568
569            // Follow caused-by links
570            if let Some(cb) = msg.caused_by() {
571                match cb {
572                    CausedBy::Begin => {}
573                    CausedBy::Single(h) => {
574                        let ch = ContentHash(h.clone());
575                        if !visited.contains(&ch) {
576                            stack.push(ch);
577                        }
578                    }
579                    CausedBy::Multiple(hs) => {
580                        for h in hs {
581                            let ch = ContentHash(h.clone());
582                            if !visited.contains(&ch) {
583                                stack.push(ch);
584                            }
585                        }
586                    }
587                }
588            }
589        }
590
591        if !missing.is_empty() {
592            return Err(ClosureError::IncompleteStore {
593                missing_hashes: missing,
594            });
595        }
596
597        // Phase 2: Topological sort (Kahn's algorithm — predecessors before successors)
598        // Use indices into hash_to_msg to avoid lifetime issues.
599        let hash_to_idx: HashMap<ContentHash, usize> = hash_to_msg
600            .iter()
601            .enumerate()
602            .map(|(i, (h, _))| (h.clone(), i))
603            .collect();
604
605        let n = hash_to_msg.len();
606        let mut in_degree: Vec<usize> = alloc::vec![0; n];
607        let mut successors_map: Vec<Vec<usize>> = (0..n).map(|_| Vec::new()).collect();
608
609        // Build edges: for each message, its caused-by predecessors have an edge TO this message
610        for (idx, (_, m)) in hash_to_msg.iter().enumerate() {
611            if let Some(cb) = m.caused_by() {
612                let pred_hashes: Vec<&str> = match cb {
613                    CausedBy::Begin => vec![],
614                    CausedBy::Single(p) => vec![p.as_str()],
615                    CausedBy::Multiple(ps) => ps.iter().map(|p| p.as_str()).collect(),
616                };
617                for p in pred_hashes {
618                    if let Some(&pred_idx) = hash_to_idx.get(&ContentHash(p.into())) {
619                        successors_map[pred_idx].push(idx);
620                        in_degree[idx] += 1;
621                    }
622                }
623            }
624        }
625
626        // Kahn's: start with nodes having in-degree 0
627        let mut queue: Vec<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
628        // Sort by hash for deterministic ordering
629        queue.sort_by(|&a, &b| hash_to_msg[a].0.cmp(&hash_to_msg[b].0));
630
631        let mut sorted_indices: Vec<usize> = Vec::with_capacity(n);
632
633        while let Some(node) = queue.pop() {
634            sorted_indices.push(node);
635            for &succ in &successors_map[node] {
636                in_degree[succ] -= 1;
637                if in_degree[succ] == 0 {
638                    // Insert in sorted position for determinism
639                    let pos = queue.partition_point(|&x| {
640                        hash_to_msg[x].0.cmp(&hash_to_msg[succ].0) == core::cmp::Ordering::Greater
641                    });
642                    queue.insert(pos, succ);
643                }
644            }
645        }
646
647        // Build the sorted messages vec
648        let mut msg_slots: Vec<Option<(ContentHash, Message)>> =
649            hash_to_msg.into_iter().map(Some).collect();
650        let messages: Vec<(ContentHash, Message)> = sorted_indices
651            .into_iter()
652            .filter_map(|i| msg_slots[i].take())
653            .collect();
654
655        Ok(CausalClosureBundle {
656            target: target.clone(),
657            thread: thread.clone(),
658            messages,
659        })
660    }
661
662    /// Verify bundle completeness — all `:caused-by` hashes resolve within the bundle.
663    ///
664    /// This is the Tier 2 verification path (REQ-212): verify that the bundle is
665    /// self-contained. No external store or protocol is needed.
666    pub fn verify_completeness(&self) -> Result<(), Vec<BundleVerificationError>> {
667        let known: HashSet<&str> = self.messages.iter().map(|(h, _)| h.0.as_str()).collect();
668        let mut errors = Vec::new();
669
670        for (_, msg) in &self.messages {
671            if let Some(cb) = msg.caused_by() {
672                let refs: Vec<&str> = match cb {
673                    CausedBy::Begin => vec![],
674                    CausedBy::Single(h) => vec![h.as_str()],
675                    CausedBy::Multiple(hs) => hs.iter().map(|h| h.as_str()).collect(),
676                };
677                for r in refs {
678                    if !known.contains(r) {
679                        errors.push(BundleVerificationError::DanglingReference {
680                            caused_by: r.into(),
681                        });
682                    }
683                }
684            }
685        }
686
687        if errors.is_empty() {
688            Ok(())
689        } else {
690            Err(errors)
691        }
692    }
693
694    /// Verify hash integrity using a caller-supplied hash function.
695    ///
696    /// For each message in the bundle, recomputes the hash from the message content
697    /// and verifies it matches the stored content hash. The hasher function receives
698    /// a reference to a `Message` and should return the computed `ContentHash`
699    /// (typically SHA-256 of the canonical serialisation).
700    pub fn verify_hashes<F>(&self, hasher: F) -> Result<(), Vec<BundleVerificationError>>
701    where
702        F: Fn(&Message) -> ContentHash,
703    {
704        let mut errors = Vec::new();
705
706        for (expected_hash, msg) in &self.messages {
707            let computed = hasher(msg);
708            if &computed != expected_hash {
709                errors.push(BundleVerificationError::HashMismatch {
710                    hash: expected_hash.clone(),
711                    expected: expected_hash.clone(),
712                    computed,
713                });
714            }
715        }
716
717        if errors.is_empty() {
718            Ok(())
719        } else {
720            Err(errors)
721        }
722    }
723
724    /// Verify causal validity against a protocol declaration (Tier 3, REQ-212).
725    ///
726    /// Builds a temporary store from the bundle messages and runs causal
727    /// verification (REQ-203) on each message against the given protocol.
728    pub fn verify_causal(
729        &self,
730        protocol: &CausalProtocol,
731    ) -> Result<(), Vec<BundleVerificationError>> {
732        // Build a temporary store from the bundle
733        let mut temp_store = ThreadedMessageStore::new();
734        for (hash, msg) in &self.messages {
735            temp_store.append(hash.clone(), self.thread.clone(), msg.clone());
736        }
737
738        let mut errors = Vec::new();
739        for (_, msg) in &self.messages {
740            let perf_name = msg.performative().map(|p| p.name()).unwrap_or("");
741
742            let result = crate::protocol::verify_causal(
743                perf_name,
744                msg.caused_by(),
745                &temp_store,
746                protocol,
747                &self.thread,
748            );
749
750            if let VerificationResult::Violation(v) = result {
751                errors.push(BundleVerificationError::CausalViolation(v));
752            }
753        }
754
755        if errors.is_empty() {
756            Ok(())
757        } else {
758            Err(errors)
759        }
760    }
761
762    /// Full verification: completeness + hash integrity + causal validity (Tier 3, REQ-212).
763    ///
764    /// Combines all three verification checks. The hasher function computes
765    /// content hashes; the protocol is used for causal validity checking.
766    pub fn verify_full<F>(
767        &self,
768        hasher: F,
769        protocol: &CausalProtocol,
770    ) -> Result<(), Vec<BundleVerificationError>>
771    where
772        F: Fn(&Message) -> ContentHash,
773    {
774        let mut all_errors = Vec::new();
775
776        if let Err(mut errs) = self.verify_completeness() {
777            all_errors.append(&mut errs);
778        }
779        if let Err(mut errs) = self.verify_hashes(hasher) {
780            all_errors.append(&mut errs);
781        }
782        if let Err(mut errs) = self.verify_causal(protocol) {
783            all_errors.append(&mut errs);
784        }
785
786        if all_errors.is_empty() {
787            Ok(())
788        } else {
789            Err(all_errors)
790        }
791    }
792
793    /// Merge this bundle into a message store (set union with deduplication, REQ-300).
794    ///
795    /// Messages already present in the store are skipped (REQ-310 deduplication).
796    /// Returns counts of newly added and deduplicated messages.
797    pub fn merge<S: MessageStore>(&self, store: &mut S) -> MergeResult {
798        let mut added = 0;
799        let mut deduplicated = 0;
800
801        for (hash, msg) in &self.messages {
802            if store.append(hash.clone(), self.thread.clone(), msg.clone()) {
803                added += 1;
804            } else {
805                deduplicated += 1;
806            }
807        }
808
809        MergeResult {
810            added,
811            deduplicated,
812        }
813    }
814
815    /// Serialize this bundle to a `(meta (causal-closure ...))` S-expression (REQ-311).
816    pub fn to_sexpr(&self) -> SExpr {
817        let mut inner = vec![
818            SExpr::Atom(Atom::Symbol("causal-closure".into())),
819            SExpr::Atom(Atom::Keyword("target".into())),
820            SExpr::Atom(Atom::Str(self.target.0.clone())),
821            SExpr::Atom(Atom::Keyword("thread".into())),
822            SExpr::Atom(Atom::Str(self.thread.0.clone())),
823            SExpr::Atom(Atom::Keyword("messages".into())),
824        ];
825
826        let msg_list: Vec<SExpr> = self
827            .messages
828            .iter()
829            .map(|(_, msg)| SExpr::from(msg))
830            .collect();
831
832        inner.push(SExpr::List(msg_list));
833
834        SExpr::List(vec![
835            SExpr::Atom(Atom::Symbol("meta".into())),
836            SExpr::List(inner),
837        ])
838    }
839
840    /// Returns the number of messages in the bundle.
841    pub fn len(&self) -> usize {
842        self.messages.len()
843    }
844
845    /// Returns true if the bundle contains no messages.
846    pub fn is_empty(&self) -> bool {
847        self.messages.is_empty()
848    }
849
850    /// Returns the content hashes of all messages in the bundle, in topological order.
851    pub fn hashes(&self) -> Vec<&ContentHash> {
852        self.messages.iter().map(|(h, _)| h).collect()
853    }
854}
855
856#[cfg(test)]
857mod tests {
858    use super::*;
859    use alloc::string::ToString;
860    use alloc::vec;
861    use alloc::vec::Vec;
862
863    fn hash(s: &str) -> ContentHash {
864        ContentHash(s.to_string())
865    }
866
867    fn thread(s: &str) -> ThreadId {
868        ThreadId(s.to_string())
869    }
870
871    // --- insert tests ---
872
873    #[test]
874    fn insert_returns_true_for_new_entry() {
875        let mut idx = HashIndex::new();
876        assert!(idx.insert(hash("h1"), thread("t1"), 0));
877    }
878
879    #[test]
880    fn insert_returns_false_for_duplicate() {
881        let mut idx = HashIndex::new();
882        idx.insert(hash("h1"), thread("t1"), 0);
883        assert!(!idx.insert(hash("h1"), thread("t1"), 1));
884    }
885
886    #[test]
887    fn insert_duplicate_does_not_overwrite() {
888        let mut idx = HashIndex::new();
889        idx.insert(hash("h1"), thread("t1"), 0);
890        idx.insert(hash("h1"), thread("t2"), 99);
891        // Original entry preserved
892        assert_eq!(idx.lookup(&hash("h1"), &thread("t1")), Some(0));
893    }
894
895    #[test]
896    fn insert_distinct_hashes_independent() {
897        let mut idx = HashIndex::new();
898        assert!(idx.insert(hash("h1"), thread("t1"), 0));
899        assert!(idx.insert(hash("h2"), thread("t1"), 1));
900        assert_eq!(idx.len(), 2);
901    }
902
903    // --- lookup tests ---
904
905    #[test]
906    fn lookup_returns_index_for_matching_thread() {
907        let mut idx = HashIndex::new();
908        idx.insert(hash("h1"), thread("t1"), 42);
909        assert_eq!(idx.lookup(&hash("h1"), &thread("t1")), Some(42));
910    }
911
912    #[test]
913    fn lookup_returns_none_for_wrong_thread() {
914        let mut idx = HashIndex::new();
915        idx.insert(hash("h1"), thread("t1"), 42);
916        assert_eq!(idx.lookup(&hash("h1"), &thread("t2")), None);
917    }
918
919    #[test]
920    fn lookup_returns_none_for_absent_hash() {
921        let idx = HashIndex::new();
922        assert_eq!(idx.lookup(&hash("h1"), &thread("t1")), None);
923    }
924
925    // --- contains tests ---
926
927    #[test]
928    fn contains_true_for_matching_thread() {
929        let mut idx = HashIndex::new();
930        idx.insert(hash("h1"), thread("t1"), 0);
931        assert!(idx.contains(&hash("h1"), &thread("t1")));
932    }
933
934    #[test]
935    fn contains_false_for_wrong_thread() {
936        let mut idx = HashIndex::new();
937        idx.insert(hash("h1"), thread("t1"), 0);
938        assert!(!idx.contains(&hash("h1"), &thread("t2")));
939    }
940
941    #[test]
942    fn contains_false_for_absent_hash() {
943        let idx = HashIndex::new();
944        assert!(!idx.contains(&hash("nonexistent"), &thread("t1")));
945    }
946
947    // --- thread isolation (ADR-008) ---
948
949    #[test]
950    fn thread_isolation_across_multiple_threads() {
951        let mut idx = HashIndex::new();
952        idx.insert(hash("h1"), thread("t1"), 0);
953        idx.insert(hash("h2"), thread("t2"), 1);
954        idx.insert(hash("h3"), thread("t1"), 2);
955
956        // t1 sees h1 and h3, not h2
957        assert_eq!(idx.lookup(&hash("h1"), &thread("t1")), Some(0));
958        assert_eq!(idx.lookup(&hash("h3"), &thread("t1")), Some(2));
959        assert_eq!(idx.lookup(&hash("h2"), &thread("t1")), None);
960
961        // t2 sees h2, not h1 or h3
962        assert_eq!(idx.lookup(&hash("h2"), &thread("t2")), Some(1));
963        assert_eq!(idx.lookup(&hash("h1"), &thread("t2")), None);
964        assert_eq!(idx.lookup(&hash("h3"), &thread("t2")), None);
965    }
966
967    // --- rebuild tests ---
968
969    #[test]
970    fn rebuild_clears_and_repopulates() {
971        let mut idx = HashIndex::new();
972        idx.insert(hash("old"), thread("t1"), 0);
973
974        idx.rebuild(vec![
975            (hash("new1"), thread("t1"), 0),
976            (hash("new2"), thread("t2"), 1),
977        ]);
978
979        assert_eq!(idx.len(), 2);
980        assert_eq!(idx.lookup(&hash("old"), &thread("t1")), None);
981        assert_eq!(idx.lookup(&hash("new1"), &thread("t1")), Some(0));
982        assert_eq!(idx.lookup(&hash("new2"), &thread("t2")), Some(1));
983    }
984
985    #[test]
986    fn rebuild_skips_duplicates_first_wins() {
987        let mut idx = HashIndex::new();
988        idx.rebuild(vec![
989            (hash("h1"), thread("t1"), 0),
990            (hash("h1"), thread("t2"), 99),
991        ]);
992        assert_eq!(idx.len(), 1);
993        assert_eq!(idx.lookup(&hash("h1"), &thread("t1")), Some(0));
994    }
995
996    #[test]
997    fn rebuild_from_empty_iterator() {
998        let mut idx = HashIndex::new();
999        idx.insert(hash("h1"), thread("t1"), 0);
1000        idx.rebuild(Vec::<(ContentHash, ThreadId, usize)>::new());
1001        assert!(idx.is_empty());
1002    }
1003
1004    // --- len / is_empty ---
1005
1006    #[test]
1007    fn new_index_is_empty() {
1008        let idx = HashIndex::new();
1009        assert!(idx.is_empty());
1010        assert_eq!(idx.len(), 0);
1011    }
1012
1013    #[test]
1014    fn len_tracks_insertions() {
1015        let mut idx = HashIndex::new();
1016        idx.insert(hash("h1"), thread("t1"), 0);
1017        idx.insert(hash("h2"), thread("t1"), 1);
1018        assert_eq!(idx.len(), 2);
1019        assert!(!idx.is_empty());
1020    }
1021
1022    // --- with_capacity ---
1023
1024    #[test]
1025    fn with_capacity_creates_empty_index() {
1026        let idx = HashIndex::with_capacity(100);
1027        assert!(idx.is_empty());
1028    }
1029
1030    // --- Default ---
1031
1032    #[test]
1033    fn default_creates_empty_index() {
1034        let idx = HashIndex::default();
1035        assert!(idx.is_empty());
1036    }
1037
1038    // --- scale test (TEST-309: 10K messages across 10 threads) ---
1039
1040    #[test]
1041    #[allow(clippy::needless_range_loop)]
1042    fn scale_10k_messages_10_threads() {
1043        let mut idx = HashIndex::new();
1044        let threads: Vec<ThreadId> = (0..10).map(|i| thread(&i.to_string())).collect();
1045
1046        // Insert 10K messages across 10 threads (1K per thread)
1047        for t in 0..10 {
1048            for m in 0..1000 {
1049                let h = hash(&alloc::format!("t{}-m{}", t, m));
1050                assert!(idx.insert(h, threads[t].clone(), m));
1051            }
1052        }
1053        assert_eq!(idx.len(), 10_000);
1054
1055        // Verify thread isolation: each message visible only in its own thread
1056        for t in 0..10 {
1057            for m in 0..1000 {
1058                let h = hash(&alloc::format!("t{}-m{}", t, m));
1059                assert_eq!(idx.lookup(&h, &threads[t]), Some(m));
1060                // Cross-thread lookup must fail
1061                let other = &threads[(t + 1) % 10];
1062                assert_eq!(idx.lookup(&h, other), None);
1063            }
1064        }
1065
1066        // Rebuild and verify
1067        let mut entries = Vec::with_capacity(10_000);
1068        for t in 0..10 {
1069            for m in 0..1000 {
1070                entries.push((
1071                    hash(&alloc::format!("t{}-m{}", t, m)),
1072                    threads[t].clone(),
1073                    m,
1074                ));
1075            }
1076        }
1077        idx.rebuild(entries);
1078        assert_eq!(idx.len(), 10_000);
1079
1080        // Spot check after rebuild
1081        assert_eq!(idx.lookup(&hash("t5-m500"), &threads[5]), Some(500));
1082        assert_eq!(idx.lookup(&hash("t5-m500"), &threads[0]), None);
1083    }
1084
1085    // =========================================================================
1086    // ThreadedMessageStore tests
1087    // =========================================================================
1088
1089    use crate::message::{CausedBy, Performative};
1090    use crate::sexpr::{Atom, SExpr};
1091
1092    /// Helper: create a simple message with optional caused_by and thread.
1093    fn simple_msg(perf: &str, content: &str, caused_by: Option<CausedBy>) -> Message {
1094        Message::Simple {
1095            performative: Performative::Core(
1096                crate::message::CorePerformative::parse(perf)
1097                    .unwrap_or(crate::message::CorePerformative::Tell),
1098            ),
1099            recipient: None,
1100            content: SExpr::Atom(Atom::Str(content.to_string())),
1101            params: Vec::new(),
1102            thread: None,
1103            sender: None,
1104            caused_by,
1105        }
1106    }
1107
1108    // --- append tests (REQ-310 deduplication) ---
1109
1110    #[test]
1111    fn append_returns_true_for_new_message() {
1112        let mut store = ThreadedMessageStore::new();
1113        let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1114        assert!(store.append(hash("h1"), thread("t1"), msg));
1115    }
1116
1117    #[test]
1118    fn append_returns_false_for_duplicate_hash() {
1119        let mut store = ThreadedMessageStore::new();
1120        let msg1 = simple_msg("tell", "hello", Some(CausedBy::Begin));
1121        let msg2 = simple_msg("tell", "hello again", Some(CausedBy::Begin));
1122        store.append(hash("h1"), thread("t1"), msg1);
1123        assert!(!store.append(hash("h1"), thread("t1"), msg2));
1124    }
1125
1126    #[test]
1127    fn append_duplicate_cross_thread_rejected() {
1128        let mut store = ThreadedMessageStore::new();
1129        let msg1 = simple_msg("tell", "hello", Some(CausedBy::Begin));
1130        let msg2 = simple_msg("tell", "hello", Some(CausedBy::Begin));
1131        store.append(hash("h1"), thread("t1"), msg1);
1132        // Same hash in different thread is still a duplicate (global dedup)
1133        assert!(!store.append(hash("h1"), thread("t2"), msg2));
1134    }
1135
1136    // --- lookup tests ---
1137
1138    #[test]
1139    fn lookup_returns_message_across_threads() {
1140        let mut store = ThreadedMessageStore::new();
1141        let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1142        store.append(hash("h1"), thread("t1"), msg);
1143        let found = store.lookup(&hash("h1"));
1144        assert!(found.is_some());
1145        assert_eq!(
1146            found.unwrap().performative(),
1147            Some(&Performative::Core(crate::message::CorePerformative::Tell))
1148        );
1149    }
1150
1151    #[test]
1152    fn lookup_returns_none_for_absent() {
1153        let store = ThreadedMessageStore::new();
1154        assert!(store.lookup(&hash("nonexistent")).is_none());
1155    }
1156
1157    // --- lookup_in_thread tests ---
1158
1159    #[test]
1160    fn lookup_in_thread_returns_message_for_correct_thread() {
1161        let mut store = ThreadedMessageStore::new();
1162        let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1163        store.append(hash("h1"), thread("t1"), msg);
1164        assert!(store.lookup_in_thread(&hash("h1"), &thread("t1")).is_some());
1165    }
1166
1167    #[test]
1168    fn lookup_in_thread_returns_none_for_wrong_thread() {
1169        let mut store = ThreadedMessageStore::new();
1170        let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1171        store.append(hash("h1"), thread("t1"), msg);
1172        assert!(store.lookup_in_thread(&hash("h1"), &thread("t2")).is_none());
1173    }
1174
1175    #[test]
1176    fn lookup_in_thread_returns_none_for_absent() {
1177        let store = ThreadedMessageStore::new();
1178        assert!(store.lookup_in_thread(&hash("h1"), &thread("t1")).is_none());
1179    }
1180
1181    // --- contains tests ---
1182
1183    #[test]
1184    fn contains_true_for_existing_in_thread() {
1185        let mut store = ThreadedMessageStore::new();
1186        let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1187        store.append(hash("h1"), thread("t1"), msg);
1188        assert!(store.contains(&hash("h1"), &thread("t1")));
1189    }
1190
1191    #[test]
1192    fn store_contains_false_for_wrong_thread() {
1193        let mut store = ThreadedMessageStore::new();
1194        let msg = simple_msg("tell", "hello", Some(CausedBy::Begin));
1195        store.append(hash("h1"), thread("t1"), msg);
1196        assert!(!store.contains(&hash("h1"), &thread("t2")));
1197    }
1198
1199    #[test]
1200    fn contains_false_for_absent() {
1201        let store = ThreadedMessageStore::new();
1202        assert!(!store.contains(&hash("h1"), &thread("t1")));
1203    }
1204
1205    // --- frontier tests (leaf messages) ---
1206
1207    #[test]
1208    fn frontier_empty_thread_returns_empty() {
1209        let store = ThreadedMessageStore::new();
1210        assert!(store.frontier(&thread("t1")).is_empty());
1211    }
1212
1213    #[test]
1214    fn frontier_single_begin_message_is_frontier() {
1215        let mut store = ThreadedMessageStore::new();
1216        store.append(
1217            hash("h1"),
1218            thread("t1"),
1219            simple_msg("tell", "start", Some(CausedBy::Begin)),
1220        );
1221        let f = store.frontier(&thread("t1"));
1222        assert_eq!(f.len(), 1);
1223        assert_eq!(f[0], &hash("h1"));
1224    }
1225
1226    #[test]
1227    fn frontier_chain_only_leaf_is_frontier() {
1228        let mut store = ThreadedMessageStore::new();
1229        store.append(
1230            hash("h1"),
1231            thread("t1"),
1232            simple_msg("tell", "start", Some(CausedBy::Begin)),
1233        );
1234        store.append(
1235            hash("h2"),
1236            thread("t1"),
1237            simple_msg("reply", "ack", Some(CausedBy::Single("h1".into()))),
1238        );
1239        let f = store.frontier(&thread("t1"));
1240        assert_eq!(f.len(), 1);
1241        assert_eq!(f[0], &hash("h2"));
1242    }
1243
1244    #[test]
1245    fn frontier_branching_two_leaves() {
1246        let mut store = ThreadedMessageStore::new();
1247        store.append(
1248            hash("root"),
1249            thread("t1"),
1250            simple_msg("tell", "start", Some(CausedBy::Begin)),
1251        );
1252        store.append(
1253            hash("b1"),
1254            thread("t1"),
1255            simple_msg("reply", "branch1", Some(CausedBy::Single("root".into()))),
1256        );
1257        store.append(
1258            hash("b2"),
1259            thread("t1"),
1260            simple_msg("reply", "branch2", Some(CausedBy::Single("root".into()))),
1261        );
1262        let mut f: Vec<_> = store.frontier(&thread("t1")).into_iter().cloned().collect();
1263        f.sort();
1264        assert_eq!(f, vec![hash("b1"), hash("b2")]);
1265    }
1266
1267    #[test]
1268    fn frontier_fan_in_merge_removes_predecessors() {
1269        let mut store = ThreadedMessageStore::new();
1270        store.append(
1271            hash("root"),
1272            thread("t1"),
1273            simple_msg("tell", "start", Some(CausedBy::Begin)),
1274        );
1275        store.append(
1276            hash("b1"),
1277            thread("t1"),
1278            simple_msg("reply", "a", Some(CausedBy::Single("root".into()))),
1279        );
1280        store.append(
1281            hash("b2"),
1282            thread("t1"),
1283            simple_msg("reply", "b", Some(CausedBy::Single("root".into()))),
1284        );
1285        // Merge message references both branches
1286        store.append(
1287            hash("merge"),
1288            thread("t1"),
1289            simple_msg(
1290                "ok",
1291                "done",
1292                Some(CausedBy::Multiple(vec!["b1".into(), "b2".into()])),
1293            ),
1294        );
1295        let f = store.frontier(&thread("t1"));
1296        assert_eq!(f.len(), 1);
1297        assert_eq!(f[0], &hash("merge"));
1298    }
1299
1300    #[test]
1301    fn frontier_separate_threads_independent() {
1302        let mut store = ThreadedMessageStore::new();
1303        store.append(
1304            hash("h1"),
1305            thread("t1"),
1306            simple_msg("tell", "a", Some(CausedBy::Begin)),
1307        );
1308        store.append(
1309            hash("h2"),
1310            thread("t2"),
1311            simple_msg("tell", "b", Some(CausedBy::Begin)),
1312        );
1313        assert_eq!(store.frontier(&thread("t1")).len(), 1);
1314        assert_eq!(store.frontier(&thread("t2")).len(), 1);
1315    }
1316
1317    // --- causal_closure tests (principal ideal) ---
1318
1319    #[test]
1320    fn causal_closure_begin_message_is_singleton() {
1321        let mut store = ThreadedMessageStore::new();
1322        store.append(
1323            hash("h1"),
1324            thread("t1"),
1325            simple_msg("tell", "start", Some(CausedBy::Begin)),
1326        );
1327        let cc = store.causal_closure(&hash("h1"), &thread("t1"));
1328        assert_eq!(cc.len(), 1);
1329        assert_eq!(cc[0], hash("h1"));
1330    }
1331
1332    #[test]
1333    fn causal_closure_chain_returns_all_ancestors() {
1334        let mut store = ThreadedMessageStore::new();
1335        store.append(
1336            hash("h1"),
1337            thread("t1"),
1338            simple_msg("tell", "start", Some(CausedBy::Begin)),
1339        );
1340        store.append(
1341            hash("h2"),
1342            thread("t1"),
1343            simple_msg("reply", "mid", Some(CausedBy::Single("h1".into()))),
1344        );
1345        store.append(
1346            hash("h3"),
1347            thread("t1"),
1348            simple_msg("ok", "end", Some(CausedBy::Single("h2".into()))),
1349        );
1350        let mut cc = store.causal_closure(&hash("h3"), &thread("t1"));
1351        cc.sort();
1352        assert_eq!(cc, vec![hash("h1"), hash("h2"), hash("h3")]);
1353    }
1354
1355    #[test]
1356    fn causal_closure_fan_in_includes_all_branches() {
1357        let mut store = ThreadedMessageStore::new();
1358        store.append(
1359            hash("root"),
1360            thread("t1"),
1361            simple_msg("tell", "start", Some(CausedBy::Begin)),
1362        );
1363        store.append(
1364            hash("b1"),
1365            thread("t1"),
1366            simple_msg("reply", "a", Some(CausedBy::Single("root".into()))),
1367        );
1368        store.append(
1369            hash("b2"),
1370            thread("t1"),
1371            simple_msg("reply", "b", Some(CausedBy::Single("root".into()))),
1372        );
1373        store.append(
1374            hash("merge"),
1375            thread("t1"),
1376            simple_msg(
1377                "ok",
1378                "done",
1379                Some(CausedBy::Multiple(vec!["b1".into(), "b2".into()])),
1380            ),
1381        );
1382        let mut cc = store.causal_closure(&hash("merge"), &thread("t1"));
1383        cc.sort();
1384        assert_eq!(
1385            cc,
1386            vec![hash("b1"), hash("b2"), hash("merge"), hash("root")]
1387        );
1388    }
1389
1390    #[test]
1391    fn causal_closure_absent_message_returns_empty() {
1392        let store = ThreadedMessageStore::new();
1393        let cc = store.causal_closure(&hash("nonexistent"), &thread("t1"));
1394        assert!(cc.is_empty());
1395    }
1396
1397    #[test]
1398    fn causal_closure_wrong_thread_returns_empty() {
1399        let mut store = ThreadedMessageStore::new();
1400        store.append(
1401            hash("h1"),
1402            thread("t1"),
1403            simple_msg("tell", "start", Some(CausedBy::Begin)),
1404        );
1405        let cc = store.causal_closure(&hash("h1"), &thread("t2"));
1406        assert!(cc.is_empty());
1407    }
1408
1409    #[test]
1410    fn causal_closure_diamond_no_duplicates() {
1411        // Diamond: root -> a, root -> b, a + b -> merge
1412        let mut store = ThreadedMessageStore::new();
1413        store.append(
1414            hash("root"),
1415            thread("t1"),
1416            simple_msg("tell", "start", Some(CausedBy::Begin)),
1417        );
1418        store.append(
1419            hash("a"),
1420            thread("t1"),
1421            simple_msg("reply", "a", Some(CausedBy::Single("root".into()))),
1422        );
1423        store.append(
1424            hash("b"),
1425            thread("t1"),
1426            simple_msg("reply", "b", Some(CausedBy::Single("root".into()))),
1427        );
1428        store.append(
1429            hash("merge"),
1430            thread("t1"),
1431            simple_msg(
1432                "ok",
1433                "done",
1434                Some(CausedBy::Multiple(vec!["a".into(), "b".into()])),
1435            ),
1436        );
1437        let cc = store.causal_closure(&hash("merge"), &thread("t1"));
1438        // No duplicates — root appears once even though reachable via both a and b
1439        assert_eq!(cc.len(), 4);
1440        let mut sorted = cc.clone();
1441        sorted.sort();
1442        sorted.dedup();
1443        assert_eq!(sorted.len(), 4);
1444    }
1445
1446    // --- G-Set monotonicity (REQ-300) ---
1447
1448    #[test]
1449    fn append_is_monotonic_store_only_grows() {
1450        let mut store = ThreadedMessageStore::new();
1451        store.append(
1452            hash("h1"),
1453            thread("t1"),
1454            simple_msg("tell", "a", Some(CausedBy::Begin)),
1455        );
1456        assert!(store.contains(&hash("h1"), &thread("t1")));
1457        store.append(
1458            hash("h2"),
1459            thread("t1"),
1460            simple_msg("reply", "b", Some(CausedBy::Single("h1".into()))),
1461        );
1462        // h1 still present after adding h2
1463        assert!(store.contains(&hash("h1"), &thread("t1")));
1464        assert!(store.contains(&hash("h2"), &thread("t1")));
1465    }
1466
1467    // --- message without caused_by ---
1468
1469    #[test]
1470    fn message_without_caused_by_is_frontier() {
1471        let mut store = ThreadedMessageStore::new();
1472        let msg = Message::Simple {
1473            performative: Performative::Core(crate::message::CorePerformative::Tell),
1474            recipient: None,
1475            content: SExpr::Atom(Atom::Str("no causality".to_string())),
1476            params: Vec::new(),
1477            thread: None,
1478            sender: None,
1479            caused_by: None,
1480        };
1481        store.append(hash("h1"), thread("t1"), msg);
1482        let f = store.frontier(&thread("t1"));
1483        assert_eq!(f.len(), 1);
1484        assert_eq!(f[0], &hash("h1"));
1485    }
1486
1487    // --- scale test ---
1488
1489    #[test]
1490    fn scale_1000_message_chain() {
1491        let mut store = ThreadedMessageStore::new();
1492        let t = thread("t1");
1493
1494        // Build a 1000-message chain
1495        store.append(
1496            hash("m0"),
1497            t.clone(),
1498            simple_msg("tell", "start", Some(CausedBy::Begin)),
1499        );
1500        for i in 1..1000 {
1501            let h = hash(&alloc::format!("m{}", i));
1502            let prev = alloc::format!("m{}", i - 1);
1503            store.append(
1504                h,
1505                t.clone(),
1506                simple_msg("reply", "msg", Some(CausedBy::Single(prev))),
1507            );
1508        }
1509
1510        // Frontier should be only the last message
1511        let f = store.frontier(&t);
1512        assert_eq!(f.len(), 1);
1513        assert_eq!(f[0], &hash("m999"));
1514
1515        // Causal closure of last message should be all 1000 messages
1516        let cc = store.causal_closure(&hash("m999"), &t);
1517        assert_eq!(cc.len(), 1000);
1518
1519        // Causal closure of first message should be just itself
1520        let cc0 = store.causal_closure(&hash("m0"), &t);
1521        assert_eq!(cc0.len(), 1);
1522    }
1523
1524    // =========================================================================
1525    // CausalClosureBundle tests (TEST-311, TEST-212)
1526    // =========================================================================
1527
1528    // --- extract tests ---
1529
1530    #[test]
1531    fn bundle_extract_single_begin_message() {
1532        let mut store = ThreadedMessageStore::new();
1533        let t = thread("t1");
1534        store.append(
1535            hash("h1"),
1536            t.clone(),
1537            simple_msg("tell", "start", Some(CausedBy::Begin)),
1538        );
1539
1540        let bundle = CausalClosureBundle::extract(&hash("h1"), &t, &store).unwrap();
1541        assert_eq!(bundle.target, hash("h1"));
1542        assert_eq!(bundle.thread, t);
1543        assert_eq!(bundle.len(), 1);
1544        assert_eq!(bundle.messages[0].0, hash("h1"));
1545    }
1546
1547    #[test]
1548    fn bundle_extract_chain_topological_order() {
1549        let mut store = ThreadedMessageStore::new();
1550        let t = thread("t1");
1551        store.append(
1552            hash("h1"),
1553            t.clone(),
1554            simple_msg("tell", "start", Some(CausedBy::Begin)),
1555        );
1556        store.append(
1557            hash("h2"),
1558            t.clone(),
1559            simple_msg("reply", "mid", Some(CausedBy::Single("h1".into()))),
1560        );
1561        store.append(
1562            hash("h3"),
1563            t.clone(),
1564            simple_msg("ok", "end", Some(CausedBy::Single("h2".into()))),
1565        );
1566
1567        let bundle = CausalClosureBundle::extract(&hash("h3"), &t, &store).unwrap();
1568        assert_eq!(bundle.len(), 3);
1569
1570        // Topological order: predecessors before successors
1571        let hashes: Vec<&ContentHash> = bundle.hashes();
1572        let pos_h1 = hashes.iter().position(|h| **h == hash("h1")).unwrap();
1573        let pos_h2 = hashes.iter().position(|h| **h == hash("h2")).unwrap();
1574        let pos_h3 = hashes.iter().position(|h| **h == hash("h3")).unwrap();
1575        assert!(pos_h1 < pos_h2);
1576        assert!(pos_h2 < pos_h3);
1577    }
1578
1579    #[test]
1580    fn bundle_extract_diamond_dag() {
1581        let mut store = ThreadedMessageStore::new();
1582        let t = thread("t1");
1583        store.append(
1584            hash("root"),
1585            t.clone(),
1586            simple_msg("tell", "start", Some(CausedBy::Begin)),
1587        );
1588        store.append(
1589            hash("a"),
1590            t.clone(),
1591            simple_msg("reply", "a", Some(CausedBy::Single("root".into()))),
1592        );
1593        store.append(
1594            hash("b"),
1595            t.clone(),
1596            simple_msg("reply", "b", Some(CausedBy::Single("root".into()))),
1597        );
1598        store.append(
1599            hash("merge"),
1600            t.clone(),
1601            simple_msg(
1602                "ok",
1603                "done",
1604                Some(CausedBy::Multiple(vec!["a".into(), "b".into()])),
1605            ),
1606        );
1607
1608        let bundle = CausalClosureBundle::extract(&hash("merge"), &t, &store).unwrap();
1609        assert_eq!(bundle.len(), 4);
1610
1611        // root must come before a, b; a and b must come before merge
1612        let hashes: Vec<&ContentHash> = bundle.hashes();
1613        let pos = |h: &str| hashes.iter().position(|x| **x == hash(h)).unwrap();
1614        assert!(pos("root") < pos("a"));
1615        assert!(pos("root") < pos("b"));
1616        assert!(pos("a") < pos("merge"));
1617        assert!(pos("b") < pos("merge"));
1618    }
1619
1620    #[test]
1621    fn bundle_extract_partial_closure() {
1622        // Extract closure of a mid-chain message — should NOT include later messages
1623        let mut store = ThreadedMessageStore::new();
1624        let t = thread("t1");
1625        store.append(
1626            hash("h1"),
1627            t.clone(),
1628            simple_msg("tell", "start", Some(CausedBy::Begin)),
1629        );
1630        store.append(
1631            hash("h2"),
1632            t.clone(),
1633            simple_msg("reply", "mid", Some(CausedBy::Single("h1".into()))),
1634        );
1635        store.append(
1636            hash("h3"),
1637            t.clone(),
1638            simple_msg("ok", "end", Some(CausedBy::Single("h2".into()))),
1639        );
1640
1641        let bundle = CausalClosureBundle::extract(&hash("h2"), &t, &store).unwrap();
1642        assert_eq!(bundle.len(), 2);
1643        let mut sorted_hashes: Vec<ContentHash> = bundle.hashes().into_iter().cloned().collect();
1644        sorted_hashes.sort();
1645        assert_eq!(sorted_hashes, vec![hash("h1"), hash("h2")]);
1646    }
1647
1648    #[test]
1649    fn bundle_extract_target_not_found() {
1650        let store = ThreadedMessageStore::new();
1651        let result = CausalClosureBundle::extract(&hash("nonexistent"), &thread("t1"), &store);
1652        assert_eq!(result, Err(ClosureError::TargetNotFound));
1653    }
1654
1655    #[test]
1656    fn bundle_extract_wrong_thread() {
1657        let mut store = ThreadedMessageStore::new();
1658        store.append(
1659            hash("h1"),
1660            thread("t1"),
1661            simple_msg("tell", "start", Some(CausedBy::Begin)),
1662        );
1663        let result = CausalClosureBundle::extract(&hash("h1"), &thread("t2"), &store);
1664        assert_eq!(result, Err(ClosureError::TargetNotFound));
1665    }
1666
1667    // --- verify_completeness tests ---
1668
1669    #[test]
1670    fn bundle_verify_completeness_valid() {
1671        let mut store = ThreadedMessageStore::new();
1672        let t = thread("t1");
1673        store.append(
1674            hash("h1"),
1675            t.clone(),
1676            simple_msg("tell", "start", Some(CausedBy::Begin)),
1677        );
1678        store.append(
1679            hash("h2"),
1680            t.clone(),
1681            simple_msg("reply", "done", Some(CausedBy::Single("h1".into()))),
1682        );
1683
1684        let bundle = CausalClosureBundle::extract(&hash("h2"), &t, &store).unwrap();
1685        assert!(bundle.verify_completeness().is_ok());
1686    }
1687
1688    #[test]
1689    fn bundle_verify_completeness_dangling_reference() {
1690        let t = thread("t1");
1691        // Manually construct a bundle with a dangling reference
1692        let bundle = CausalClosureBundle {
1693            target: hash("h2"),
1694            thread: t,
1695            messages: vec![(
1696                hash("h2"),
1697                simple_msg("reply", "done", Some(CausedBy::Single("missing".into()))),
1698            )],
1699        };
1700
1701        let result = bundle.verify_completeness();
1702        assert!(result.is_err());
1703        let errors = result.unwrap_err();
1704        assert_eq!(errors.len(), 1);
1705        assert!(
1706            matches!(&errors[0], BundleVerificationError::DanglingReference { caused_by } if caused_by == "missing")
1707        );
1708    }
1709
1710    // --- verify_hashes tests ---
1711
1712    #[test]
1713    fn bundle_verify_hashes_matching() {
1714        let mut store = ThreadedMessageStore::new();
1715        let t = thread("t1");
1716        store.append(
1717            hash("h1"),
1718            t.clone(),
1719            simple_msg("tell", "start", Some(CausedBy::Begin)),
1720        );
1721
1722        let bundle = CausalClosureBundle::extract(&hash("h1"), &t, &store).unwrap();
1723        // Identity hasher — hashes match
1724        let result = bundle.verify_hashes(|_| hash("h1"));
1725        assert!(result.is_ok());
1726    }
1727
1728    #[test]
1729    fn bundle_verify_hashes_mismatch() {
1730        let mut store = ThreadedMessageStore::new();
1731        let t = thread("t1");
1732        store.append(
1733            hash("h1"),
1734            t.clone(),
1735            simple_msg("tell", "start", Some(CausedBy::Begin)),
1736        );
1737
1738        let bundle = CausalClosureBundle::extract(&hash("h1"), &t, &store).unwrap();
1739        // Hasher that returns wrong hash
1740        let result = bundle.verify_hashes(|_| hash("wrong"));
1741        assert!(result.is_err());
1742        let errors = result.unwrap_err();
1743        assert!(matches!(
1744            &errors[0],
1745            BundleVerificationError::HashMismatch { expected, computed, .. }
1746            if expected.0 == "h1" && computed.0 == "wrong"
1747        ));
1748    }
1749
1750    // --- verify_causal tests ---
1751
1752    #[test]
1753    fn bundle_verify_causal_no_protocol_steps() {
1754        use crate::protocol::CausalProtocol;
1755        use alloc::collections::BTreeMap;
1756
1757        let mut store = ThreadedMessageStore::new();
1758        let t = thread("t1");
1759        store.append(
1760            hash("h1"),
1761            t.clone(),
1762            simple_msg("tell", "start", Some(CausedBy::Begin)),
1763        );
1764        store.append(
1765            hash("h2"),
1766            t.clone(),
1767            simple_msg("reply", "done", Some(CausedBy::Single("h1".into()))),
1768        );
1769
1770        let bundle = CausalClosureBundle::extract(&hash("h2"), &t, &store).unwrap();
1771        let empty_protocol = CausalProtocol {
1772            steps: BTreeMap::new(),
1773        };
1774        assert!(bundle.verify_causal(&empty_protocol).is_ok());
1775    }
1776
1777    // --- merge tests ---
1778
1779    #[test]
1780    fn bundle_merge_into_empty_store() {
1781        let mut source_store = ThreadedMessageStore::new();
1782        let t = thread("t1");
1783        source_store.append(
1784            hash("h1"),
1785            t.clone(),
1786            simple_msg("tell", "start", Some(CausedBy::Begin)),
1787        );
1788        source_store.append(
1789            hash("h2"),
1790            t.clone(),
1791            simple_msg("reply", "done", Some(CausedBy::Single("h1".into()))),
1792        );
1793
1794        let bundle = CausalClosureBundle::extract(&hash("h2"), &t, &source_store).unwrap();
1795
1796        let mut target_store = ThreadedMessageStore::new();
1797        let result = bundle.merge(&mut target_store);
1798        assert_eq!(result.added, 2);
1799        assert_eq!(result.deduplicated, 0);
1800
1801        // All messages now in target store
1802        assert!(target_store.contains(&hash("h1"), &t));
1803        assert!(target_store.contains(&hash("h2"), &t));
1804    }
1805
1806    #[test]
1807    fn bundle_merge_deduplication() {
1808        let mut store = ThreadedMessageStore::new();
1809        let t = thread("t1");
1810        store.append(
1811            hash("h1"),
1812            t.clone(),
1813            simple_msg("tell", "start", Some(CausedBy::Begin)),
1814        );
1815        store.append(
1816            hash("h2"),
1817            t.clone(),
1818            simple_msg("reply", "done", Some(CausedBy::Single("h1".into()))),
1819        );
1820
1821        let bundle = CausalClosureBundle::extract(&hash("h2"), &t, &store).unwrap();
1822
1823        // Merge into a store that already has h1
1824        let mut target_store = ThreadedMessageStore::new();
1825        target_store.append(
1826            hash("h1"),
1827            t.clone(),
1828            simple_msg("tell", "start", Some(CausedBy::Begin)),
1829        );
1830
1831        let result = bundle.merge(&mut target_store);
1832        assert_eq!(result.added, 1); // only h2 is new
1833        assert_eq!(result.deduplicated, 1); // h1 was deduplicated
1834    }
1835
1836    #[test]
1837    fn bundle_merge_all_duplicates() {
1838        let mut store = ThreadedMessageStore::new();
1839        let t = thread("t1");
1840        store.append(
1841            hash("h1"),
1842            t.clone(),
1843            simple_msg("tell", "start", Some(CausedBy::Begin)),
1844        );
1845
1846        let bundle = CausalClosureBundle::extract(&hash("h1"), &t, &store).unwrap();
1847
1848        // Merge into same store
1849        let result = bundle.merge(&mut store);
1850        assert_eq!(result.added, 0);
1851        assert_eq!(result.deduplicated, 1);
1852    }
1853
1854    // --- to_sexpr tests ---
1855
1856    #[test]
1857    fn bundle_to_sexpr_structure() {
1858        let mut store = ThreadedMessageStore::new();
1859        let t = thread("t1");
1860        store.append(
1861            hash("h1"),
1862            t.clone(),
1863            simple_msg("tell", "start", Some(CausedBy::Begin)),
1864        );
1865
1866        let bundle = CausalClosureBundle::extract(&hash("h1"), &t, &store).unwrap();
1867        let sexpr = bundle.to_sexpr();
1868
1869        // Should be (meta (causal-closure :target ... :thread ... :messages ...))
1870        if let SExpr::List(outer) = &sexpr {
1871            assert_eq!(outer.len(), 2);
1872            assert_eq!(outer[0], SExpr::Atom(Atom::Symbol("meta".into())));
1873            if let SExpr::List(inner) = &outer[1] {
1874                assert_eq!(inner[0], SExpr::Atom(Atom::Symbol("causal-closure".into())));
1875                assert_eq!(inner[1], SExpr::Atom(Atom::Keyword("target".into())));
1876                assert_eq!(inner[2], SExpr::Atom(Atom::Str("h1".into())));
1877                assert_eq!(inner[3], SExpr::Atom(Atom::Keyword("thread".into())));
1878                assert_eq!(inner[4], SExpr::Atom(Atom::Str("t1".into())));
1879                assert_eq!(inner[5], SExpr::Atom(Atom::Keyword("messages".into())));
1880                if let SExpr::List(msgs) = &inner[6] {
1881                    assert_eq!(msgs.len(), 1); // one message
1882                } else {
1883                    panic!("expected messages list");
1884                }
1885            } else {
1886                panic!("expected inner list");
1887            }
1888        } else {
1889            panic!("expected outer list");
1890        }
1891    }
1892
1893    // --- round-trip tests (extract -> merge -> compare) ---
1894
1895    #[test]
1896    fn bundle_round_trip_extract_merge_matches() {
1897        let mut store = ThreadedMessageStore::new();
1898        let t = thread("t1");
1899        store.append(
1900            hash("h1"),
1901            t.clone(),
1902            simple_msg("tell", "start", Some(CausedBy::Begin)),
1903        );
1904        store.append(
1905            hash("h2"),
1906            t.clone(),
1907            simple_msg("reply", "mid", Some(CausedBy::Single("h1".into()))),
1908        );
1909        store.append(
1910            hash("h3"),
1911            t.clone(),
1912            simple_msg("ok", "end", Some(CausedBy::Single("h2".into()))),
1913        );
1914
1915        let bundle = CausalClosureBundle::extract(&hash("h3"), &t, &store).unwrap();
1916        assert!(bundle.verify_completeness().is_ok());
1917
1918        // Merge into empty store
1919        let mut target = ThreadedMessageStore::new();
1920        let result = bundle.merge(&mut target);
1921        assert_eq!(result.added, 3);
1922
1923        // Target store should have same causal closure
1924        let cc = target.causal_closure(&hash("h3"), &t);
1925        assert_eq!(cc.len(), 3);
1926    }
1927
1928    #[test]
1929    fn bundle_round_trip_diamond() {
1930        let mut store = ThreadedMessageStore::new();
1931        let t = thread("t1");
1932        store.append(
1933            hash("root"),
1934            t.clone(),
1935            simple_msg("tell", "start", Some(CausedBy::Begin)),
1936        );
1937        store.append(
1938            hash("a"),
1939            t.clone(),
1940            simple_msg("reply", "a", Some(CausedBy::Single("root".into()))),
1941        );
1942        store.append(
1943            hash("b"),
1944            t.clone(),
1945            simple_msg("reply", "b", Some(CausedBy::Single("root".into()))),
1946        );
1947        store.append(
1948            hash("merge"),
1949            t.clone(),
1950            simple_msg(
1951                "ok",
1952                "done",
1953                Some(CausedBy::Multiple(vec!["a".into(), "b".into()])),
1954            ),
1955        );
1956
1957        let bundle = CausalClosureBundle::extract(&hash("merge"), &t, &store).unwrap();
1958        assert!(bundle.verify_completeness().is_ok());
1959
1960        let mut target = ThreadedMessageStore::new();
1961        let result = bundle.merge(&mut target);
1962        assert_eq!(result.added, 4);
1963
1964        // Verify causal closure matches
1965        let mut cc = target.causal_closure(&hash("merge"), &t);
1966        cc.sort();
1967        assert_eq!(cc, vec![hash("a"), hash("b"), hash("merge"), hash("root")]);
1968
1969        // Verify frontier
1970        let f = target.frontier(&t);
1971        assert_eq!(f.len(), 1);
1972        assert_eq!(f[0], &hash("merge"));
1973    }
1974
1975    // --- Tier 2: partial causal closure verification (REQ-212) ---
1976
1977    #[test]
1978    fn tier2_partial_closure_sufficient_for_target() {
1979        // Build a larger thread, extract closure for a mid-point message,
1980        // verify the closure is self-contained
1981        let mut store = ThreadedMessageStore::new();
1982        let t = thread("t1");
1983        store.append(
1984            hash("h1"),
1985            t.clone(),
1986            simple_msg("tell", "start", Some(CausedBy::Begin)),
1987        );
1988        store.append(
1989            hash("h2"),
1990            t.clone(),
1991            simple_msg("reply", "a", Some(CausedBy::Single("h1".into()))),
1992        );
1993        store.append(
1994            hash("h3"),
1995            t.clone(),
1996            simple_msg("reply", "b", Some(CausedBy::Single("h2".into()))),
1997        );
1998        // h4 is on a different branch from h1
1999        store.append(
2000            hash("h4"),
2001            t.clone(),
2002            simple_msg("reply", "c", Some(CausedBy::Single("h1".into()))),
2003        );
2004
2005        // Extract closure of h3 — should include h1, h2, h3 but NOT h4
2006        let bundle = CausalClosureBundle::extract(&hash("h3"), &t, &store).unwrap();
2007        assert_eq!(bundle.len(), 3);
2008        let hashes: Vec<ContentHash> = bundle.hashes().into_iter().cloned().collect();
2009        assert!(hashes.contains(&hash("h1")));
2010        assert!(hashes.contains(&hash("h2")));
2011        assert!(hashes.contains(&hash("h3")));
2012        assert!(!hashes.contains(&hash("h4"))); // unrelated branch excluded
2013        assert!(bundle.verify_completeness().is_ok());
2014    }
2015
2016    // --- Tier 3: full audit verification (REQ-212) ---
2017
2018    #[test]
2019    fn tier3_full_audit_detects_hash_mismatch() {
2020        let t = thread("t1");
2021        // Construct a bundle where one message has a wrong hash
2022        let bundle = CausalClosureBundle {
2023            target: hash("h2"),
2024            thread: t,
2025            messages: vec![
2026                (
2027                    hash("h1"),
2028                    simple_msg("tell", "start", Some(CausedBy::Begin)),
2029                ),
2030                (
2031                    hash("h2"),
2032                    simple_msg("reply", "done", Some(CausedBy::Single("h1".into()))),
2033                ),
2034            ],
2035        };
2036
2037        // Hasher that always returns "computed-hash" — will mismatch both
2038        let result = bundle.verify_hashes(|_| hash("computed-hash"));
2039        assert!(result.is_err());
2040        assert_eq!(result.unwrap_err().len(), 2);
2041    }
2042
2043    #[test]
2044    fn tier3_full_audit_detects_dangling_refs() {
2045        let t = thread("t1");
2046        let bundle = CausalClosureBundle {
2047            target: hash("h2"),
2048            thread: t,
2049            messages: vec![(
2050                hash("h2"),
2051                simple_msg("reply", "done", Some(CausedBy::Single("missing".into()))),
2052            )],
2053        };
2054
2055        let result = bundle.verify_completeness();
2056        assert!(result.is_err());
2057    }
2058
2059    #[test]
2060    fn tier3_full_audit_all_checks_pass() {
2061        let mut store = ThreadedMessageStore::new();
2062        let t = thread("t1");
2063        store.append(
2064            hash("h1"),
2065            t.clone(),
2066            simple_msg("tell", "start", Some(CausedBy::Begin)),
2067        );
2068        store.append(
2069            hash("h2"),
2070            t.clone(),
2071            simple_msg("reply", "mid", Some(CausedBy::Single("h1".into()))),
2072        );
2073        store.append(
2074            hash("h3"),
2075            t.clone(),
2076            simple_msg("ok", "end", Some(CausedBy::Single("h2".into()))),
2077        );
2078
2079        let bundle = CausalClosureBundle::extract(&hash("h3"), &t, &store).unwrap();
2080
2081        // Identity hasher that maps known hashes
2082        let result = bundle.verify_full(
2083            |msg| {
2084                // Simple identity-like hasher for testing
2085                match msg.caused_by() {
2086                    Some(CausedBy::Begin) => hash("h1"),
2087                    Some(CausedBy::Single(p)) if p == "h1" => hash("h2"),
2088                    Some(CausedBy::Single(p)) if p == "h2" => hash("h3"),
2089                    _ => hash("unknown"),
2090                }
2091            },
2092            &CausalProtocol {
2093                steps: alloc::collections::BTreeMap::new(),
2094            },
2095        );
2096        assert!(result.is_ok());
2097    }
2098
2099    // --- len / is_empty ---
2100
2101    #[test]
2102    fn bundle_empty_has_correct_len() {
2103        let bundle = CausalClosureBundle {
2104            target: hash("h1"),
2105            thread: thread("t1"),
2106            messages: vec![],
2107        };
2108        assert!(bundle.is_empty());
2109        assert_eq!(bundle.len(), 0);
2110    }
2111
2112    // --- scale test ---
2113
2114    #[test]
2115    fn bundle_extract_100_message_chain() {
2116        let mut store = ThreadedMessageStore::new();
2117        let t = thread("t1");
2118
2119        store.append(
2120            hash("m0"),
2121            t.clone(),
2122            simple_msg("tell", "start", Some(CausedBy::Begin)),
2123        );
2124        for i in 1..100 {
2125            let h = hash(&alloc::format!("m{}", i));
2126            let prev = alloc::format!("m{}", i - 1);
2127            store.append(
2128                h,
2129                t.clone(),
2130                simple_msg("reply", "msg", Some(CausedBy::Single(prev))),
2131            );
2132        }
2133
2134        let bundle = CausalClosureBundle::extract(&hash("m99"), &t, &store).unwrap();
2135        assert_eq!(bundle.len(), 100);
2136        assert!(bundle.verify_completeness().is_ok());
2137
2138        // Verify topological order: m0 before m1 before ... before m99
2139        let hashes: Vec<&ContentHash> = bundle.hashes();
2140        for i in 0..99 {
2141            let pos_i = hashes
2142                .iter()
2143                .position(|h| **h == hash(&alloc::format!("m{}", i)))
2144                .unwrap();
2145            let pos_next = hashes
2146                .iter()
2147                .position(|h| **h == hash(&alloc::format!("m{}", i + 1)))
2148                .unwrap();
2149            assert!(pos_i < pos_next, "m{} should come before m{}", i, i + 1);
2150        }
2151
2152        // Round-trip merge
2153        let mut target = ThreadedMessageStore::new();
2154        let result = bundle.merge(&mut target);
2155        assert_eq!(result.added, 100);
2156        assert_eq!(result.deduplicated, 0);
2157    }
2158
2159    // =========================================================================
2160    // SPEC-015 REQ-702: envelope shelf (append_envelope / envelope_in_thread)
2161    // =========================================================================
2162
2163    use crate::attest::{sign_attestation_v2, AttestationHeader};
2164    use crate::keyid::KeyId;
2165    use alloc::collections::BTreeSet;
2166
2167    /// Data-dependent test signer (as in `attest.rs`): any change to the
2168    /// authenticated fields kills the signature.
2169    struct TestSigner {
2170        secret: &'static [u8],
2171    }
2172
2173    impl Signer for TestSigner {
2174        fn sign(&self, data: &[u8]) -> Vec<u8> {
2175            use sha2::{Digest, Sha256};
2176            let mut h = Sha256::new();
2177            h.update(self.secret);
2178            h.update(data);
2179            h.finalize().to_vec()
2180        }
2181        fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
2182            self.sign(data) == sig
2183        }
2184    }
2185
2186    const SIGNER: TestSigner = TestSigner { secret: b"alice" };
2187
2188    fn env(hash_s: &str, perf: &str, thread_name: &str) -> RedactedEnvelope {
2189        let mut to = BTreeSet::new();
2190        to.insert(KeyId::parse("@bob").unwrap());
2191        let header = AttestationHeader {
2192            content_hash: hash_s.into(),
2193            performative: perf.into(),
2194            from: KeyId::parse("@alice").unwrap(),
2195            to,
2196            thread: thread_name.into(),
2197            caused_by: Some(CausedBy::Begin),
2198        };
2199        let signature = sign_attestation_v2(&SIGNER, &header).unwrap();
2200        RedactedEnvelope { header, signature }
2201    }
2202
2203    /// REQ-702: acceptance places the envelope in the thread its
2204    /// *authenticated* thread field names — no caller-chosen thread exists.
2205    #[test]
2206    fn envelope_is_placed_by_its_authenticated_thread() {
2207        let mut store = ThreadedMessageStore::new();
2208        assert_eq!(
2209            store.append_envelope(env("h1", "offer", "t1"), &SIGNER),
2210            Ok(true)
2211        );
2212        assert!(store
2213            .envelope_in_thread(&hash("h1"), &thread("t1"))
2214            .is_some());
2215        // Invisible from any other thread.
2216        assert!(store
2217            .envelope_in_thread(&hash("h1"), &thread("t2"))
2218            .is_none());
2219        // …and the message paths are untouched: no phantom full message.
2220        assert!(store.lookup_in_thread(&hash("h1"), &thread("t1")).is_none());
2221        assert!(!store.contains(&hash("h1"), &thread("t1")));
2222    }
2223
2224    /// REQ-702: cross-thread injection of a genuine envelope is a
2225    /// *signature* failure — relabelling the thread breaks the attestation
2226    /// and the envelope is never stored.
2227    #[test]
2228    fn relabelled_envelope_is_a_signature_failure_and_not_stored() {
2229        let mut store = ThreadedMessageStore::new();
2230        let mut e = env("h1", "offer", "t1");
2231        e.header.thread = String::from("t2"); // inject into another thread
2232        assert_eq!(
2233            store.append_envelope(e, &SIGNER),
2234            Err(crate::attest::AttestError::InvalidSignature)
2235        );
2236        assert!(store
2237            .envelope_in_thread(&hash("h1"), &thread("t1"))
2238            .is_none());
2239        assert!(store
2240            .envelope_in_thread(&hash("h1"), &thread("t2"))
2241            .is_none());
2242    }
2243
2244    #[test]
2245    fn envelope_shelf_deduplicates_by_content_hash() {
2246        let mut store = ThreadedMessageStore::new();
2247        assert_eq!(
2248            store.append_envelope(env("h1", "offer", "t1"), &SIGNER),
2249            Ok(true)
2250        );
2251        assert_eq!(
2252            store.append_envelope(env("h1", "offer", "t1"), &SIGNER),
2253            Ok(false)
2254        );
2255    }
2256
2257    /// The trait's default lookup returns `None`: a pre-SPEC-015 store
2258    /// keeps its exact v1 behaviour without touching envelope code.
2259    #[test]
2260    fn default_envelope_lookup_is_none() {
2261        struct NullStore;
2262        impl MessageStore for NullStore {
2263            fn lookup(&self, _: &ContentHash) -> Option<&Message> {
2264                None
2265            }
2266            fn lookup_in_thread(&self, _: &ContentHash, _: &ThreadId) -> Option<&Message> {
2267                None
2268            }
2269            fn contains(&self, _: &ContentHash, _: &ThreadId) -> bool {
2270                false
2271            }
2272            fn append(&mut self, _: ContentHash, _: ThreadId, _: Message) -> bool {
2273                false
2274            }
2275            fn frontier(&self, _: &ThreadId) -> Vec<&ContentHash> {
2276                Vec::new()
2277            }
2278            fn causal_closure(&self, _: &ContentHash, _: &ThreadId) -> Vec<ContentHash> {
2279                Vec::new()
2280            }
2281        }
2282        assert!(NullStore
2283            .envelope_in_thread(&hash("h1"), &thread("t1"))
2284            .is_none());
2285        // The opened-shelf lookup is likewise a default-None (SPEC-017).
2286        assert!(NullStore
2287            .opened_in_thread(&hash("h1"), &thread("t1"))
2288            .is_none());
2289    }
2290
2291    // =========================================================================
2292    // SPEC-017 REQ-813: opened-envelope shelf (append_opened / opened_in_thread)
2293    // =========================================================================
2294
2295    use crate::envelope::{build_opened, OpenedError, HEADER_FIELDS};
2296    use crate::keyid::SignatureSuite;
2297    // `Performative` is already imported by the test module above.
2298    use crate::message::Recipients;
2299    use crate::typed_addr::{typed_root, FieldId};
2300
2301    /// A predecessor message typed `perf`, sender `@alice`, thread
2302    /// `thread_name`; returns its opened envelope and its typed root.
2303    fn opened(perf: &str, thread_name: &str) -> (crate::envelope::OpenedEnvelope, String) {
2304        let mut to = alloc::collections::BTreeSet::new();
2305        to.insert("@bob".to_string());
2306        let m = Message::Simple {
2307            performative: Performative::Custom(perf.into()),
2308            recipient: Some(Recipients::Set(to)),
2309            content: SExpr::Atom(Atom::Str("secret".into())),
2310            params: Vec::new(),
2311            thread: Some(thread_name.into()),
2312            sender: Some("@alice".into()),
2313            caused_by: Some(CausedBy::Begin),
2314        };
2315        let root = typed_root(&m);
2316        let env = build_opened(&m, &HEADER_FIELDS, &SignatureSuite::Ed25519, &SIGNER).unwrap();
2317        (env, root)
2318    }
2319
2320    /// REQ-813: acceptance places an opened envelope in the thread its
2321    /// *authenticated* Thread opening names — no caller-chosen thread.
2322    #[test]
2323    fn opened_envelope_is_placed_by_its_authenticated_thread() {
2324        let mut store = ThreadedMessageStore::new();
2325        let (env, root) = opened("offer", "t1");
2326        assert_eq!(store.append_opened(env, &SIGNER), Ok(true));
2327        assert!(store
2328            .opened_in_thread(&hash(&root), &thread("t1"))
2329            .is_some());
2330        // Invisible from any other thread, and no phantom full message.
2331        assert!(store
2332            .opened_in_thread(&hash(&root), &thread("t2"))
2333            .is_none());
2334        assert!(store
2335            .lookup_in_thread(&hash(&root), &thread("t1"))
2336            .is_none());
2337    }
2338
2339    /// REQ-813: relabelling the Thread opening to inject into another thread
2340    /// makes that opening fail against the signed root — the envelope is
2341    /// never stored (fail closed at the signature/opening, not a policy).
2342    #[test]
2343    fn relabelled_opened_envelope_is_a_signature_failure_and_not_stored() {
2344        let mut store = ThreadedMessageStore::new();
2345        let (mut env, root) = opened("offer", "t1");
2346        for op in &mut env.openings {
2347            if op.field == FieldId::Thread {
2348                op.value = SExpr::List(vec![SExpr::Atom(Atom::Str("t2".to_string()))]);
2349            }
2350        }
2351        assert_eq!(
2352            store.append_opened(env, &SIGNER),
2353            Err(OpenedError::OpeningFailed {
2354                field: FieldId::Thread
2355            })
2356        );
2357        assert!(store
2358            .opened_in_thread(&hash(&root), &thread("t1"))
2359            .is_none());
2360        assert!(store
2361            .opened_in_thread(&hash(&root), &thread("t2"))
2362            .is_none());
2363    }
2364
2365    #[test]
2366    fn opened_shelf_deduplicates_by_root() {
2367        let mut store = ThreadedMessageStore::new();
2368        let (env1, _) = opened("offer", "t1");
2369        let (env2, _) = opened("offer", "t1");
2370        assert_eq!(store.append_opened(env1, &SIGNER), Ok(true));
2371        assert_eq!(store.append_opened(env2, &SIGNER), Ok(false));
2372    }
2373}