Skip to main content

cbcl_core/
blame.rs

1//! Violation blame attribution (REQ-230, REQ-232, REQ-233, CON-205).
2//!
3//! When a constraint violation is detected, a `ViolationError` captures who is
4//! responsible (`BlameParty`), what went wrong, and a chain of evidence entries
5//! (`BlameEntry`) that a third party can independently verify.
6//!
7//! `to_sexpr` produces a valid CBCL error message per REQ-233 grammar.
8//! `verify_blame` allows third-party re-checking of the evidence chain.
9
10#![forbid(unsafe_code)]
11
12use alloc::string::String;
13use alloc::vec::Vec;
14use core::fmt;
15
16use crate::protocol::CausalViolation;
17use crate::sexpr::{Atom, SExpr};
18use crate::shape::{ShapeConstraint, ShapeViolation};
19
20// ================================================================
21// Blame Party (CON-205)
22// ================================================================
23
24/// Who is responsible for a violation.
25///
26/// - `Sender` — the agent that sent a malformed or protocol-violating message.
27/// - `DialectAuthor` — the dialect definition itself contains errors (e.g. R5).
28/// - `Installer` — the agent that installed a faulty dialect.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
31pub enum BlameParty {
32    Sender,
33    DialectAuthor,
34    Installer,
35}
36
37impl BlameParty {
38    /// Symbol name used in S-expression serialisation.
39    pub fn as_str(&self) -> &'static str {
40        match self {
41            BlameParty::Sender => "sender",
42            BlameParty::DialectAuthor => "dialect-author",
43            BlameParty::Installer => "installer",
44        }
45    }
46}
47
48impl fmt::Display for BlameParty {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        f.write_str(self.as_str())
51    }
52}
53
54// ================================================================
55// Violation Kind
56// ================================================================
57
58/// Classification of the underlying constraint that was violated.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
61pub enum ViolationKind {
62    /// Operational exhaustion is not a value mismatch or sender fault.
63    ResourceLimit,
64    /// Shape constraint violation (REQ-223).
65    Shape,
66    /// Causal protocol violation (CON-202).
67    Causal,
68    /// R5 well-formedness violation (REQ-222).
69    R5,
70}
71
72impl ViolationKind {
73    /// Short symbol name (used for tracing labels and `Display`).
74    pub fn as_str(&self) -> &'static str {
75        match self {
76            ViolationKind::ResourceLimit => "resource-limit",
77            ViolationKind::Shape => "shape",
78            ViolationKind::Causal => "causal",
79            ViolationKind::R5 => "r5",
80        }
81    }
82
83    /// Quoted-string form used as the positional violation-type element in the
84    /// REQ-233 ABNF (`"shape-violation"` / `"causal-violation"` / `"r5-violation"`).
85    pub fn as_violation_type(&self) -> &'static str {
86        match self {
87            ViolationKind::ResourceLimit => "resource-limit",
88            ViolationKind::Shape => "shape-violation",
89            ViolationKind::Causal => "causal-violation",
90            ViolationKind::R5 => "r5-violation",
91        }
92    }
93}
94
95impl fmt::Display for ViolationKind {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        f.write_str(self.as_str())
98    }
99}
100
101// ================================================================
102// Blame Entry (CON-205)
103// ================================================================
104
105/// A single entry in the blame chain, attributing a piece of evidence to a party.
106#[derive(Debug, Clone, PartialEq, Eq)]
107#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
108pub struct BlameEntry {
109    /// Who is responsible.
110    pub party: BlameParty,
111    /// Human-readable reason for blame.
112    pub reason: String,
113    /// Optional evidence S-expression (the violating data).
114    pub evidence: Option<SExpr>,
115}
116
117impl BlameEntry {
118    /// Serialise this entry as an S-expression.
119    ///
120    /// ```text
121    /// (blame :party sender :reason "missing :caused-by" :evidence (...))
122    /// ```
123    pub fn to_sexpr(&self) -> SExpr {
124        let mut items: Vec<SExpr> = alloc::vec![
125            SExpr::Atom(Atom::Symbol(String::from("blame"))),
126            SExpr::Atom(Atom::Keyword(String::from("party"))),
127            SExpr::Atom(Atom::Symbol(String::from(self.party.as_str()))),
128            SExpr::Atom(Atom::Keyword(String::from("reason"))),
129            SExpr::Atom(Atom::Str(self.reason.clone())),
130        ];
131        if let Some(ref ev) = self.evidence {
132            items.push(SExpr::Atom(Atom::Keyword(String::from("evidence"))));
133            items.push(ev.clone());
134        }
135        SExpr::List(items)
136    }
137}
138
139// ================================================================
140// Violation Error (REQ-230, REQ-232)
141// ================================================================
142
143/// A complete violation error with blame attribution.
144///
145/// Carries the violation kind, a human-readable detail, optional context
146/// (message hash, thread), and a chain of blame entries that allow
147/// third-party verification.
148#[derive(Debug, Clone, PartialEq, Eq)]
149#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
150pub struct ViolationError {
151    /// What kind of constraint was violated.
152    pub kind: ViolationKind,
153    /// Ordered chain of blame entries (CON-205).
154    pub blame_chain: Vec<BlameEntry>,
155    /// Human-readable description of the violation.
156    pub detail: String,
157
158    // -- REQ-233 ABNF fields --
159    /// The party the error is addressed to (e.g. `@sender`). Positional in the
160    /// ABNF; `None` emits `@unknown` as a placeholder.
161    pub recipient: Option<String>,
162    /// Dialect name.
163    pub dialect: Option<String>,
164    /// Dialect author identity (e.g. Ed25519 key ref).
165    pub dialect_author: Option<String>,
166    /// Hash of the dialect definition.
167    pub dialect_hash: Option<String>,
168    /// Performative under which the violation occurred.
169    pub performative: Option<String>,
170    /// Identity of the agent that performed the check.
171    pub verifier: Option<String>,
172    /// Hash of the offending message.
173    pub message_hash: Option<String>,
174    /// Predecessor hash (for causal violations).
175    pub caused_by: Option<String>,
176    /// Shape rule text (for shape violations).
177    pub rule: Option<String>,
178    /// Field/keyword that failed (for shape violations).
179    pub field: Option<String>,
180    /// Expected type (for shape violations).
181    pub expected: Option<String>,
182    /// Found type (for shape violations).
183    pub found: Option<String>,
184
185    /// Thread in which the violation occurred. Retained for internal use
186    /// (metrics, callers that want to correlate with their own thread state)
187    /// but **not** emitted by `to_sexpr` — `:thread` is not in the REQ-233 ABNF.
188    pub thread_id: Option<String>,
189}
190
191impl fmt::Display for ViolationError {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        write!(f, "{} violation: {}", self.kind, self.detail)
194    }
195}
196
197// ----------------------------------------------------------------
198// Constructors
199// ----------------------------------------------------------------
200
201impl ViolationError {
202    /// Build an empty error with a given kind. Use the `with_*` builders or
203    /// `from_*` constructors to populate it.
204    fn new(kind: ViolationKind, detail: String, blame_chain: Vec<BlameEntry>) -> Self {
205        ViolationError {
206            kind,
207            blame_chain,
208            detail,
209            recipient: None,
210            dialect: None,
211            dialect_author: None,
212            dialect_hash: None,
213            performative: None,
214            verifier: None,
215            message_hash: None,
216            caused_by: None,
217            rule: None,
218            field: None,
219            expected: None,
220            found: None,
221            thread_id: None,
222        }
223    }
224
225    /// Set the recipient (the party the error is addressed to).
226    pub fn with_recipient(mut self, recipient: impl Into<String>) -> Self {
227        self.recipient = Some(recipient.into());
228        self
229    }
230
231    /// Set the verifier (the agent that performed the check).
232    pub fn with_verifier(mut self, verifier: impl Into<String>) -> Self {
233        self.verifier = Some(verifier.into());
234        self
235    }
236
237    /// Populate dialect-related fields (`:dialect`, `:dialect-author`,
238    /// `:dialect-hash`) from a `Dialect`. Also stamps `:performative` if given.
239    pub fn with_dialect_context(
240        mut self,
241        dialect_name: &str,
242        dialect_author: Option<&str>,
243        dialect_hash: Option<&str>,
244        performative: Option<&str>,
245    ) -> Self {
246        self.dialect = Some(String::from(dialect_name));
247        self.dialect_author = dialect_author.map(String::from);
248        self.dialect_hash = dialect_hash.map(String::from);
249        if let Some(p) = performative {
250            self.performative = Some(String::from(p));
251        }
252        self
253    }
254
255    /// Set the message hash.
256    pub fn with_message_hash(mut self, hash: impl Into<String>) -> Self {
257        self.message_hash = Some(hash.into());
258        self
259    }
260
261    /// Set the thread id (kept for internal use; not emitted in the wire form).
262    pub fn with_thread_id(mut self, thread: impl Into<String>) -> Self {
263        self.thread_id = Some(thread.into());
264        self
265    }
266
267    /// Create a `ViolationError` from a `ShapeViolation` (REQ-230).
268    ///
269    /// Shape violations blame the **Sender** (who sent a message that does not
270    /// conform to the declared shape) with the violating S-expression as evidence.
271    /// Populates `:rule`, `:field`, `:expected`, `:found` from the violation.
272    pub fn from_shape_violation(
273        violation: &ShapeViolation,
274        message_hash: Option<String>,
275        thread_id: Option<String>,
276        evidence: Option<SExpr>,
277    ) -> Self {
278        if violation.rule == "resource-limit" {
279            let mut err = Self::new(
280                ViolationKind::ResourceLimit,
281                violation.detail.clone(),
282                alloc::vec![],
283            );
284            err.field = violation.field.clone();
285            err.rule = Some("resource-limit".into());
286            err.message_hash = message_hash;
287            err.thread_id = thread_id;
288            return err;
289        }
290        let reason = alloc::format!(
291            "shape rule '{}' violated: {}",
292            violation.rule,
293            violation.detail
294        );
295        let mut err = Self::new(
296            ViolationKind::Shape,
297            alloc::format!("{}", violation),
298            alloc::vec![BlameEntry {
299                party: BlameParty::Sender,
300                reason,
301                evidence,
302            }],
303        );
304        err.message_hash = message_hash;
305        err.thread_id = thread_id;
306        err.rule = Some(violation.rule.clone());
307        err.field = violation.field.clone();
308        err.expected = violation.expected.clone();
309        err.found = violation.found.clone();
310        err
311    }
312
313    /// Create a `ViolationError` from a `CausalViolation` (REQ-230).
314    ///
315    /// Causal violations blame the **Sender** (who sent a message with invalid
316    /// causal predecessors). Populates `:caused-by` from the violation when
317    /// the variant carries a predecessor hash.
318    pub fn from_causal_violation(
319        violation: &CausalViolation,
320        message_hash: Option<String>,
321        thread_id: Option<String>,
322    ) -> Self {
323        let reason = alloc::format!("{}", violation);
324        let mut err = Self::new(
325            ViolationKind::Causal,
326            reason.clone(),
327            alloc::vec![BlameEntry {
328                party: BlameParty::Sender,
329                reason,
330                evidence: None,
331            }],
332        );
333        err.message_hash = message_hash;
334        err.thread_id = thread_id;
335        err.caused_by = match violation {
336            CausalViolation::UnknownPredecessor { caused_by } => Some(caused_by.clone()),
337            CausalViolation::InvalidPredecessor { caused_by, .. } => Some(caused_by.clone()),
338            _ => None,
339        };
340        err
341    }
342
343    /// Create a `ViolationError` for an *unsatisfiable* shape constraint (REQ-230).
344    ///
345    /// Per the SPEC-002 blame table, a shape that no valid message can satisfy
346    /// is the dialect author's fault, not the sender's. This constructor exists
347    /// for callers that detect unsatisfiability (e.g. at install time via
348    /// witness/example-based R5 checks, or at first runtime failure when no
349    /// sender could plausibly conform). It does *not* run a detector itself —
350    /// callers must determine unsatisfiability and supply the rationale.
351    pub fn from_unsatisfiable_shape(
352        dialect_name: &str,
353        constraint_summary: &str,
354        rationale: &str,
355    ) -> Self {
356        let detail = alloc::format!(
357            "dialect '{}' contains an unsatisfiable shape constraint: {}",
358            dialect_name,
359            constraint_summary
360        );
361        let reason = alloc::format!(
362            "shape constraint cannot be satisfied by any message: {}",
363            rationale
364        );
365        let mut err = Self::new(
366            ViolationKind::Shape,
367            detail,
368            alloc::vec![BlameEntry {
369                party: BlameParty::DialectAuthor,
370                reason,
371                evidence: None,
372            }],
373        );
374        err.dialect = Some(String::from(dialect_name));
375        err
376    }
377
378    /// Create a `ViolationError` from R5 well-formedness violations (REQ-230).
379    ///
380    /// R5 violations blame the **DialectAuthor** (who wrote a dialect with
381    /// malformed shapes or protocol) with an additional **Installer** entry
382    /// (who installed it without catching the problem).
383    pub fn from_r5_violation(dialect_name: &str, violations: &[String]) -> Self {
384        let detail = alloc::format!(
385            "dialect '{}' has {} R5 violation(s): {}",
386            dialect_name,
387            violations.len(),
388            violations.join("; ")
389        );
390
391        let author_reason =
392            alloc::format!("dialect '{}' contains well-formedness errors", dialect_name);
393        let installer_reason = alloc::format!(
394            "installed dialect '{}' without catching R5 violations",
395            dialect_name
396        );
397
398        let mut err = Self::new(
399            ViolationKind::R5,
400            detail,
401            alloc::vec![
402                BlameEntry {
403                    party: BlameParty::DialectAuthor,
404                    reason: author_reason,
405                    evidence: None,
406                },
407                BlameEntry {
408                    party: BlameParty::Installer,
409                    reason: installer_reason,
410                    evidence: None,
411                },
412            ],
413        );
414        err.dialect = Some(String::from(dialect_name));
415        err
416    }
417
418    // ----------------------------------------------------------------
419    // Serialisation (REQ-233)
420    // ----------------------------------------------------------------
421
422    /// Serialise as a CBCL error S-expression (REQ-233).
423    ///
424    /// Emits the SPEC-002 ABNF form:
425    /// ```text
426    /// (error <recipient> "shape-violation"
427    ///        :dialect <name> :dialect-author <key> :dialect-hash <hash>
428    ///        :performative <perf> :rule <rule>
429    ///        :field <field> :expected <type> :found <type>
430    ///        :detail <text>
431    ///        :blamed sender :verifier <key>
432    ///        :message-hash <hash> :caused-by <hash>
433    ///        :blame-chain (...))
434    /// ```
435    ///
436    /// Recipient is positional and falls back to `@unknown` if unset. Optional
437    /// fields are omitted when their value is `None`. `:thread` is *not*
438    /// emitted: it isn't in the ABNF (`thread_id` is retained on the struct
439    /// for internal use).
440    pub fn to_sexpr(&self) -> SExpr {
441        let mut items: Vec<SExpr> = Vec::new();
442        items.push(SExpr::Atom(Atom::Symbol(String::from("error"))));
443
444        // 1. recipient (positional)
445        let recipient = self
446            .recipient
447            .clone()
448            .unwrap_or_else(|| String::from("@unknown"));
449        items.push(SExpr::Atom(Atom::Symbol(recipient)));
450
451        // 2. violation type (positional, quoted string)
452        items.push(SExpr::Atom(Atom::Str(String::from(
453            self.kind.as_violation_type(),
454        ))));
455
456        // 3+. keyword fields
457        let push_str_kv = |items: &mut Vec<SExpr>, key: &str, val: &str| {
458            items.push(SExpr::Atom(Atom::Keyword(String::from(key))));
459            items.push(SExpr::Atom(Atom::Str(String::from(val))));
460        };
461
462        if let Some(ref v) = self.dialect {
463            push_str_kv(&mut items, "dialect", v);
464        }
465        if let Some(ref v) = self.dialect_author {
466            push_str_kv(&mut items, "dialect-author", v);
467        }
468        if let Some(ref v) = self.dialect_hash {
469            push_str_kv(&mut items, "dialect-hash", v);
470        }
471        if let Some(ref v) = self.performative {
472            push_str_kv(&mut items, "performative", v);
473        }
474        if let Some(ref v) = self.rule {
475            push_str_kv(&mut items, "rule", v);
476        }
477        if let Some(ref v) = self.field {
478            // :field is a keyword in the ABNF (e.g. `:route`).
479            items.push(SExpr::Atom(Atom::Keyword(String::from("field"))));
480            // Strip a leading ':' from the field name so we emit a bare keyword atom.
481            let stripped = v.strip_prefix(':').unwrap_or(v.as_str());
482            items.push(SExpr::Atom(Atom::Keyword(String::from(stripped))));
483        }
484        if let Some(ref v) = self.expected {
485            push_str_kv(&mut items, "expected", v);
486        }
487        if let Some(ref v) = self.found {
488            push_str_kv(&mut items, "found", v);
489        }
490
491        // :detail (always present)
492        push_str_kv(&mut items, "detail", &self.detail);
493
494        // :blamed (derived from the first blame_chain entry)
495        if let Some(first) = self.blame_chain.first() {
496            items.push(SExpr::Atom(Atom::Keyword(String::from("blamed"))));
497            items.push(SExpr::Atom(Atom::Symbol(String::from(
498                first.party.as_str(),
499            ))));
500        }
501
502        if let Some(ref v) = self.verifier {
503            push_str_kv(&mut items, "verifier", v);
504        }
505        if let Some(ref v) = self.message_hash {
506            push_str_kv(&mut items, "message-hash", v);
507        }
508        if let Some(ref v) = self.caused_by {
509            push_str_kv(&mut items, "caused-by", v);
510        }
511
512        // :blame-chain
513        items.push(SExpr::Atom(Atom::Keyword(String::from("blame-chain"))));
514        let chain: Vec<SExpr> = self.blame_chain.iter().map(|e| e.to_sexpr()).collect();
515        items.push(SExpr::List(chain));
516
517        SExpr::List(items)
518    }
519
520    // ----------------------------------------------------------------
521    // Third-party verification (REQ-232)
522    // ----------------------------------------------------------------
523
524    /// Verify that a shape-blame claim is justified by re-checking the evidence
525    /// against the given shape constraint.
526    ///
527    /// Returns `true` if the blame chain is verified: the evidence S-expression
528    /// actually fails the shape constraint, confirming the violation is real.
529    /// Returns `false` if the evidence passes (blame is unjustified) or if
530    /// verification is not applicable (wrong kind, no evidence, no constraint).
531    pub fn verify_blame(&self, shape_constraint: Option<&ShapeConstraint>) -> bool {
532        match self.kind {
533            ViolationKind::ResourceLimit => false,
534            ViolationKind::Shape => self.verify_shape_blame(shape_constraint),
535            ViolationKind::Causal => self.verify_causal_blame(),
536            ViolationKind::R5 => self.verify_r5_blame(),
537        }
538    }
539
540    /// Re-check shape violation evidence against the constraint.
541    fn verify_shape_blame(&self, shape_constraint: Option<&ShapeConstraint>) -> bool {
542        let constraint = match shape_constraint {
543            Some(c) => c,
544            None => return false,
545        };
546
547        // At least one blame entry must have evidence that actually violates
548        // the shape constraint.
549        for entry in &self.blame_chain {
550            if let Some(ref evidence) = entry.evidence {
551                if matches!(constraint.check(evidence), Err(ref e) if e.rule != "resource-limit") {
552                    return true;
553                }
554            }
555        }
556        false
557    }
558
559    /// Verify causal blame: the chain must have at least one Sender entry.
560    fn verify_causal_blame(&self) -> bool {
561        self.blame_chain
562            .iter()
563            .any(|e| e.party == BlameParty::Sender)
564    }
565
566    /// Verify R5 blame: the chain must have a DialectAuthor entry.
567    fn verify_r5_blame(&self) -> bool {
568        self.blame_chain
569            .iter()
570            .any(|e| e.party == BlameParty::DialectAuthor)
571    }
572
573    // ----------------------------------------------------------------
574    // Observability (REQ-234)
575    // ----------------------------------------------------------------
576
577    /// Emit tracing events for blame attribution metrics.
578    ///
579    /// Emits two events when the `tracing` feature is enabled:
580    /// - `cbcl_blame_attribution_count` — one event per blame-chain entry,
581    ///   with labels `{dialect, blamed_party, violation_type}`.
582    /// - `cbcl_violation_error_size_bytes` — the serialised S-expression
583    ///   byte length of this error.
584    ///
585    /// This is a no-op when the `tracing` feature is disabled.
586    #[allow(unused_variables)]
587    pub fn record_metrics(&self, dialect: &str) {
588        #[cfg(feature = "tracing")]
589        {
590            // Counter: one event per blame-chain entry.
591            for entry in &self.blame_chain {
592                tracing::event!(
593                    tracing::Level::INFO,
594                    dialect = dialect,
595                    blamed_party = entry.party.as_str(),
596                    violation_type = self.kind.as_str(),
597                    "cbcl_blame_attribution_count"
598                );
599            }
600
601            // Histogram: serialised error size in bytes.
602            let sexpr = self.to_sexpr();
603            let size = alloc::format!("{}", sexpr).len();
604            tracing::event!(
605                tracing::Level::INFO,
606                size_bytes = size,
607                violation_type = self.kind.as_str(),
608                dialect = dialect,
609                "cbcl_violation_error_size_bytes"
610            );
611        }
612    }
613}
614
615// ================================================================
616// Tests
617// ================================================================
618
619#[cfg(test)]
620mod tests {
621    use super::*;
622    use alloc::string::ToString;
623    use alloc::vec;
624
625    fn sym(s: &str) -> SExpr {
626        SExpr::Atom(Atom::Symbol(String::from(s)))
627    }
628
629    fn kw(s: &str) -> SExpr {
630        SExpr::Atom(Atom::Keyword(String::from(s)))
631    }
632
633    fn str_expr(s: &str) -> SExpr {
634        SExpr::Atom(Atom::Str(String::from(s)))
635    }
636
637    fn num(n: i64) -> SExpr {
638        SExpr::Atom(Atom::Num(n))
639    }
640
641    fn list(items: Vec<SExpr>) -> SExpr {
642        SExpr::List(items)
643    }
644
645    // -- BlameParty --
646
647    #[test]
648    fn blame_party_as_str() {
649        assert_eq!(BlameParty::Sender.as_str(), "sender");
650        assert_eq!(BlameParty::DialectAuthor.as_str(), "dialect-author");
651        assert_eq!(BlameParty::Installer.as_str(), "installer");
652    }
653
654    #[test]
655    fn blame_party_display() {
656        assert_eq!(BlameParty::Sender.to_string(), "sender");
657        assert_eq!(BlameParty::DialectAuthor.to_string(), "dialect-author");
658        assert_eq!(BlameParty::Installer.to_string(), "installer");
659    }
660
661    // -- ViolationKind --
662
663    #[test]
664    fn violation_kind_as_str() {
665        assert_eq!(ViolationKind::Shape.as_str(), "shape");
666        assert_eq!(ViolationKind::Causal.as_str(), "causal");
667        assert_eq!(ViolationKind::R5.as_str(), "r5");
668    }
669
670    #[test]
671    fn violation_kind_display() {
672        assert_eq!(ViolationKind::Shape.to_string(), "shape");
673        assert_eq!(ViolationKind::Causal.to_string(), "causal");
674        assert_eq!(ViolationKind::R5.to_string(), "r5");
675    }
676
677    // -- BlameEntry::to_sexpr --
678
679    #[test]
680    fn blame_entry_to_sexpr_with_evidence() {
681        let entry = BlameEntry {
682            party: BlameParty::Sender,
683            reason: String::from("missing :target"),
684            evidence: Some(list(vec![sym("track"), kw("route"), str_expr("A")])),
685        };
686        let sexpr = entry.to_sexpr();
687        let s = alloc::format!("{}", sexpr);
688        assert!(s.contains("blame"));
689        assert!(s.contains(":party"));
690        assert!(s.contains("sender"));
691        assert!(s.contains(":reason"));
692        assert!(s.contains("missing :target"));
693        assert!(s.contains(":evidence"));
694    }
695
696    #[test]
697    fn blame_entry_to_sexpr_without_evidence() {
698        let entry = BlameEntry {
699            party: BlameParty::DialectAuthor,
700            reason: String::from("bad shape"),
701            evidence: None,
702        };
703        let sexpr = entry.to_sexpr();
704        let s = alloc::format!("{}", sexpr);
705        assert!(s.contains("dialect-author"));
706        assert!(!s.contains(":evidence"));
707    }
708
709    // -- from_shape_violation --
710
711    #[test]
712    fn from_shape_violation_blames_sender() {
713        let sv = ShapeViolation {
714            rule: String::from("require :target string"),
715            field: Some(String::from(":target")),
716            expected: Some(String::from("string")),
717            found: Some(String::from("number")),
718            detail: String::from("parameter :target expected type string, found number"),
719        };
720        let evidence = list(vec![sym("propose"), kw("target"), num(42)]);
721        let err = ViolationError::from_shape_violation(
722            &sv,
723            Some(String::from("abc123")),
724            Some(String::from("t1")),
725            Some(evidence),
726        );
727
728        assert_eq!(err.kind, ViolationKind::Shape);
729        assert_eq!(err.message_hash, Some(String::from("abc123")));
730        assert_eq!(err.thread_id, Some(String::from("t1")));
731        assert_eq!(err.blame_chain.len(), 1);
732        assert_eq!(err.blame_chain[0].party, BlameParty::Sender);
733        assert!(err.blame_chain[0].evidence.is_some());
734        assert!(err.detail.contains("shape violation"));
735    }
736
737    // -- from_causal_violation --
738
739    #[test]
740    fn from_causal_violation_blames_sender() {
741        let cv = CausalViolation::MissingCausedBy;
742        let err = ViolationError::from_causal_violation(
743            &cv,
744            Some(String::from("def456")),
745            Some(String::from("t2")),
746        );
747
748        assert_eq!(err.kind, ViolationKind::Causal);
749        assert_eq!(err.blame_chain.len(), 1);
750        assert_eq!(err.blame_chain[0].party, BlameParty::Sender);
751        assert!(err.detail.contains("caused-by"));
752    }
753
754    #[test]
755    fn from_causal_violation_unknown_predecessor() {
756        let cv = CausalViolation::UnknownPredecessor {
757            caused_by: String::from("hash999"),
758        };
759        let err = ViolationError::from_causal_violation(&cv, None, None);
760
761        assert_eq!(err.kind, ViolationKind::Causal);
762        assert!(err.detail.contains("hash999"));
763    }
764
765    #[test]
766    fn from_causal_violation_invalid_predecessor() {
767        let cv = CausalViolation::InvalidPredecessor {
768            caused_by: String::from("hash111"),
769            expected: alloc::vec![String::from("ask"), String::from("tell")],
770            found: String::from("reply"),
771        };
772        let err = ViolationError::from_causal_violation(&cv, None, None);
773
774        assert!(err.detail.contains("hash111"));
775        assert!(err.detail.contains("reply"));
776    }
777
778    // -- from_r5_violation --
779
780    #[test]
781    fn from_r5_violation_blames_author_and_installer() {
782        let violations = alloc::vec![
783            String::from("shape targets unknown performative 'foo'"),
784            String::from("cycle detected: a → b → a"),
785        ];
786        let err = ViolationError::from_r5_violation("bad-dialect", &violations);
787
788        assert_eq!(err.kind, ViolationKind::R5);
789        assert_eq!(err.blame_chain.len(), 2);
790        assert_eq!(err.blame_chain[0].party, BlameParty::DialectAuthor);
791        assert_eq!(err.blame_chain[1].party, BlameParty::Installer);
792        assert!(err.detail.contains("bad-dialect"));
793        assert!(err.detail.contains("2 R5 violation(s)"));
794    }
795
796    // -- from_unsatisfiable_shape --
797
798    #[test]
799    fn from_unsatisfiable_shape_blames_dialect_author() {
800        let err = ViolationError::from_unsatisfiable_shape(
801            "logistics",
802            "require :route string AND require :route number",
803            "no value can satisfy both type constraints simultaneously",
804        );
805        assert_eq!(err.kind, ViolationKind::Shape);
806        assert_eq!(err.blame_chain.len(), 1);
807        assert_eq!(err.blame_chain[0].party, BlameParty::DialectAuthor);
808        assert!(err.blame_chain[0].evidence.is_none());
809        assert!(err.detail.contains("logistics"));
810        assert!(err.detail.contains("unsatisfiable"));
811        assert!(err.message_hash.is_none());
812        assert!(err.thread_id.is_none());
813    }
814
815    // -- to_sexpr (REQ-233) --
816
817    #[test]
818    fn to_sexpr_shape_violation() {
819        let sv = ShapeViolation {
820            rule: String::from("require :pkg string"),
821            field: Some(String::from(":pkg")),
822            expected: Some(String::from("string")),
823            found: Some(String::from("number")),
824            detail: String::from(":pkg expected string, found number"),
825        };
826        let err = ViolationError::from_shape_violation(
827            &sv,
828            Some(String::from("h1")),
829            Some(String::from("t1")),
830            Some(num(42)),
831        );
832        let sexpr = err.to_sexpr();
833        let s = alloc::format!("{}", sexpr);
834
835        // Must start with (error <recipient> "shape-violation" ...)
836        assert!(s.starts_with("(error @unknown \"shape-violation\""));
837        assert!(s.contains(":detail"));
838        assert!(s.contains(":message-hash"));
839        assert!(s.contains("\"h1\""));
840        // :thread is intentionally NOT in the wire form (REQ-233 ABNF).
841        assert!(!s.contains(":thread"));
842        assert!(s.contains(":blame-chain"));
843        assert!(s.contains("(blame "));
844        // Shape-derived fields are populated.
845        assert!(s.contains(":rule"));
846        assert!(s.contains(":expected"));
847        assert!(s.contains(":found"));
848    }
849
850    #[test]
851    fn to_sexpr_without_optional_fields() {
852        let cv = CausalViolation::MissingCausedBy;
853        let err = ViolationError::from_causal_violation(&cv, None, None);
854        let sexpr = err.to_sexpr();
855        let s = alloc::format!("{}", sexpr);
856
857        assert!(s.starts_with("(error @unknown \"causal-violation\""));
858        assert!(!s.contains(":message-hash"));
859        assert!(!s.contains(":thread"));
860        // :kind is no longer in the wire form (REQ-233).
861        assert!(!s.contains(":kind"));
862    }
863
864    #[test]
865    fn to_sexpr_r5_violation() {
866        let err = ViolationError::from_r5_violation("test-d", &[String::from("cycle found")]);
867        let sexpr = err.to_sexpr();
868        let s = alloc::format!("{}", sexpr);
869
870        assert!(s.starts_with("(error "));
871        assert!(s.contains("r5"));
872        assert!(s.contains(":blame-chain"));
873        // Two blame entries: dialect-author and installer
874        let blame_count = s.matches("(blame ").count();
875        assert_eq!(blame_count, 2);
876    }
877
878    /// REQ-233 ABNF conformance: positional recipient + quoted violation type +
879    /// every spec keyword field plumbed through.
880    #[test]
881    fn to_sexpr_matches_req233_abnf() {
882        let sv = ShapeViolation {
883            rule: String::from("require :route string"),
884            field: Some(String::from(":route")),
885            expected: Some(String::from("string")),
886            found: Some(String::from("number")),
887            detail: String::from(":route expected string, found number"),
888        };
889        let err =
890            ViolationError::from_shape_violation(&sv, Some(String::from("f1220msg")), None, None)
891                .with_recipient("@sender")
892                .with_verifier("@receiver")
893                .with_dialect_context(
894                    "logistics",
895                    Some("@consortium"),
896                    Some("f1220abc"),
897                    Some("track-shipment"),
898                );
899        let s = alloc::format!("{}", err.to_sexpr());
900
901        // Spec ABNF (SPEC-002 REQ-233):
902        assert!(s.starts_with("(error @sender \"shape-violation\""));
903        assert!(s.contains(":dialect "), "missing :dialect");
904        assert!(s.contains(":dialect-author "), "missing :dialect-author");
905        assert!(s.contains(":dialect-hash "), "missing :dialect-hash");
906        assert!(s.contains(":performative "), "missing :performative");
907        assert!(s.contains(":rule "), "missing :rule");
908        assert!(s.contains(":field "), "missing :field");
909        assert!(s.contains(":expected "), "missing :expected");
910        assert!(s.contains(":found "), "missing :found");
911        assert!(s.contains(":blamed sender"), "missing :blamed positional");
912        assert!(s.contains(":verifier "), "missing :verifier");
913        assert!(s.contains(":message-hash "), "missing :message-hash");
914        assert!(!s.contains(":kind"), "spec form has no :kind keyword");
915        assert!(!s.contains(":thread"), "spec form has no :thread keyword");
916    }
917
918    /// REQ-233: causal-violation form populates `:caused-by` from the violation.
919    #[test]
920    fn to_sexpr_causal_includes_caused_by() {
921        let cv = CausalViolation::UnknownPredecessor {
922            caused_by: String::from("f1220pred"),
923        };
924        let err = ViolationError::from_causal_violation(&cv, None, None)
925            .with_recipient("@sender")
926            .with_dialect_context("d", None, None, Some("ack"));
927        let s = alloc::format!("{}", err.to_sexpr());
928        assert!(s.starts_with("(error @sender \"causal-violation\""));
929        assert!(s.contains(":caused-by"));
930        assert!(s.contains("\"f1220pred\""));
931        assert!(s.contains(":blamed sender"));
932    }
933
934    /// REQ-233: `InvalidPredecessor` populates `:caused-by` with the bad
935    /// predecessor hash (the variant has different field shape from
936    /// `UnknownPredecessor`, so test it separately).
937    #[test]
938    fn to_sexpr_causal_invalid_predecessor_includes_caused_by() {
939        let cv = CausalViolation::InvalidPredecessor {
940            caused_by: String::from("f1220bad"),
941            expected: alloc::vec![String::from("pause")],
942            found: String::from("ack"),
943        };
944        let err = ViolationError::from_causal_violation(&cv, None, None);
945        assert_eq!(err.caused_by.as_deref(), Some("f1220bad"));
946        let s = alloc::format!("{}", err.to_sexpr());
947        assert!(s.contains(":caused-by"));
948        assert!(s.contains("\"f1220bad\""));
949    }
950
951    /// REQ-230 + REQ-233: unsatisfiable shape blames DialectAuthor *and*
952    /// the wire form reflects the attribution.
953    #[test]
954    fn to_sexpr_unsatisfiable_shape_blames_dialect_author() {
955        let err = ViolationError::from_unsatisfiable_shape(
956            "logistics",
957            "string AND number",
958            "no value satisfies both",
959        );
960        let s = alloc::format!("{}", err.to_sexpr());
961        assert!(s.starts_with("(error @unknown \"shape-violation\""));
962        assert!(s.contains(":blamed dialect-author"));
963        assert!(s.contains(":dialect "));
964        assert!(s.contains("\"logistics\""));
965    }
966
967    /// REQ-233: R5 emission carries dialect, blames dialect-author first,
968    /// and emits `r5-violation` (not `"r5"`).
969    #[test]
970    fn to_sexpr_r5_violation_matches_abnf() {
971        let err = ViolationError::from_r5_violation(
972            "broken",
973            &alloc::vec![String::from("cycle: a → b → a")],
974        )
975        .with_recipient("@installer");
976        let s = alloc::format!("{}", err.to_sexpr());
977        assert!(s.starts_with("(error @installer \"r5-violation\""));
978        assert!(s.contains(":dialect "));
979        assert!(s.contains("\"broken\""));
980        assert!(s.contains(":blamed dialect-author"));
981        // Two blame entries: dialect-author and installer.
982        assert_eq!(s.matches("(blame ").count(), 2);
983    }
984
985    /// `:field` is emitted as a keyword atom (e.g. `:route`), not a string.
986    /// A leading colon on the input is stripped to avoid `::route`.
987    #[test]
988    fn to_sexpr_field_emits_keyword_atom() {
989        let sv = ShapeViolation {
990            rule: String::from("require :route string"),
991            field: Some(String::from(":route")),
992            expected: None,
993            found: None,
994            detail: String::from("test"),
995        };
996        let err = ViolationError::from_shape_violation(&sv, None, None, None);
997        let sexpr = err.to_sexpr();
998
999        // Walk the items and find the :field keyword and the value following it.
1000        let items = match sexpr {
1001            SExpr::List(items) => items,
1002            _ => panic!("error must be a list"),
1003        };
1004        let mut idx = None;
1005        for (i, item) in items.iter().enumerate() {
1006            if matches!(item, SExpr::Atom(Atom::Keyword(k)) if k == "field") {
1007                idx = Some(i);
1008                break;
1009            }
1010        }
1011        let i = idx.expect(":field keyword must be present");
1012        let value = &items[i + 1];
1013        // Value must be a Keyword atom with the colon stripped.
1014        match value {
1015            SExpr::Atom(Atom::Keyword(k)) => assert_eq!(k, "route"),
1016            other => panic!(":field value must be a Keyword atom, got {other:?}"),
1017        }
1018    }
1019
1020    // -- builders --
1021
1022    #[test]
1023    fn with_recipient_sets_recipient() {
1024        let cv = CausalViolation::MissingCausedBy;
1025        let err = ViolationError::from_causal_violation(&cv, None, None).with_recipient("@alice");
1026        assert_eq!(err.recipient.as_deref(), Some("@alice"));
1027    }
1028
1029    #[test]
1030    fn with_verifier_sets_verifier() {
1031        let cv = CausalViolation::MissingCausedBy;
1032        let err = ViolationError::from_causal_violation(&cv, None, None).with_verifier("@bob");
1033        assert_eq!(err.verifier.as_deref(), Some("@bob"));
1034    }
1035
1036    #[test]
1037    fn with_message_hash_sets_message_hash() {
1038        let cv = CausalViolation::MissingCausedBy;
1039        let err =
1040            ViolationError::from_causal_violation(&cv, None, None).with_message_hash("f1220msg");
1041        assert_eq!(err.message_hash.as_deref(), Some("f1220msg"));
1042    }
1043
1044    #[test]
1045    fn with_thread_id_sets_thread_id_but_does_not_emit() {
1046        let cv = CausalViolation::MissingCausedBy;
1047        let err = ViolationError::from_causal_violation(&cv, None, None).with_thread_id("t-7");
1048        assert_eq!(err.thread_id.as_deref(), Some("t-7"));
1049        let s = alloc::format!("{}", err.to_sexpr());
1050        assert!(!s.contains(":thread"));
1051        assert!(!s.contains("t-7"));
1052    }
1053
1054    #[test]
1055    fn with_dialect_context_sets_all_fields() {
1056        let cv = CausalViolation::MissingCausedBy;
1057        let err = ViolationError::from_causal_violation(&cv, None, None).with_dialect_context(
1058            "d",
1059            Some("@a"),
1060            Some("h"),
1061            Some("p"),
1062        );
1063        assert_eq!(err.dialect.as_deref(), Some("d"));
1064        assert_eq!(err.dialect_author.as_deref(), Some("@a"));
1065        assert_eq!(err.dialect_hash.as_deref(), Some("h"));
1066        assert_eq!(err.performative.as_deref(), Some("p"));
1067    }
1068
1069    #[test]
1070    fn with_dialect_context_handles_optional_fields() {
1071        let cv = CausalViolation::MissingCausedBy;
1072        let err = ViolationError::from_causal_violation(&cv, None, None)
1073            .with_dialect_context("d", None, None, None);
1074        assert_eq!(err.dialect.as_deref(), Some("d"));
1075        assert_eq!(err.dialect_author, None);
1076        assert_eq!(err.dialect_hash, None);
1077        assert_eq!(err.performative, None);
1078    }
1079
1080    // -- ViolationError::display --
1081
1082    #[test]
1083    fn violation_error_display() {
1084        let cv = CausalViolation::MissingCausedBy;
1085        let err = ViolationError::from_causal_violation(&cv, None, None);
1086        let s = err.to_string();
1087        assert!(s.contains("causal violation"));
1088    }
1089
1090    // -- verify_blame --
1091
1092    #[test]
1093    fn verify_blame_shape_with_valid_evidence() {
1094        use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
1095
1096        let constraint = ShapeConstraint {
1097            performative: String::from("track"),
1098            rules: vec![ShapeRule::Require {
1099                keyword: String::from("package"),
1100                type_constraint: Some(TypeConstraint::String),
1101                children: vec![],
1102            }],
1103        };
1104
1105        // Evidence that actually violates the constraint (wrong type)
1106        let evidence = list(vec![sym("track"), kw("package"), num(42)]);
1107        let sv = ShapeViolation {
1108            rule: String::from("require :package string"),
1109            field: Some(String::from(":package")),
1110            expected: Some(String::from("string")),
1111            found: Some(String::from("number")),
1112            detail: String::from(":package expected string, found number"),
1113        };
1114        let err = ViolationError::from_shape_violation(&sv, None, None, Some(evidence));
1115
1116        assert!(err.verify_blame(Some(&constraint)));
1117    }
1118
1119    #[test]
1120    fn verify_blame_shape_with_passing_evidence_returns_false() {
1121        use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
1122
1123        let constraint = ShapeConstraint {
1124            performative: String::from("track"),
1125            rules: vec![ShapeRule::Require {
1126                keyword: String::from("package"),
1127                type_constraint: Some(TypeConstraint::String),
1128                children: vec![],
1129            }],
1130        };
1131
1132        // Evidence that actually passes (correct type) — blame is unjustified
1133        let evidence = list(vec![sym("track"), kw("package"), str_expr("box-1")]);
1134        let sv = ShapeViolation {
1135            rule: String::from("require :package string"),
1136            field: Some(String::from(":package")),
1137            expected: Some(String::from("string")),
1138            found: Some(String::from("number")),
1139            detail: String::from("fabricated violation"),
1140        };
1141        let err = ViolationError::from_shape_violation(&sv, None, None, Some(evidence));
1142
1143        assert!(!err.verify_blame(Some(&constraint)));
1144    }
1145
1146    #[test]
1147    fn verify_blame_shape_without_constraint_returns_false() {
1148        let sv = ShapeViolation {
1149            rule: String::from("require :x"),
1150            field: None,
1151            expected: None,
1152            found: None,
1153            detail: String::from("missing"),
1154        };
1155        let err = ViolationError::from_shape_violation(&sv, None, None, Some(sym("x")));
1156        assert!(!err.verify_blame(None));
1157    }
1158
1159    #[test]
1160    fn verify_blame_shape_without_evidence_returns_false() {
1161        use crate::shape::{ShapeConstraint, ShapeRule, TypeConstraint};
1162
1163        let constraint = ShapeConstraint {
1164            performative: String::from("track"),
1165            rules: vec![ShapeRule::Require {
1166                keyword: String::from("package"),
1167                type_constraint: Some(TypeConstraint::String),
1168                children: vec![],
1169            }],
1170        };
1171
1172        let sv = ShapeViolation {
1173            rule: String::from("require :package string"),
1174            field: None,
1175            expected: None,
1176            found: None,
1177            detail: String::from("missing"),
1178        };
1179        let err = ViolationError::from_shape_violation(&sv, None, None, None);
1180        assert!(!err.verify_blame(Some(&constraint)));
1181    }
1182
1183    #[test]
1184    fn verify_blame_causal() {
1185        let cv = CausalViolation::MissingCausedBy;
1186        let err = ViolationError::from_causal_violation(&cv, None, None);
1187        assert!(err.verify_blame(None));
1188    }
1189
1190    #[test]
1191    fn verify_blame_r5() {
1192        let err = ViolationError::from_r5_violation("d", &[String::from("bad")]);
1193        assert!(err.verify_blame(None));
1194    }
1195
1196    #[test]
1197    fn verify_blame_r5_without_author_returns_false() {
1198        // Start from a real R5 error then overwrite the chain with only Installer.
1199        let mut err = ViolationError::from_r5_violation("d", &[String::from("x")]);
1200        err.blame_chain = vec![BlameEntry {
1201            party: BlameParty::Installer,
1202            reason: String::from("installed bad dialect"),
1203            evidence: None,
1204        }];
1205        assert!(!err.verify_blame(None));
1206    }
1207
1208    #[test]
1209    fn verify_blame_causal_without_sender_returns_false() {
1210        let cv = CausalViolation::MissingCausedBy;
1211        let mut err = ViolationError::from_causal_violation(&cv, None, None);
1212        err.blame_chain = vec![BlameEntry {
1213            party: BlameParty::DialectAuthor,
1214            reason: String::from("wrong party"),
1215            evidence: None,
1216        }];
1217        assert!(!err.verify_blame(None));
1218    }
1219
1220    // -- Equality and Clone --
1221
1222    #[test]
1223    fn blame_party_copy_and_eq() {
1224        let a = BlameParty::Sender;
1225        let b = a; // Copy
1226        assert_eq!(a, b);
1227    }
1228
1229    #[test]
1230    fn violation_error_clone_and_eq() {
1231        let err = ViolationError::from_r5_violation("d", &[String::from("x")]);
1232        let err2 = err.clone();
1233        assert_eq!(err, err2);
1234    }
1235
1236    // -- record_metrics (REQ-234) --
1237
1238    #[test]
1239    fn record_metrics_does_not_panic_shape() {
1240        let sv = ShapeViolation {
1241            rule: String::from("require :x string"),
1242            field: Some(String::from(":x")),
1243            expected: Some(String::from("string")),
1244            found: Some(String::from("number")),
1245            detail: String::from(":x expected string, found number"),
1246        };
1247        let err = ViolationError::from_shape_violation(
1248            &sv,
1249            Some(String::from("h1")),
1250            Some(String::from("t1")),
1251            Some(num(42)),
1252        );
1253        // Should not panic regardless of tracing feature state.
1254        err.record_metrics("test-dialect");
1255    }
1256
1257    #[test]
1258    fn record_metrics_does_not_panic_causal() {
1259        let cv = CausalViolation::MissingCausedBy;
1260        let err = ViolationError::from_causal_violation(&cv, None, None);
1261        err.record_metrics("test-dialect");
1262    }
1263
1264    #[test]
1265    fn record_metrics_does_not_panic_r5() {
1266        let err = ViolationError::from_r5_violation("bad-d", &[String::from("cycle")]);
1267        // R5 has two blame-chain entries; both should be emitted.
1268        err.record_metrics("bad-d");
1269    }
1270}