Skip to main content

rigorix_verifier/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2//! rigorix-verifier — protocol-only verification of Rigorix audit envelopes.
3//!
4//! Strategy A (SDK freeze D-2): the HMAC trail must be independently
5//! checkable anywhere — this crate verifies envelopes WITHOUT depending on
6//! rigorix-engine. The envelope structs below are FROZEN copies of
7//! rigorix-oss `engine/src/audit/domain/envelope.rs` + the redacted identity
8//! ref from `identity/domain/claim.rs` (contract freeze: do not edit them to
9//! match engine internals; edit them only when the SDK schemas change).
10//!
11//! @canonical schemas/envelope.json (Rigorix Audit Envelope v2) — the contract
12//! this verifier checks against; the frozen structs below mirror rigorix-oss
13//! `engine/src/audit/domain/envelope.rs`.
14//!
15//! Canonicalization contract (must reproduce the engine byte-exact):
16//! HMAC-SHA256 over `serde_json::to_string(envelope with signature = None)`.
17//! Struct field order is declaration order; Options with `skip_serializing_if`
18//! are omitted when None; Options without it serialize as `null`; empty
19//! vectors/maps with `skip_serializing_if` are omitted. The signature field is
20//! NOT skipped — canonical bytes include `"signature": null`.
21
22use std::collections::HashMap;
23use std::path::Path;
24
25use chrono::{DateTime, Utc};
26use ed25519_dalek::{Signature, Verifier, VerifyingKey};
27use hmac::{Hmac, Mac};
28use serde::{Deserialize, Serialize};
29use sha2::{Digest, Sha256};
30
31/// Deterministic map serialization (mirrors rigorix-oss envelope.rs).
32///
33/// Envelope maps MUST serialize byte-identically on every process for the
34/// HMAC canonical form to be reproducible. `std::collections::HashMap`
35/// iteration order is hash-randomized per process, so maps are emitted with
36/// sorted keys (JSON object key order is not semantic — shape unchanged).
37mod sorted_map {
38    use serde::Serialize;
39    use std::collections::BTreeMap;
40
41    pub fn serialize<S, K, V>(
42        value: &std::collections::HashMap<K, V>,
43        serializer: S,
44    ) -> Result<S::Ok, S::Error>
45    where
46        S: serde::Serializer,
47        K: Ord + serde::Serialize,
48        V: serde::Serialize,
49    {
50        let ordered: BTreeMap<&K, &V> = value.iter().collect();
51        ordered.serialize(serializer)
52    }
53}
54
55/// JSON Schema conformance failure.
56#[derive(Debug, thiserror::Error)]
57pub enum VerifyError {
58    #[error("envelope parse failed: {0}")]
59    Parse(#[from] serde_json::Error),
60    #[error("schema read failed: {0}")]
61    SchemaRead(String),
62    #[error("schema validation failed: {0}")]
63    Schema(String),
64    #[error("signature field is null")]
65    MissingSignature,
66    #[error("signature mismatch: expected {expected}, got {got}")]
67    SignatureMismatch { expected: String, got: String },
68    #[error("unsigned envelope without evidence_degraded=true (GAP-M-12 violation)")]
69    UnsignedNotDegraded,
70    #[error("HMAC key error: {0}")]
71    HmacKey(String),
72    #[error("audit chain broken: {detail}")]
73    ChainBroken { detail: String },
74    #[error("invalid Ed25519 anchor signature: {0}")]
75    AnchorSignature(String),
76    #[error(
77        "method `{0}` is not declared in the frozen rigorix.* catalog \
78         (ADR-0001 D3 — the namespace is closed; a server implements a subset)"
79    )]
80    UndeclaredMethod(String),
81    #[error("effect record invariant violated: {detail}")]
82    EffectInvariant { detail: String },
83    #[error("settlement evidence has no readback bytes to verify")]
84    ReadbackMissing,
85    #[error("readback digest mismatch: expected {expected}, got {got}")]
86    ReadbackDigestMismatch { expected: String, got: String },
87}
88
89pub type VerifyResult<T> = Result<T, VerifyError>;
90
91type HmacSha256 = Hmac<Sha256>;
92
93// ─── Frozen envelope structs (mirror rigorix-oss envelope.rs) ───────────────
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct AuditEnvelope {
97    pub execution_id: uuid::Uuid,
98    pub timestamp: DateTime<Utc>,
99    pub template_id: String,
100    pub planning_hash: String,
101    pub source: Option<String>,
102    pub repository: Option<String>,
103    pub author: Option<String>,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub identity: Option<IdentityRef>,
106    /// ADR-014: domain-supplied canonical effect key (one-way keyed hash).
107    /// Serde-defaulted, omitted when absent — canonical bytes unchanged for
108    /// effect-less envelopes. MUST stay in the engine's struct position
109    /// (after `identity`, before `total_tokens`).
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub effect_key: Option<String>,
112    pub total_tokens: u32,
113    pub duration_ms: u64,
114    pub git_commit: Option<String>,
115    pub git_branch: Option<String>,
116    pub model_version: Option<String>,
117    pub planning_prompt: Option<String>,
118    #[serde(default, skip_serializing_if = "Vec::is_empty")]
119    pub file_paths: Vec<String>,
120    pub events: Vec<ExecutionEventRef>,
121    #[serde(
122        default,
123        skip_serializing_if = "HashMap::is_empty",
124        serialize_with = "sorted_map::serialize"
125    )]
126    pub scoring_results: HashMap<String, ScoringResultRef>,
127    pub signature: Option<String>,
128    #[serde(default)]
129    pub evidence_degraded: bool,
130    /// ADR-016 / GAP-A-30 (Phase A): the chain this envelope belongs to.
131    /// Additive and serde-defaulted; `None` in legacy (pre-chain) envelopes.
132    /// MUST stay in the engine's struct position (after `evidence_degraded`,
133    /// before `approval_events`) or canonical bytes diverge.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub producer_id: Option<String>,
136    /// ADR-016: monotonic per-producer sequence (genesis 0). Serde-defaulted.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub sequence: Option<u64>,
139    /// ADR-016: SHA-256 of the predecessor's canonical bytes (`signature`
140    /// nulled — the SAME form the HMAC signs). `None` for genesis/legacy.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub prev_hash: Option<String>,
143    /// ADR-016: which integrity regime produced this evidence.
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub history_integrity: Option<HistoryIntegrity>,
146    /// ADR-016: the recorded `allow_unanchored` opt-in, when present. Adds to
147    /// the signed bytes, so the regime is auditable.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub history_policy: Option<HistoryPolicy>,
150    /// ADR-016 Phase C: the **verified** anchor ledger head this evidence was
151    /// decided against — `Some` only in `anchored` mode, bound into the signed
152    /// bytes so an auditor can prove which ledger state a decision used.
153    /// MUST stay in the engine's struct position (after `history_policy`,
154    /// before `approval_events`) or canonical bytes diverge.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub anchor_head: Option<String>,
157    #[serde(default, skip_serializing_if = "Vec::is_empty")]
158    pub approval_events: Vec<ApprovalRecordRef>,
159    #[serde(default, skip_serializing_if = "Vec::is_empty")]
160    pub scope_violations: Vec<ScopeViolationRef>,
161    /// #1189: whether the R5 scope check actually ran. `None` on legacy
162    /// envelopes. MUST stay in the engine's struct position (after
163    /// `scope_violations`, before `sequence_policy_findings`) or canonical
164    /// bytes diverge; 0.8.0 omitted the field, which made every envelope
165    /// carrying it fail verification (#1222).
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub scope_check: Option<ScopeCheckStatus>,
168    #[serde(default, skip_serializing_if = "Vec::is_empty")]
169    pub sequence_policy_findings: Vec<SequencePolicyFindingRef>,
170    /// R9/ADR-015 operator step-requirement findings. MUST stay after
171    /// `sequence_policy_findings` and before `decision_context_ref`.
172    #[serde(default, skip_serializing_if = "Vec::is_empty")]
173    pub requirement_findings: Vec<RequirementFindingRef>,
174    /// ADR-017 R1/B dispatch-time precondition findings. MUST stay after
175    /// `requirement_findings` and before `decision_context_ref`.
176    #[serde(default, skip_serializing_if = "Vec::is_empty")]
177    pub precondition_findings: Vec<PreconditionFindingRef>,
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub decision_context_ref: Option<String>,
180}
181
182/// Whether the R5 effect-scope check ran, separate from what it found (#1189).
183#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
184#[serde(rename_all = "snake_case")]
185pub enum ScopeCheckStatus {
186    Checked,
187    NotDeclared,
188    Unavailable,
189}
190
191/// ADR-016: which integrity regime produced an envelope's evidence.
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(rename_all = "snake_case")]
194pub enum HistoryIntegrity {
195    /// Local cache only — tamper-evident, not anchor-authenticated.
196    LocalUnanchored,
197    /// Anchor-authenticated evidence (Phase C).
198    Anchored,
199    /// Anchor configured in anchored mode but no verified head exists yet
200    /// (startup window). Not anchor-authenticated; never treat as `Anchored`.
201    AnchoredPending,
202}
203
204/// ADR-016: a recorded history-policy opt-in.
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
206#[serde(rename_all = "snake_case")]
207pub enum HistoryPolicy {
208    /// Accept best-effort evaluation over `local_unanchored` history.
209    AllowUnanchored,
210}
211
212#[derive(Debug, Clone, Serialize, Deserialize)]
213pub struct IdentityRef {
214    pub subject: String,
215    pub issuer: String,
216    pub source: IdentitySource,
217    pub authority: Option<String>,
218    pub expires_at: Option<DateTime<Utc>>,
219}
220
221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222#[serde(rename_all = "snake_case")]
223pub enum IdentitySource {
224    IdpToken,
225    LocalPrincipal,
226    Unverified,
227}
228
229#[derive(Debug, Clone, Serialize, Deserialize)]
230pub struct ExecutionEventRef {
231    pub event_type: String,
232    pub summary: String,
233    pub occurred_at: DateTime<Utc>,
234    pub correlation_id: Option<uuid::Uuid>,
235    pub status: EventStatus,
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub payload: Option<serde_json::Value>,
238}
239
240/// EventStatus mirrors the engine enum EXACTLY — including the absence of
241/// `rename_all`: serde emits the capitalized variant names
242/// (`Success`, `Failure`, `Skipped`, `Cancelled`).
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
244pub enum EventStatus {
245    Success,
246    Failure,
247    Skipped,
248    Cancelled,
249}
250
251/// How an approval's `intent_hash` came to exist (#1243).
252#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(rename_all = "snake_case")]
254pub enum IntentHashProvenance {
255    /// The re-deriving engine computed it from the sealed graph (RS-011).
256    Derived,
257    /// A caller asserted it; the attestation covers who said it, not the graph.
258    Asserted,
259}
260
261#[derive(Debug, Clone, Serialize, Deserialize)]
262pub struct ApprovalRecordRef {
263    pub node_id: uuid::Uuid,
264    pub step_name: String,
265    pub intent_hash: String,
266    /// Required: a verifier can distinguish RS-011 binding from RS-013
267    /// attribution. The field sits after `intent_hash` in the signed bytes.
268    pub intent_hash_provenance: IntentHashProvenance,
269    pub approver_id: String,
270    pub authority: Option<String>,
271    pub decided_at: DateTime<Utc>,
272}
273
274#[derive(Debug, Clone, Serialize, Deserialize)]
275pub struct ScopeViolationRef {
276    pub node_id: uuid::Uuid,
277    pub step_name: String,
278    pub out_of_scope: Vec<String>,
279    pub detected_at: DateTime<Utc>,
280}
281
282#[derive(Debug, Clone, Serialize, Deserialize)]
283pub struct SequencePolicyFindingRef {
284    pub rule_id: String,
285    pub action: String,
286    pub later_step: String,
287    pub matched_indices: Vec<usize>,
288    pub summary: String,
289}
290
291/// R9/ADR-015 redacted operator step-requirement finding (mirrors the engine
292/// `RequirementFindingRef`). Parameter VALUES never appear (SpanPrivacy).
293#[derive(Debug, Clone, Serialize, Deserialize)]
294pub struct RequirementFindingRef {
295    pub requirement_id: String,
296    pub step: String,
297    pub action: String,
298    pub unmet: Vec<String>,
299    pub summary: String,
300}
301
302/// ADR-017 R1/B dispatch-time precondition finding (mirrors the engine
303/// `PreconditionFindingRef`). Fixed shape: `exit_code` is always serialized
304/// (`null` for `error`/`unarmed`). Only an `inputs_hash` is recorded \u2014 never
305/// parameter values or raw stdout (SpanPrivacy).
306#[derive(Debug, Clone, Serialize, Deserialize)]
307pub struct PreconditionFindingRef {
308    pub precondition_id: String,
309    pub step: String,
310    pub outcome: String,
311    pub exit_code: Option<i32>,
312    pub inputs_hash: String,
313    pub checked_at: DateTime<Utc>,
314    pub summary: String,
315    /// ADR-017 attribution (#987): SHA-256 of the resolved check program.
316    /// Additive/omitted when absent (pre-attribution envelope).
317    #[serde(default, skip_serializing_if = "Option::is_none")]
318    pub check_digest: Option<String>,
319    /// ADR-017 attribution (#987): SHA-256 of the authority artifact the check
320    /// consulted. A changed authority changes this digest.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub authority_digest: Option<String>,
323    /// ADR-017 boundary fact (#986): the check was writable by the engine euid.
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub check_writable: Option<bool>,
326    /// ISSUE-ATTRIBUTION-ABSENCE-REASON: structured reason the attribution
327    /// digests are present or absent (`recorded` | `refused_before_check` |
328    /// `artifact_unreadable`). Additive/omitted when absent (pre-attribution
329    /// envelope); a new engine always sets it.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub attribution: Option<String>,
332}
333
334#[derive(Debug, Clone, Serialize, Deserialize)]
335pub struct ScoringResultRef {
336    pub passed: bool,
337    pub backend: String,
338    #[serde(serialize_with = "sorted_map::serialize")]
339    pub dimensions: HashMap<String, ScoreDimensionRef>,
340    pub duration_ms: u64,
341}
342
343#[derive(Debug, Clone, Serialize, Deserialize)]
344pub struct ScoreDimensionRef {
345    pub score: f64,
346    pub max: f64,
347    pub label: String,
348    pub passed: bool,
349}
350
351// ─── Verification ────────────────────────────────────────────────────────────
352
353/// Compute the canonical envelope bytes: parse, null the signature, serialize
354/// exactly as the engine's `compute_signature` does.
355pub fn canonical_bytes(json: &str) -> VerifyResult<Vec<u8>> {
356    let envelope: AuditEnvelope = serde_json::from_str(json)?;
357    canonical_bytes_of(&envelope)
358}
359
360/// Canonical bytes of a parsed envelope (`signature` nulled, sorted maps) —
361/// ADR-016: the SAME bytes define the HMAC signature, `prev_hash`, ledger
362/// `envelope_hash`, and checkpoint `prior_head`/`new_head` (one form).
363pub fn canonical_bytes_of(envelope: &AuditEnvelope) -> VerifyResult<Vec<u8>> {
364    let mut canonical = envelope.clone();
365    canonical.signature = None;
366    Ok(serde_json::to_vec(&canonical)?)
367}
368
369/// SHA-256 (hex) of an envelope's canonical bytes — the `prev_hash` value a
370/// successor stores (and the ledger `envelope_hash`).
371pub fn envelope_hash(json: &str) -> VerifyResult<String> {
372    let envelope: AuditEnvelope = serde_json::from_str(json)?;
373    envelope_hash_of(&envelope)
374}
375
376/// SHA-256 (hex) of a parsed envelope's canonical bytes.
377pub fn envelope_hash_of(envelope: &AuditEnvelope) -> VerifyResult<String> {
378    Ok(sha256_hex(&canonical_bytes_of(envelope)?))
379}
380
381fn sha256_hex(bytes: &[u8]) -> String {
382    let mut hasher = Sha256::new();
383    hasher.update(bytes);
384    hasher
385        .finalize()
386        .iter()
387        .map(|b| format!("{b:02x}"))
388        .collect()
389}
390
391fn truncate8(s: &str) -> &str {
392    &s[..s.len().min(8)]
393}
394
395// ─── ADR-016: local per-producer chain ───────────────────────────────────────
396
397/// Group chained envelopes by producer and sort each chain by sequence.
398fn chains_by_producer(envelopes: &[AuditEnvelope]) -> Vec<(String, Vec<&AuditEnvelope>)> {
399    let mut by_producer: HashMap<String, Vec<&AuditEnvelope>> = HashMap::new();
400    for envelope in envelopes {
401        if let (Some(producer), Some(_)) = (envelope.producer_id.as_deref(), envelope.sequence) {
402            by_producer
403                .entry(producer.to_string())
404                .or_default()
405                .push(envelope);
406        }
407    }
408    let mut producers: Vec<String> = by_producer.keys().cloned().collect();
409    producers.sort();
410    producers
411        .into_iter()
412        .map(|producer| {
413            let mut chain = by_producer.remove(&producer).unwrap_or_default();
414            chain.sort_by_key(|e| e.sequence.expect("filtered on Some(sequence)"));
415            (producer, chain)
416        })
417        .collect()
418}
419
420/// Verify the local per-producer chain (ADR-016 Phase A), strictly — no gap is
421/// accepted. For each producer with chained envelopes:
422/// - genesis is sequence `0` with no `prev_hash` (a later start = head deletion);
423/// - sequences are contiguous and strictly increasing (missing = interior
424///   deletion; duplicate/out-of-order = insertion/reorder);
425/// - each successor's `prev_hash` equals SHA-256 of the predecessor's canonical
426///   bytes.
427///
428/// Legacy envelopes (`producer_id`/`sequence` = `None`) carry no chain claim and
429/// are grandfathered. See [`verify_chain_with_checkpoints`] to accept a range
430/// covered by a valid signed compaction checkpoint.
431pub fn verify_chain(envelopes: &[AuditEnvelope]) -> VerifyResult<()> {
432    verify_chain_with_checkpoints(envelopes, &[], "")
433}
434
435/// Verify the local per-producer chain, accepting a gap **iff** it is covered
436/// by a valid anchor-signed compaction checkpoint (ADR-016 AC 7): the
437/// checkpoint must bracket the gap with `prior_head == hash(before)` and
438/// `new_head == prev_hash(after)`, and name exactly the missing sequence range.
439/// An uncovered gap fails.
440pub fn verify_chain_with_checkpoints(
441    envelopes: &[AuditEnvelope],
442    checkpoints: &[CompactionCheckpoint],
443    anchor_public_key_hex: &str,
444) -> VerifyResult<()> {
445    // A checkpoint can only excuse a gap after its Ed25519 signature verifies.
446    for checkpoint in checkpoints {
447        verify_compaction_checkpoint(checkpoint, anchor_public_key_hex)?;
448    }
449
450    for (producer, chain) in chains_by_producer(envelopes) {
451        if chain.is_empty() {
452            continue;
453        }
454        let base = chain[0].sequence.expect("chained");
455        if base != 0 {
456            return Err(VerifyError::ChainBroken {
457                detail: format!(
458                    "producer '{producer}': chain starts at sequence {base}, not genesis 0 — \
459                     the earliest envelope(s) were deleted"
460                ),
461            });
462        }
463        if chain[0].prev_hash.is_some() {
464            return Err(VerifyError::ChainBroken {
465                detail: format!(
466                    "producer '{producer}': genesis envelope carries a prev_hash — \
467                     content was reordered into the genesis slot"
468                ),
469            });
470        }
471
472        for pair in chain.windows(2) {
473            let prev = pair[0];
474            let next = pair[1];
475            let prev_seq = prev.sequence.expect("chained");
476            let next_seq = next.sequence.expect("chained");
477            if next_seq <= prev_seq {
478                return Err(VerifyError::ChainBroken {
479                    detail: format!(
480                        "producer '{producer}': sequence not strictly increasing \
481                         ({prev_seq} -> {next_seq}) — insertion/reorder"
482                    ),
483                });
484            }
485            let prev_hash = envelope_hash_of(prev)?;
486            if next_seq == prev_seq + 1 {
487                match next.prev_hash.as_deref() {
488                    Some(actual) if actual == prev_hash => {}
489                    Some(actual) => {
490                        return Err(VerifyError::ChainBroken {
491                            detail: format!(
492                                "producer '{producer}': prev_hash mismatch at sequence \
493                                 {next_seq} (expected {}…, got {}…)",
494                                truncate8(&prev_hash),
495                                truncate8(actual),
496                            ),
497                        });
498                    }
499                    None => {
500                        return Err(VerifyError::ChainBroken {
501                            detail: format!(
502                                "producer '{producer}': missing prev_hash at sequence {next_seq}"
503                            ),
504                        });
505                    }
506                }
507                continue;
508            }
509
510            // A gap [prev_seq+1, next_seq-1] must be covered by a valid signed
511            // checkpoint that brackets it: prior_head == hash(before) and
512            // new_head == prev_hash(after) (the link over the erased range).
513            let next_link = next
514                .prev_hash
515                .as_deref()
516                .ok_or_else(|| VerifyError::ChainBroken {
517                    detail: format!(
518                        "producer '{producer}': missing prev_hash after gap at sequence {next_seq}"
519                    ),
520                })?;
521            let covered = checkpoints.iter().any(|c| {
522                c.sequence_from == prev_seq + 1
523                    && c.sequence_to == next_seq - 1
524                    && c.prior_head == prev_hash
525                    && c.new_head == next_link
526            });
527            if !covered {
528                return Err(VerifyError::ChainBroken {
529                    detail: format!(
530                        "producer '{producer}': uncovered gap sequences {}..={} \
531                         (missing envelopes with no valid compaction checkpoint)",
532                        prev_seq + 1,
533                        next_seq - 1,
534                    ),
535                });
536            }
537        }
538    }
539    Ok(())
540}
541
542// ─── ADR-016: anchor-signed artifacts (Ed25519) ──────────────────────────────
543
544/// ADR-016 anchor-signed ledger receipt.
545#[derive(Debug, Clone, Serialize, Deserialize)]
546pub struct LedgerReceipt {
547    pub ledger_id: String,
548    pub envelope_hash: String,
549    pub sequence: u64,
550    pub recorded_at: DateTime<Utc>,
551    /// `None` only while computing the signing bytes (`sig` nulled).
552    pub sig: Option<String>,
553}
554
555/// One prior action in an anchor-signed history slice (mirrors engine
556/// `HistoryAction`; parameter values never appear).
557#[derive(Debug, Clone, Serialize, Deserialize)]
558pub struct HistoryActionRef {
559    pub node: String,
560    pub principal: Option<String>,
561    pub at: DateTime<Utc>,
562    #[serde(default, skip_serializing_if = "Option::is_none")]
563    pub effect_key: Option<String>,
564}
565
566/// ADR-016 anchor-signed history projection the guard consumes in anchored mode.
567#[derive(Debug, Clone, Serialize, Deserialize)]
568pub struct HistorySlice {
569    pub scope: String,
570    pub since: DateTime<Utc>,
571    pub actions: Vec<HistoryActionRef>,
572    pub head_hash: String,
573    pub sig: Option<String>,
574}
575
576/// ADR-016 anchor-signed compaction checkpoint.
577#[derive(Debug, Clone, Serialize, Deserialize)]
578pub struct CompactionCheckpoint {
579    pub sequence_from: u64,
580    pub sequence_to: u64,
581    pub reason: String,
582    pub prior_head: String,
583    pub new_head: String,
584    pub sig: Option<String>,
585}
586
587// ─── Effect commitment (ADR-019 / SDK 0.7.0) ────────────────────────────────
588//
589// Mirrors rigorix-oss `effect_commitment` (state machine, ObservedOutcome) and
590// the frozen enterprise wire record (`EffectRecordResponse`). The artifact is
591// the PAIR — record + the evidence that settled it — because the wire record
592// alone carries no evidence and a `committed` claim with no receipt behind it
593// must not verify.
594
595/// Lifecycle state of a recorded effect (mirrors rigorix-oss `EffectState`).
596#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
597#[serde(rename_all = "snake_case")]
598pub enum EffectState {
599    /// Durable intent recorded; the effect has been (or is being) sent.
600    Dispatched,
601    /// Provider evidence proves the effect committed (terminal for this attempt).
602    Committed,
603    /// Provider evidence proves the effect did not commit (terminal for this attempt).
604    NotCommitted,
605    /// The outcome is unknown until a resolver presents provider evidence.
606    /// Deliberately NOT terminal.
607    Ambiguous,
608}
609
610impl EffectState {
611    /// Whether no further transition is legal for this attempt.
612    pub fn is_terminal(&self) -> bool {
613        matches!(self, Self::Committed | Self::NotCommitted)
614    }
615
616    /// The canonical snake_case wire label.
617    pub fn as_str(&self) -> &'static str {
618        match self {
619            Self::Dispatched => "dispatched",
620            Self::Committed => "committed",
621            Self::NotCommitted => "not_committed",
622            Self::Ambiguous => "ambiguous",
623        }
624    }
625}
626
627impl std::fmt::Display for EffectState {
628    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
629        f.write_str(self.as_str())
630    }
631}
632
633/// What a provider read-back proved (mirrors rigorix-oss `OutcomeVerdict`).
634#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
635#[serde(rename_all = "snake_case")]
636pub enum OutcomeVerdict {
637    Committed,
638    NotCommitted,
639}
640
641impl OutcomeVerdict {
642    /// The terminal state this verdict authorises.
643    pub fn terminal_state(&self) -> EffectState {
644        match self {
645            Self::Committed => EffectState::Committed,
646            Self::NotCommitted => EffectState::NotCommitted,
647        }
648    }
649
650    /// The canonical snake_case wire label.
651    pub fn as_str(&self) -> &'static str {
652        match self {
653            Self::Committed => "committed",
654            Self::NotCommitted => "not_committed",
655        }
656    }
657}
658
659/// The class of a resolver (mirrors enterprise `ResolverKind`).
660#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
661#[serde(rename_all = "snake_case")]
662pub enum ResolverKind {
663    Operator,
664    Reconciler,
665    BreakGlass,
666}
667
668/// Who settled an ambiguous attempt (`ResolverIdentity`).
669#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
670pub struct ResolverIdentity {
671    pub actor: String,
672    pub kind: ResolverKind,
673}
674
675/// The frozen wire record (mirrors enterprise `EffectRecordResponse`).
676#[derive(Debug, Clone, Serialize, Deserialize)]
677pub struct EffectRecord {
678    pub id: uuid::Uuid,
679    pub intent_key: String,
680    pub dag_id: String,
681    pub node_id: String,
682    pub attempt: u32,
683    pub state: EffectState,
684    pub dispatched_by: String,
685    pub deadline: Option<DateTime<Utc>>,
686    pub reason: Option<String>,
687    pub created_at: DateTime<Utc>,
688}
689
690/// Provider evidence that settled an attempt (mirrors OSS `ObservedOutcome`),
691/// plus the exact read-back bytes and the optional resolver.
692#[derive(Debug, Clone, Serialize, Deserialize)]
693pub struct SettlementEvidence {
694    pub receipt_id: String,
695    pub readback_digest: String,
696    pub observed_at: DateTime<Utc>,
697    pub source: String,
698    pub verdict: OutcomeVerdict,
699    /// Exact provider response bytes (UTF-8). Optional: absent means only the
700    /// structural claim is available.
701    #[serde(default, skip_serializing_if = "Option::is_none")]
702    pub readback: Option<String>,
703    /// Present only when an `ambiguous` attempt was settled by a resolver.
704    #[serde(default, skip_serializing_if = "Option::is_none")]
705    pub resolver: Option<ResolverIdentity>,
706}
707
708/// Durability axis: how long the record survives.
709#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
710#[serde(rename_all = "lowercase")]
711pub enum Durability {
712    /// In-process only: after a restart there is no record, no fence, no sweep.
713    L1,
714    /// Shared/durable: records and fences survive process death.
715    L2,
716}
717
718/// Settlement axis: whether provider evidence can prove the effect settled.
719#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
720#[serde(rename_all = "lowercase")]
721pub enum SettlementLevel {
722    /// The deployment can prove not-settled, never settled.
723    None,
724    /// A configured provider read-back can prove settlement.
725    L3,
726}
727
728/// What the producing deployment can do, on two independent axes.
729///
730/// `l1` durability + `l3` settlement is legitimate (an in-process ledger with a
731/// receipt reader). Never collapse the axes into one label (#1182).
732#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
733pub struct ClaimLevels {
734    pub durability: Durability,
735    pub settlement: SettlementLevel,
736}
737
738/// The effect-commitment artifact: record + settlement evidence + levels.
739#[derive(Debug, Clone, Serialize, Deserialize)]
740pub struct EffectRecordArtifact {
741    pub record: EffectRecord,
742    /// Legality is state-dependent: terminal states require it, non-terminal
743    /// states forbid it (`verify_effect_record`).
744    #[serde(default, skip_serializing_if = "Option::is_none")]
745    pub settlement: Option<SettlementEvidence>,
746    pub levels: ClaimLevels,
747}
748
749/// Canonical signing bytes for a ledger receipt (`sig` nulled).
750pub fn ledger_receipt_signing_bytes(receipt: &LedgerReceipt) -> VerifyResult<Vec<u8>> {
751    let mut unsigned = receipt.clone();
752    unsigned.sig = None;
753    Ok(serde_json::to_vec(&unsigned)?)
754}
755
756/// Canonical signing bytes for a history slice (`sig` nulled).
757pub fn history_slice_signing_bytes(slice: &HistorySlice) -> VerifyResult<Vec<u8>> {
758    let mut unsigned = slice.clone();
759    unsigned.sig = None;
760    Ok(serde_json::to_vec(&unsigned)?)
761}
762
763/// Canonical signing bytes for a compaction checkpoint (`sig` nulled).
764pub fn compaction_checkpoint_signing_bytes(
765    checkpoint: &CompactionCheckpoint,
766) -> VerifyResult<Vec<u8>> {
767    let mut unsigned = checkpoint.clone();
768    unsigned.sig = None;
769    Ok(serde_json::to_vec(&unsigned)?)
770}
771
772fn public_key_from_hex(public_key_hex: &str) -> VerifyResult<VerifyingKey> {
773    let bytes = hex::decode(public_key_hex)
774        .map_err(|e| VerifyError::AnchorSignature(format!("public key hex: {e}")))?;
775    let arr: [u8; 32] = bytes
776        .as_slice()
777        .try_into()
778        .map_err(|_| VerifyError::AnchorSignature("public key must be 32 bytes".to_string()))?;
779    VerifyingKey::from_bytes(&arr).map_err(|e| VerifyError::AnchorSignature(e.to_string()))
780}
781
782/// Verify an Ed25519 signature (`sig_hex`, 64 bytes) over `canonical` with the
783/// anchor's public key (`public_key_hex`, 32 bytes).
784pub fn verify_ed25519(canonical: &[u8], sig_hex: &str, public_key_hex: &str) -> VerifyResult<()> {
785    let key = public_key_from_hex(public_key_hex)?;
786    let sig_bytes = hex::decode(sig_hex)
787        .map_err(|e| VerifyError::AnchorSignature(format!("signature hex: {e}")))?;
788    let arr: [u8; 64] = sig_bytes
789        .as_slice()
790        .try_into()
791        .map_err(|_| VerifyError::AnchorSignature("signature must be 64 bytes".to_string()))?;
792    let signature = Signature::from_bytes(&arr);
793    key.verify(canonical, &signature)
794        .map_err(|e| VerifyError::AnchorSignature(e.to_string()))
795}
796
797/// Verify a ledger receipt's Ed25519 signature.
798pub fn verify_ledger_receipt(receipt: &LedgerReceipt, public_key_hex: &str) -> VerifyResult<()> {
799    let sig = receipt.sig.clone().unwrap_or_default();
800    verify_ed25519(
801        &ledger_receipt_signing_bytes(receipt)?,
802        &sig,
803        public_key_hex,
804    )
805}
806
807/// Verify a history slice's Ed25519 signature.
808pub fn verify_history_slice(slice: &HistorySlice, public_key_hex: &str) -> VerifyResult<()> {
809    let sig = slice.sig.clone().unwrap_or_default();
810    verify_ed25519(&history_slice_signing_bytes(slice)?, &sig, public_key_hex)
811}
812
813/// Verify a compaction checkpoint's Ed25519 signature.
814pub fn verify_compaction_checkpoint(
815    checkpoint: &CompactionCheckpoint,
816    public_key_hex: &str,
817) -> VerifyResult<()> {
818    let sig = checkpoint.sig.clone().unwrap_or_default();
819    verify_ed25519(
820        &compaction_checkpoint_signing_bytes(checkpoint)?,
821        &sig,
822        public_key_hex,
823    )
824}
825
826/// Structural verification of an effect-commitment artifact.
827///
828/// Independently re-checks what the engine's `EffectRecord::hydrate` enforces:
829///
830/// - a terminal state carries settlement evidence (`EvidenceMissing`);
831/// - a non-terminal state carries none — no outcome, no resolver (`Contended`);
832/// - `dispatched` carries a deadline;
833/// - the verdict authorises the record's terminal state;
834/// - evidence implies the deployment's settlement level is `l3`.
835///
836/// It does NOT bind the record to a signed envelope: the record is unsigned and
837/// its intent is not derivable from the envelope (see the schema ceiling).
838pub fn verify_effect_record(artifact: &EffectRecordArtifact) -> VerifyResult<()> {
839    let record = &artifact.record;
840
841    if record.state == EffectState::Dispatched && record.deadline.is_none() {
842        return Err(VerifyError::EffectInvariant {
843            detail: "dispatched record must carry a deadline".to_string(),
844        });
845    }
846
847    match (record.state.is_terminal(), artifact.settlement.as_ref()) {
848        (true, None) => {
849            return Err(VerifyError::EffectInvariant {
850                detail: format!(
851                    "terminal state `{}` must carry settlement evidence (EvidenceMissing)",
852                    record.state
853                ),
854            });
855        }
856        (false, Some(_)) => {
857            return Err(VerifyError::EffectInvariant {
858                detail: format!(
859                    "non-terminal state `{}` must not carry settlement evidence (Contended)",
860                    record.state
861                ),
862            });
863        }
864        _ => {}
865    }
866
867    if let Some(settlement) = artifact.settlement.as_ref() {
868        let authorised = settlement.verdict.terminal_state();
869        if authorised != record.state {
870            return Err(VerifyError::EffectInvariant {
871                detail: format!(
872                    "settlement verdict `{}` authorises `{}`, but the record is `{}`",
873                    settlement.verdict.as_str(),
874                    authorised,
875                    record.state
876                ),
877            });
878        }
879        if artifact.levels.settlement != SettlementLevel::L3 {
880            return Err(VerifyError::EffectInvariant {
881                detail: "settlement evidence is present but levels.settlement is `none`"
882                    .to_string(),
883            });
884        }
885    }
886
887    Ok(())
888}
889
890/// Readback verification: re-derive `readback_digest` from the exact provider
891/// bytes carried in `settlement.readback` (`hex(SHA-256(bytes))`).
892///
893/// This is the level that makes "settled" a claim rather than a field: the
894/// provider is the authority for the effect, the record is not. A missing body
895/// is refused rather than silently downgraded to the structural claim.
896pub fn verify_settlement_evidence(artifact: &EffectRecordArtifact) -> VerifyResult<()> {
897    verify_effect_record(artifact)?;
898    let settlement = artifact
899        .settlement
900        .as_ref()
901        .ok_or_else(|| VerifyError::EffectInvariant {
902            detail: "no settlement evidence to verify".to_string(),
903        })?;
904    let readback = settlement
905        .readback
906        .as_ref()
907        .ok_or(VerifyError::ReadbackMissing)?;
908    let got = hex::encode(Sha256::digest(readback.as_bytes()));
909    if got != settlement.readback_digest {
910        return Err(VerifyError::ReadbackDigestMismatch {
911            expected: settlement.readback_digest.clone(),
912            got,
913        });
914    }
915    Ok(())
916}
917
918/// Compute the HMAC-SHA256 hex signature over the canonical form.
919pub fn sign(json: &str, key: &str) -> VerifyResult<String> {
920    let mut mac = HmacSha256::new_from_slice(key.as_bytes())
921        .map_err(|e| VerifyError::HmacKey(e.to_string()))?;
922    mac.update(&canonical_bytes(json)?);
923    Ok(hex::encode(mac.finalize().into_bytes()))
924}
925
926/// Verify an envelope's signature over its canonical form.
927///
928/// GAP-M-12: an envelope with `signature: null` is only acceptable when
929/// `evidence_degraded: true` (explicitly produced unsigned). A null signature
930/// without the marker is treated as tampering evidence.
931pub fn verify_signature(json: &str, key: &str) -> VerifyResult<()> {
932    let envelope: AuditEnvelope = serde_json::from_str(json)?;
933    let Some(expected) = envelope.signature.as_ref() else {
934        if envelope.evidence_degraded {
935            return Ok(()); // intentionally unsigned, explicitly marked
936        }
937        return Err(VerifyError::UnsignedNotDegraded);
938    };
939    let got = sign(json, key)?;
940    if constant_time_eq(expected, &got) {
941        Ok(())
942    } else {
943        Err(VerifyError::SignatureMismatch {
944            expected: expected.clone(),
945            got,
946        })
947    }
948}
949
950/// Validate an envelope against the SDK envelope schema (`envelope.json`).
951///
952/// The schema resolves from `RIGORIX_SDK_SCHEMAS` (explicit override) or the
953/// embedded `rigorix-schemas` corpus — never from the repo layout.
954pub fn validate_schema(json: &str) -> VerifyResult<()> {
955    validate_schema_file("envelope.json", json)
956}
957
958/// Validate any JSON instance against a named SDK schema file.
959fn validate_schema_file(file: &str, json: &str) -> VerifyResult<()> {
960    let schema_text = schema_text(file)?;
961    let schema = serde_json::from_str(&schema_text)?;
962    let instance: serde_json::Value = serde_json::from_str(json)?;
963    let compiled = build_validator(file, &schema)?;
964    let errors: Vec<String> = compiled
965        .iter_errors(&instance)
966        .map(|e| e.to_string())
967        .collect();
968    if !errors.is_empty() {
969        return Err(VerifyError::Schema(errors.join("; ")));
970    }
971    Ok(())
972}
973
974/// Resolve a contract's JSON text (SDK-VERIFIER-PUBLISH resolution order).
975///
976/// 1. `RIGORIX_SDK_SCHEMAS` — an explicit external corpus (CI/local override).
977/// 2. The embedded `rigorix-schemas` corpus — the published, self-contained path.
978///
979/// There is deliberately **no** `CARGO_MANIFEST_DIR/../../schemas` fallback: a
980/// published verifier must not depend on the repo layout.
981fn schema_text(file: &str) -> VerifyResult<String> {
982    if let Ok(dir) = std::env::var("RIGORIX_SDK_SCHEMAS") {
983        let path = Path::new(&dir).join(file);
984        if !path.exists() {
985            return Err(VerifyError::SchemaRead(format!(
986                "RIGORIX_SDK_SCHEMAS set but {} missing",
987                path.display()
988            )));
989        }
990        return std::fs::read_to_string(&path)
991            .map_err(|e| VerifyError::SchemaRead(format!("{}: {e}", path.display())));
992    }
993    rigorix_schemas::schema(file)
994        .map(str::to_string)
995        .ok_or_else(|| {
996            VerifyError::SchemaRead(format!(
997                "schema `{file}` not found — set RIGORIX_SDK_SCHEMAS or use the embedded \
998             rigorix-schemas corpus"
999            ))
1000        })
1001}
1002
1003/// Verify that every method in `candidate` is declared in the frozen catalog
1004/// (`schemas/api/catalog.json`).
1005///
1006/// ADR-0001 D3: the `rigorix.*` namespace is **closed** — a server implements a
1007/// SUBSET of the frozen catalog and MUST NOT register an undeclared method.
1008/// Server CI / conformance passes the method set it serves; an unknown
1009/// `rigorix.*` name is a contract violation (SDK-C5 / #15).
1010pub fn verify_catalog_subset(candidate: &[&str]) -> VerifyResult<()> {
1011    let text = schema_text("api/catalog.json")?;
1012    let catalog: serde_json::Value = serde_json::from_str(&text)?;
1013    let declared: std::collections::HashSet<&str> = catalog["methods"]
1014        .as_array()
1015        .ok_or_else(|| VerifyError::Schema("catalog.json: methods is not an array".to_string()))?
1016        .iter()
1017        .filter_map(|method| method["name"].as_str())
1018        .collect();
1019    for method in candidate {
1020        if !declared.contains(method) {
1021            return Err(VerifyError::UndeclaredMethod((*method).to_string()));
1022        }
1023    }
1024    Ok(())
1025}
1026
1027/// The `$id` of the canonical envelope schema — a cross-file `$ref` target on
1028/// the contract surface (`api/events.json` → `envelope.json`).
1029const ENVELOPE_SCHEMA_ID: &str = "https://rigorix.eu/schemas/envelope-v2.json";
1030
1031/// The `$id` of the canonical claims schema — the home of the shared identity
1032/// shapes, a cross-file `$ref` target from the catalog
1033/// (`api/catalog.json` → `claims.json#/$defs/identityRef|identityClaim`).
1034const CLAIMS_SCHEMA_ID: &str = "https://rigorix.eu/schemas/claims.json";
1035
1036/// The `$id` of the ADR-016 history-slice schema — the result shape of
1037/// `rigorix.audit.history`, referenced cross-file from the catalog.
1038const HISTORY_SLICE_SCHEMA_ID: &str = "https://rigorix.eu/schemas/api/history-slice-v1.json";
1039
1040/// The `$id` of the consequence-gating §4.3 authority-fact bundle schema — the
1041/// result shape of `rigorix.audit.authorityFacts`, referenced cross-file from
1042/// the catalog. It in turn `$ref`s the one canonical envelope dialect.
1043const AUTHORITY_FACT_BUNDLE_SCHEMA_ID: &str =
1044    "https://rigorix.eu/schemas/api/authority-fact-bundle-v1.json";
1045
1046/// Build a JSON Schema validator, registering sibling contract schemas so
1047/// cross-file `$ref`s resolve offline (`events.json` → `envelope.json`;
1048/// `api/catalog.json` → `claims.json`).
1049///
1050/// The schema being compiled is never registered as its own sibling resource.
1051fn build_validator(file: &str, schema: &serde_json::Value) -> VerifyResult<jsonschema::Validator> {
1052    let mut options = jsonschema::options();
1053    for (sibling, id) in [
1054        ("envelope.json", ENVELOPE_SCHEMA_ID),
1055        ("claims.json", CLAIMS_SCHEMA_ID),
1056        ("api/history-slice.json", HISTORY_SLICE_SCHEMA_ID),
1057        (
1058            "api/authority-fact-bundle.json",
1059            AUTHORITY_FACT_BUNDLE_SCHEMA_ID,
1060        ),
1061    ] {
1062        if file == sibling {
1063            continue;
1064        }
1065        let text = schema_text(sibling)?;
1066        let value: serde_json::Value = serde_json::from_str(&text)?;
1067        let resource = jsonschema::Resource::from_contents(value)
1068            .map_err(|e| VerifyError::Schema(e.to_string()))?;
1069        options.with_resource(id, resource);
1070    }
1071    options
1072        .build(schema)
1073        .map_err(|e| VerifyError::Schema(e.to_string()))
1074}
1075
1076/// Constant-time comparison for hex signatures.
1077fn constant_time_eq(a: &str, b: &str) -> bool {
1078    if a.len() != b.len() {
1079        return false;
1080    }
1081    a.bytes()
1082        .zip(b.bytes())
1083        .fold(0u8, |acc, (x, y)| acc | (x ^ y))
1084        == 0
1085}
1086
1087#[cfg(test)]
1088mod tests {
1089    use super::*;
1090
1091    // ─── Contract resolution (env override -> embedded rigorix-schemas) ───
1092    //
1093    // Tests must exercise the PUBLISHED resolution path: with no override they
1094    // read the embedded corpus, exactly like a consumer of the packaged crate.
1095
1096    /// Read a fixture by path relative to `schemas/fixtures/`.
1097    fn fixture_text(rel: &str) -> String {
1098        if let Ok(dir) = std::env::var("RIGORIX_SDK_SCHEMAS") {
1099            let path = Path::new(&dir).join("fixtures").join(rel);
1100            return std::fs::read_to_string(&path)
1101                .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
1102        }
1103        rigorix_schemas::fixture(rel)
1104            .map(str::to_string)
1105            .unwrap_or_else(|| panic!("fixture `{rel}` is not embedded in rigorix-schemas"))
1106    }
1107
1108    /// Every `.json` fixture path relative to `fixtures/<prefix>/`, sorted.
1109    fn fixture_json_names(prefix: &str) -> Vec<String> {
1110        if let Ok(dir) = std::env::var("RIGORIX_SDK_SCHEMAS") {
1111            let root = Path::new(&dir).join("fixtures").join(prefix);
1112            let mut out = Vec::new();
1113            collect_json(&root, &root, &mut out);
1114            out.sort();
1115            return out;
1116        }
1117        let needle = format!("fixtures/{prefix}/");
1118        let mut out: Vec<String> = rigorix_schemas::schema_names()
1119            .iter()
1120            .filter_map(|name| name.strip_prefix(&needle))
1121            .filter(|rel| rel.ends_with(".json"))
1122            .map(str::to_string)
1123            .collect();
1124        out.sort();
1125        out
1126    }
1127
1128    fn collect_json(root: &Path, dir: &Path, out: &mut Vec<String>) {
1129        let entries =
1130            std::fs::read_dir(dir).unwrap_or_else(|e| panic!("read {}: {e}", dir.display()));
1131        for entry in entries {
1132            let path = entry.expect("dir entry").path();
1133            if path.is_dir() {
1134                collect_json(root, &path, out);
1135            } else if path.extension().and_then(|e| e.to_str()) == Some("json") {
1136                out.push(
1137                    path.strip_prefix(root)
1138                        .expect("under fixture root")
1139                        .to_string_lossy()
1140                        .replace('\\', "/"),
1141                );
1142            }
1143        }
1144    }
1145
1146    const KEY: &str = "test-hmac-key";
1147
1148    fn minimal_envelope() -> String {
1149        serde_json::json!({
1150            "execution_id": "c24a5a7e-1f4d-4f0e-9b3a-8e0d3a1b2c3d",
1151            "timestamp": "2026-09-07T10:00:00Z",
1152            "template_id": "conference-registration",
1153            "planning_hash": "abc123",
1154            "total_tokens": 1000,
1155            "duration_ms": 5000,
1156            "events": [
1157                {
1158                    "event_type": "tool_executed",
1159                    "summary": "removed alice",
1160                    "occurred_at": "2026-09-07T09:59:59Z",
1161                    "status": "Success"
1162                }
1163            ],
1164            "signature": null,
1165            "evidence_degraded": false
1166        })
1167        .to_string()
1168    }
1169
1170    fn signed_envelope() -> String {
1171        let json = minimal_envelope();
1172        let sig = sign(&json, KEY).unwrap();
1173        let mut v: serde_json::Value = serde_json::from_str(&json).unwrap();
1174        v["signature"] = serde_json::Value::String(sig);
1175        v.to_string()
1176    }
1177
1178    #[test]
1179    fn sign_and_verify_roundtrip() {
1180        let envelope = signed_envelope();
1181        assert!(verify_signature(&envelope, KEY).is_ok());
1182    }
1183
1184    #[test]
1185    fn tampering_detected() {
1186        let mut v: serde_json::Value = serde_json::from_str(&signed_envelope()).unwrap();
1187        v["total_tokens"] = serde_json::json!(9999); // tamper
1188        let err = verify_signature(&v.to_string(), KEY).unwrap_err();
1189        assert!(matches!(err, VerifyError::SignatureMismatch { .. }));
1190    }
1191
1192    #[test]
1193    fn unsigned_must_be_degraded() {
1194        // signature null, evidence_degraded false → GAP-M-12 violation
1195        let err = verify_signature(&minimal_envelope(), KEY).unwrap_err();
1196        assert!(matches!(err, VerifyError::UnsignedNotDegraded));
1197    }
1198
1199    #[test]
1200    fn unsigned_marked_degraded_is_ok() {
1201        let mut v: serde_json::Value = serde_json::from_str(&minimal_envelope()).unwrap();
1202        v["evidence_degraded"] = serde_json::json!(true);
1203        assert!(verify_signature(&v.to_string(), KEY).is_ok());
1204    }
1205
1206    #[test]
1207    fn wrong_key_fails() {
1208        let envelope = signed_envelope();
1209        let err = verify_signature(&envelope, "wrong-key").unwrap_err();
1210        assert!(matches!(err, VerifyError::SignatureMismatch { .. }));
1211    }
1212
1213    #[test]
1214    fn canonical_stability() {
1215        // Parsing + re-serializing twice must produce identical canonical bytes.
1216        let a = canonical_bytes(&minimal_envelope()).unwrap();
1217        let b = canonical_bytes(&minimal_envelope()).unwrap();
1218        assert_eq!(a, b);
1219    }
1220
1221    #[test]
1222    fn schema_conformance_of_minimal() {
1223        // minimal_envelope is unsigned with evidence_degraded=false — schema
1224        // allows it (schema describes shape, not policy); verifier policy
1225        // (GAP-M-12) is enforced in verify_signature.
1226        assert!(validate_schema(&minimal_envelope()).is_ok());
1227    }
1228
1229    #[test]
1230    fn schema_rejects_wrong_status_case() {
1231        // v1 schema requires serde-exact capitalized EventStatus; lowercase
1232        // `success` must fail schema validation.
1233        let mut v: serde_json::Value = serde_json::from_str(&minimal_envelope()).unwrap();
1234        v["events"][0]["status"] = serde_json::json!("success");
1235        let err = validate_schema(&v.to_string()).unwrap_err();
1236        assert!(matches!(err, VerifyError::Schema(_)));
1237    }
1238
1239    // ─── ADR-015 operator step-requirements (R9) ──────────────────────────
1240    //
1241    // Grounded in rigorix-oss `sequence_policy/domain/requirement.rs` +
1242    // `audit/domain/envelope.rs` (code is truth).
1243    #[test]
1244    fn policy_schema_round_trips_step_requirement() {
1245        let policy = serde_json::json!({
1246            "fail_closed": true,
1247            "rules": [],
1248            "requirements": [{
1249                "id": "payout-guard",
1250                "name": "Payout commands must be attested and carry effect data",
1251                "description": "d",
1252                "match": {
1253                    "tool": "run_command",
1254                    "params": [{
1255                        "pointer": "/command",
1256                        "kind": "glob",
1257                        "value": "*execute_payout.sh*"
1258                    }]
1259                },
1260                "require_identity": true,
1261                "require_params": ["/beneficiary", "/effect_key"],
1262                "action": "deny"
1263            }]
1264        });
1265        assert!(validate_schema_file("policy.json", &policy.to_string()).is_ok());
1266
1267        // `action` is serde-defaulted — a requirement may omit it.
1268        let mut defaulted = policy.clone();
1269        defaulted["requirements"][0]
1270            .as_object_mut()
1271            .unwrap()
1272            .remove("action");
1273        assert!(validate_schema_file("policy.json", &defaulted.to_string()).is_ok());
1274
1275        // `name` has NO serde default on StepRequirement — it is required.
1276        let mut missing_name = policy.clone();
1277        missing_name["requirements"][0]
1278            .as_object_mut()
1279            .unwrap()
1280            .remove("name");
1281        assert!(validate_schema_file("policy.json", &missing_name.to_string()).is_err());
1282
1283        // require_params entries are JSON pointers — must start with '/'.
1284        let mut bad_pointer = policy.clone();
1285        bad_pointer["requirements"][0]["require_params"] = serde_json::json!(["beneficiary"]);
1286        assert!(validate_schema_file("policy.json", &bad_pointer.to_string()).is_err());
1287    }
1288
1289    #[test]
1290    fn envelope_schema_accepts_requirement_findings() {
1291        let mut v: serde_json::Value = serde_json::from_str(&minimal_envelope()).unwrap();
1292        v["requirement_findings"] = serde_json::json!([{
1293            "requirement_id": "payout-guard",
1294            "step": "pay",
1295            "action": "deny",
1296            "unmet": ["identity", "/beneficiary"],
1297            "summary": "operator requirement 'payout-guard' denied step 'pay'"
1298        }]);
1299        assert!(validate_schema(&v.to_string()).is_ok());
1300
1301        // `unmet` is required on RequirementFindingRef.
1302        let mut bad = v.clone();
1303        bad["requirement_findings"][0]
1304            .as_object_mut()
1305            .unwrap()
1306            .remove("unmet");
1307        assert!(validate_schema(&bad.to_string()).is_err());
1308
1309        // Action is the lowercase serde set — `DENY` is not a valid value.
1310        let mut wrong_action = v.clone();
1311        wrong_action["requirement_findings"][0]["action"] = serde_json::json!("DENY");
1312        assert!(validate_schema(&wrong_action.to_string()).is_err());
1313    }
1314
1315    // ─── Real engine fixture corpus (F-20260907-01) ────────────────────────
1316    //
1317    // Envelopes in schemas/fixtures/envelope/*.json are produced by REAL
1318    // rigorix-oss engine runs (fixed test key fixture-hmac-key-2026, see the
1319    // README there). Verifying them byte-exact proves canonicalization parity
1320    // between the engine and this independent verifier — the Strategy A
1321    // claim that the HMAC trail is checkable anywhere.
1322    #[test]
1323    fn engine_signed_fixtures_verify_byte_exact() {
1324        let key = "fixture-hmac-key-2026";
1325        let names = fixture_json_names("envelope");
1326        let mut found = 0;
1327        for name in &names {
1328            let json = fixture_text(&format!("envelope/{name}"));
1329            // Independent verifier accepts the engine's signature byte-exact.
1330            verify_signature(&json, key).unwrap_or_else(|e| panic!("{name}: {e}"));
1331            // And the envelope conforms to the SDK schema.
1332            validate_schema(&json).unwrap_or_else(|e| panic!("{name}: {e}"));
1333            found += 1;
1334        }
1335        assert!(
1336            found >= 3,
1337            "expected ≥3 committed engine fixtures, found {found}"
1338        );
1339    }
1340
1341    /// #1243: an approval ref states whether its intent hash was derived by
1342    /// the engine or asserted by a caller. The field is required and sits in
1343    /// the signed bytes immediately after `intent_hash`.
1344    #[test]
1345    fn approval_ref_provenance_is_required_and_signed() {
1346        let json = fixture_text("envelope/envelope-rich-signed.json");
1347        let envelope: AuditEnvelope = serde_json::from_str(&json).expect("fixture parses");
1348        let approval = envelope
1349            .approval_events
1350            .first()
1351            .expect("rich fixture carries an approval");
1352        assert_eq!(
1353            approval.intent_hash_provenance,
1354            IntentHashProvenance::Derived,
1355            "the OSS engine emits derived intent hashes"
1356        );
1357
1358        let mut value: serde_json::Value = serde_json::from_str(&json).expect("json");
1359        let refs = value["approval_events"]
1360            .as_array_mut()
1361            .expect("approval_events");
1362        refs[0]["intent_hash_provenance"] = serde_json::json!("asserted");
1363        let asserted = serde_json::to_string(&value).expect("serialize");
1364        validate_schema(&asserted).expect("asserted is a valid, weaker kind");
1365        let asserted_envelope: AuditEnvelope =
1366            serde_json::from_value(value.clone()).expect("asserted parses");
1367        assert_eq!(
1368            asserted_envelope.approval_events[0].intent_hash_provenance,
1369            IntentHashProvenance::Asserted
1370        );
1371
1372        value["approval_events"][0]
1373            .as_object_mut()
1374            .expect("approval ref")
1375            .remove("intent_hash_provenance");
1376        let missing = serde_json::to_string(&value).expect("serialize");
1377        assert!(
1378            validate_schema(&missing).is_err(),
1379            "schema must reject an approval ref that does not state provenance"
1380        );
1381        assert!(
1382            serde_json::from_value::<AuditEnvelope>(value).is_err(),
1383            "deserialization must reject a missing provenance, not default it"
1384        );
1385    }
1386
1387    /// SDK #31 / ADR-016 Phase C regression: the anchored engine fixture's HMAC
1388    /// reproduces ONLY when `anchor_head` sits after `history_policy` and before
1389    /// `approval_events`. Before the field was declared the verifier dropped it,
1390    /// so this failed with `SignatureMismatch` on authentic anchored evidence.
1391    #[test]
1392    fn anchored_envelope_binds_anchor_head_at_engine_position() {
1393        const HEAD: &str = "3f2a9c1e7b4d5f6081a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708";
1394        let json = fixture_text("envelope/envelope-anchored-signed.json");
1395        let envelope: AuditEnvelope = serde_json::from_str(&json).expect("anchored fixture parses");
1396        assert_eq!(envelope.history_integrity, Some(HistoryIntegrity::Anchored));
1397        assert_eq!(envelope.anchor_head.as_deref(), Some(HEAD));
1398        assert!(
1399            !envelope.approval_events.is_empty(),
1400            "fixture must carry approval_events (position proof)"
1401        );
1402
1403        // Byte-exact parity — the regression: dropping the field breaks this.
1404        verify_signature(&json, "fixture-hmac-key-2026")
1405            .expect("anchored fixture verifies byte-exact");
1406        validate_schema(&json).expect("anchored fixture conforms to envelope.json");
1407
1408        // The field is signed, in the engine's declared position.
1409        let bytes = canonical_bytes_of(&envelope).expect("canonical bytes");
1410        let canonical = String::from_utf8(bytes).expect("utf8");
1411        let head_at = canonical
1412            .find("\"anchor_head\"")
1413            .expect("anchor_head is part of the signed bytes");
1414        let approvals_at = canonical
1415            .find("\"approval_events\"")
1416            .expect("approval_events present");
1417        assert!(
1418            head_at < approvals_at,
1419            "anchor_head must precede approval_events"
1420        );
1421
1422        // Tampering with the head is detected (it is not ignored).
1423        let tampered = json.replacen(HEAD, &"0".repeat(64), 1);
1424        assert!(matches!(
1425            verify_signature(&tampered, "fixture-hmac-key-2026"),
1426            Err(VerifyError::SignatureMismatch { .. })
1427        ));
1428
1429        // A legacy fixture has no anchor_head — skip-if-none keeps its bytes
1430        // unchanged (Phase A regression guard).
1431        let local = fixture_text("envelope/envelope-minimal-signed.json");
1432        assert!(!local.contains("\"anchor_head\""));
1433        verify_signature(&local, "fixture-hmac-key-2026").expect("local fixture unchanged");
1434    }
1435
1436    /// SDK #39 / ADR-017: write the contract-first `precondition_findings[]`
1437    /// fixture. The engine does not implement ADR-017 yet, so the reference
1438    /// verifier signs a minimal envelope (the cross-language check is that
1439    /// Python/TS/Java/Go independently reproduce the bytes). Regenerate from the
1440    /// engine once ADR-017 Phase B lands.
1441    #[test]
1442    #[ignore = "writes the ADR-017 precondition fixture (contract-first)"]
1443    fn generate_precondition_fixture() {
1444        let base = fixture_text("envelope/envelope-minimal-signed.json");
1445        let mut value: serde_json::Value =
1446            serde_json::from_str(&base).expect("minimal fixture parses");
1447        let obj = value.as_object_mut().expect("object");
1448        let _ = obj.remove("signature");
1449        obj.insert(
1450            "precondition_findings".to_string(),
1451            serde_json::json!([
1452                {
1453                    "precondition_id": "beneficiary-eligible",
1454                    "step": "risky_step",
1455                    "outcome": "failed",
1456                    "exit_code": 3,
1457                    "inputs_hash": "5f2a9c1e7b4d5f6081a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708",
1458                    "checked_at": "2026-10-01T12:00:00Z",
1459                    "summary": "authority check denied dispatch (exit 3)",
1460                    "check_digest": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
1461                    "authority_digest": "sha256:2222222222222222222222222222222222222222222222222222222222222222",
1462                    "check_writable": false,
1463                    "attribution": "recorded"
1464                },
1465                {
1466                    "precondition_id": "account-open",
1467                    "step": "run_command",
1468                    "outcome": "passed",
1469                    "exit_code": 0,
1470                    "inputs_hash": "1c2b3a495867798a0b1c2d3e4f5061728394a5b6c7d8e9f0a1b2c3d4e5f60718",
1471                    "checked_at": "2026-10-01T12:00:01Z",
1472                    "summary": "authority stands",
1473                    "check_digest": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
1474                    "check_writable": true,
1475                    "attribution": "recorded"
1476                },
1477                {
1478                    "precondition_id": "network-eligible",
1479                    "step": "run_command",
1480                    "outcome": "error",
1481                    "exit_code": null,
1482                    "inputs_hash": "9e8d7c6b5a4938271605f4e3d2c1b0a99887766554433221100ffeeddccbbaa",
1483                    "checked_at": "2026-10-01T12:00:02Z",
1484                    "summary": "check refused before it ran",
1485                    "attribution": "refused_before_check"
1486                },
1487                {
1488                    "precondition_id": "payout-authority",
1489                    "step": "run_command",
1490                    "outcome": "failed",
1491                    "exit_code": 5,
1492                    "inputs_hash": "0a1b2c3d4e5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcdef",
1493                    "checked_at": "2026-10-01T12:00:03Z",
1494                    "summary": "authority check denied dispatch (exit 5)",
1495                    "check_digest": "sha256:1111111111111111111111111111111111111111111111111111111111111111",
1496                    "attribution": "artifact_unreadable"
1497                }
1498            ]),
1499        );
1500        let signature = sign(&value.to_string(), FIXTURE_KEY).expect("sign fixture");
1501        let mut envelope: AuditEnvelope =
1502            serde_json::from_value(value).expect("fixture parses into AuditEnvelope");
1503        envelope.signature = Some(signature);
1504        let json = serde_json::to_string_pretty(&envelope).expect("serialize fixture");
1505        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
1506            .join("../../schemas/fixtures/envelope/envelope-precondition-signed.json");
1507        std::fs::write(&path, format!("{json}\n")).expect("write fixture");
1508        eprintln!("wrote {}", path.display());
1509    }
1510
1511    /// SDK #47 / ADR-016: write a fixture envelope carrying the third
1512    /// `historyIntegrity` value `anchored_pending` (anchored mode configured,
1513    /// no verified head). Derived from the engine-signed `anchored` fixture by
1514    /// dropping the unverified `anchor_head` and re-signing with the fixed test
1515    /// key; the engine emits this value in the same shape
1516    /// (`envelope_factory_impl.rs`: `AnchoredPending => anchor_head: None`).
1517    /// Contract-first until the engine's conformance writer emits it directly.
1518    #[test]
1519    #[ignore = "writes the anchored_pending fixture (contract-first)"]
1520    fn generate_anchored_pending_fixture() {
1521        let base = fixture_text("envelope/envelope-anchored-signed.json");
1522        let mut value: serde_json::Value =
1523            serde_json::from_str(&base).expect("anchored fixture parses");
1524        let obj = value.as_object_mut().expect("object");
1525        let _ = obj.remove("signature");
1526        // `anchored_pending` pairs with `anchor_head: None` in the engine.
1527        let _ = obj.remove("anchor_head");
1528        obj.insert(
1529            "history_integrity".to_string(),
1530            serde_json::json!("anchored_pending"),
1531        );
1532        let signature = sign(&value.to_string(), FIXTURE_KEY).expect("sign fixture");
1533        let mut envelope: AuditEnvelope =
1534            serde_json::from_value(value).expect("fixture parses into AuditEnvelope");
1535        assert_eq!(
1536            envelope.history_integrity,
1537            Some(HistoryIntegrity::AnchoredPending)
1538        );
1539        assert!(envelope.anchor_head.is_none());
1540        envelope.signature = Some(signature);
1541        let json = serde_json::to_string_pretty(&envelope).expect("serialize fixture");
1542        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
1543            .join("../../schemas/fixtures/envelope/envelope-anchored-pending-signed.json");
1544        std::fs::write(&path, format!("{json}\n")).expect("write fixture");
1545        eprintln!("wrote {}", path.display());
1546    }
1547
1548    /// SDK #47: the `anchored_pending` fixture is schema-valid and HMAC-valid,
1549    /// and the label is not a weaker `anchored` (nothing was verified).
1550    #[test]
1551    fn anchored_pending_fixture_verifies() {
1552        let json = fixture_text("envelope/envelope-anchored-pending-signed.json");
1553        let envelope: AuditEnvelope = serde_json::from_str(&json).expect("fixture parses");
1554        assert_eq!(
1555            envelope.history_integrity,
1556            Some(HistoryIntegrity::AnchoredPending)
1557        );
1558        assert!(envelope.anchor_head.is_none(), "nothing was verified");
1559        assert_ne!(
1560            envelope.history_integrity,
1561            Some(HistoryIntegrity::Anchored),
1562            "anchored_pending must not be treated as authenticated"
1563        );
1564        verify_signature(&json, FIXTURE_KEY).expect("fixture verifies byte-exact");
1565        validate_schema(&json).expect("fixture conforms to envelope.json");
1566
1567        // The label is part of the signed canonical form.
1568        let tampered = json.replacen("anchored_pending", "anchored", 1);
1569        assert!(matches!(
1570            verify_signature(&tampered, FIXTURE_KEY),
1571            Err(VerifyError::SignatureMismatch { .. })
1572        ));
1573    }
1574
1575    /// SDK #39 / ADR-017: the contract-first `precondition_findings[]` fixture
1576    /// verifies byte-exact and is tamper-detected; legacy fixtures are unchanged.
1577    #[test]
1578    fn precondition_findings_fixture_verifies() {
1579        let json = fixture_text("envelope/envelope-precondition-signed.json");
1580        let envelope: AuditEnvelope = serde_json::from_str(&json).expect("fixture parses");
1581        assert_eq!(envelope.precondition_findings.len(), 4);
1582        assert_eq!(envelope.precondition_findings[0].outcome, "failed");
1583        assert_eq!(envelope.precondition_findings[0].exit_code, Some(3));
1584        assert_eq!(envelope.precondition_findings[1].outcome, "passed");
1585        assert_eq!(envelope.precondition_findings[1].exit_code, Some(0));
1586        assert_eq!(envelope.precondition_findings[2].outcome, "error");
1587        assert_eq!(envelope.precondition_findings[2].exit_code, None);
1588        assert_eq!(envelope.precondition_findings[3].outcome, "failed");
1589        assert_eq!(envelope.precondition_findings[3].exit_code, Some(5));
1590        // ADR-017 attribution (#987): digests + boundary fact are bound.
1591        assert_eq!(
1592            envelope.precondition_findings[0].check_digest.as_deref(),
1593            Some("sha256:1111111111111111111111111111111111111111111111111111111111111111")
1594        );
1595        assert_eq!(
1596            envelope.precondition_findings[0]
1597                .authority_digest
1598                .as_deref(),
1599            Some("sha256:2222222222222222222222222222222222222222222222222222222222222222")
1600        );
1601        assert_eq!(
1602            envelope.precondition_findings[0].check_writable,
1603            Some(false)
1604        );
1605        // ISSUE-ATTRIBUTION-ABSENCE-REASON: the four states are distinct.
1606        assert_eq!(
1607            envelope.precondition_findings[0].attribution.as_deref(),
1608            Some("recorded")
1609        );
1610        assert_eq!(
1611            envelope.precondition_findings[1].attribution.as_deref(),
1612            Some("recorded")
1613        );
1614        assert_eq!(
1615            envelope.precondition_findings[2].attribution.as_deref(),
1616            Some("refused_before_check")
1617        );
1618        assert_eq!(
1619            envelope.precondition_findings[3].attribution.as_deref(),
1620            Some("artifact_unreadable")
1621        );
1622        // A refusal omits the digests; the reason is the machine-readable cause.
1623        assert_eq!(envelope.precondition_findings[2].check_digest, None);
1624        assert_eq!(envelope.precondition_findings[2].authority_digest, None);
1625        // `artifact_unreadable` keeps the digest it could compute and omits the other.
1626        assert_eq!(
1627            envelope.precondition_findings[3].check_digest.as_deref(),
1628            Some("sha256:1111111111111111111111111111111111111111111111111111111111111111")
1629        );
1630        assert_eq!(envelope.precondition_findings[3].authority_digest, None);
1631
1632        verify_signature(&json, "fixture-hmac-key-2026").expect("byte-exact");
1633        validate_schema(&json).expect("schema conformance");
1634
1635        let tampered = json.replacen("\"exit_code\": 3", "\"exit_code\": 0", 1);
1636        assert!(matches!(
1637            verify_signature(&tampered, "fixture-hmac-key-2026"),
1638            Err(VerifyError::SignatureMismatch { .. })
1639        ));
1640
1641        // A forged authority changes `authority_digest` -> signature mismatch.
1642        let forged = json.replacen(
1643            "sha256:2222222222222222222222222222222222222222222222222222222222222222",
1644            "sha256:3333333333333333333333333333333333333333333333333333333333333333",
1645            1,
1646        );
1647        assert!(matches!(
1648            verify_signature(&forged, "fixture-hmac-key-2026"),
1649            Err(VerifyError::SignatureMismatch { .. })
1650        ));
1651
1652        let legacy = fixture_text("envelope/envelope-minimal-signed.json");
1653        assert!(!legacy.contains("precondition_findings"));
1654        verify_signature(&legacy, "fixture-hmac-key-2026").expect("legacy unchanged");
1655    }
1656
1657    // ─── Schema lint (SDK contract surface) ───────────────────────────────
1658    //
1659    // Every top-level contract schema must be a well-formed JSON Schema
1660    // (draft 2020-12) that compiles cleanly. This is the SDK's own guard that
1661    // the published contract surface never ships a broken schema.
1662    #[test]
1663    fn all_schemas_compile() {
1664        for name in [
1665            "envelope.json",
1666            "claims.json",
1667            "policy.json",
1668            "api/catalog.schema.json",
1669            "api/errors.json",
1670            "api/events.json",
1671            "api/ledger-receipt.json",
1672            "api/history-slice.json",
1673            "api/compaction-checkpoint.json",
1674            "api/authority-fact-bundle.json",
1675            "api/effect-record.json",
1676        ] {
1677            let text = schema_text(name).unwrap_or_else(|e| panic!("{name}: {e}"));
1678            let schema: serde_json::Value =
1679                serde_json::from_str(&text).unwrap_or_else(|e| panic!("{name}: {e}"));
1680            build_validator(name, &schema)
1681                .unwrap_or_else(|e| panic!("{name}: not a valid schema: {e}"));
1682        }
1683    }
1684
1685    // ─── SSE push events (ADR-0002 / SDK-C1) ────────────────────────────
1686    //
1687    // The committed event fixtures must validate against `api/events.json`
1688    // (which `$ref`s the envelope event-ref shape — no second dialect), and
1689    // the engine→SSE mapping table must stay complete: every engine
1690    // `ExecutionEvent` variant is either assigned to one of the three frozen
1691    // SSE names or explicitly marked not-pushed (`null`). SDK-C1 acceptance
1692    // criteria 2 and 4.
1693    #[test]
1694    fn events_fixtures_validate() {
1695        let mut found = 0;
1696        for name in fixture_json_names("events") {
1697            let json = fixture_text(&format!("events/{name}"));
1698            validate_schema_file("api/events.json", &json)
1699                .unwrap_or_else(|e| panic!("{name}: {e}"));
1700            found += 1;
1701        }
1702        assert!(
1703            found >= 3,
1704            "expected ≥3 committed SSE event fixtures, found {found}"
1705        );
1706    }
1707
1708    #[test]
1709    fn events_mapping_complete() {
1710        let text = schema_text("api/events.json").expect("events schema");
1711        let events: serde_json::Value = serde_json::from_str(&text).expect("events parses");
1712
1713        // 24 `ExecutionEvent` variants live in
1714        // `engine/src/event_system/domain/event.rs::event_type_name()`.
1715        let mapping = events["x-engine-event-mapping"]
1716            .as_object()
1717            .expect("x-engine-event-mapping object");
1718        assert_eq!(
1719            mapping.len(),
1720            24,
1721            "engine→SSE mapping must cover all 24 engine event variants"
1722        );
1723
1724        let frozen = ["approval_required", "run_progress", "policy_changed"];
1725        for (event_type, target) in mapping {
1726            match target.as_str() {
1727                Some(name) => assert!(
1728                    frozen.contains(&name),
1729                    "{event_type} maps to unknown SSE event {name}"
1730                ),
1731                None => assert!(target.is_null(), "{event_type}: bad mapping value"),
1732            }
1733        }
1734        for name in frozen {
1735            assert!(
1736                mapping.values().any(|v| v.as_str() == Some(name)),
1737                "SSE event {name} has no engine event assigned"
1738            );
1739        }
1740
1741        // The `oneOf` discriminant consts must equal the frozen event-name set.
1742        let mut consts: Vec<String> = Vec::new();
1743        for variant in events["oneOf"].as_array().expect("events oneOf") {
1744            let key = variant["$ref"]
1745                .as_str()
1746                .expect("variant $ref")
1747                .rsplit('/')
1748                .next()
1749                .expect("$defs key");
1750            for part in events["$defs"][key]["allOf"].as_array().expect("allOf") {
1751                if let Some(c) = part["properties"]["event"]["const"].as_str() {
1752                    consts.push(c.to_string());
1753                }
1754            }
1755        }
1756        consts.sort();
1757        let mut expected: Vec<String> = frozen.iter().map(|s| s.to_string()).collect();
1758        expected.sort();
1759        assert_eq!(consts, expected, "oneOf discriminant set drifted");
1760    }
1761
1762    // ─── Native API catalog integrity (ADR-0001) ──────────────────────────
1763    //
1764    // The frozen catalog is a contract consumers build against. Guard its
1765    // internal consistency: unique method names, known auth/kind/stability,
1766    // semver `since`, and every params/result `$ref` resolving into `$defs`.
1767    /// The catalog inlines no identity shapes: `identityRef` / `identityClaim`
1768    /// live in `claims.json` and are referenced cross-file, so there is exactly
1769    /// one copy of each (no silent drift). Compiling the catalog proves both
1770    /// `$id`-addressed refs resolve offline.
1771    #[test]
1772    fn catalog_references_claims_shapes_instead_of_duplicating_them() {
1773        let text = schema_text("api/catalog.json").expect("catalog.json");
1774        let catalog: serde_json::Value = serde_json::from_str(&text).expect("catalog parses");
1775
1776        let defs = catalog["$defs"].as_object().expect("$defs object");
1777        assert!(
1778            !defs.contains_key("identityRef"),
1779            "identityRef must not be duplicated in catalog.json — it lives in claims.json"
1780        );
1781        assert!(
1782            !defs.contains_key("identityClaim"),
1783            "identityClaim must not be duplicated in catalog.json — it lives in claims.json"
1784        );
1785
1786        assert_eq!(
1787            catalog["$defs"]["validatePlanParams"]["properties"]["identity"]["$ref"],
1788            "https://rigorix.eu/schemas/claims.json#/$defs/identityRef"
1789        );
1790        assert_eq!(
1791            catalog["$defs"]["authVerifyResult"]["properties"]["claim"]["$ref"],
1792            "https://rigorix.eu/schemas/claims.json#/$defs/identityClaim"
1793        );
1794
1795        // Unresolvable cross-file refs fail compilation — so this proves
1796        // claims.json is registered and both refs resolve offline.
1797        build_validator("api/catalog.json", &catalog)
1798            .expect("catalog compiles with claims.json registered");
1799    }
1800
1801    #[test]
1802    fn catalog_integrity() {
1803        let text = schema_text("api/catalog.json").expect("catalog.json");
1804        let catalog: serde_json::Value = serde_json::from_str(&text).expect("catalog parses");
1805
1806        // The catalog is DATA — validate it against its own schema document.
1807        let catalog_schema_text =
1808            schema_text("api/catalog.schema.json").expect("catalog.schema.json");
1809        let schema: serde_json::Value =
1810            serde_json::from_str(&catalog_schema_text).expect("schema parses");
1811        let compiled = jsonschema::validator_for(&schema).expect("catalog schema compiles");
1812        let errors: Vec<String> = compiled
1813            .iter_errors(&catalog)
1814            .map(|e| e.to_string())
1815            .collect();
1816        assert!(errors.is_empty(), "catalog violates its schema: {errors:?}");
1817
1818        let api_version = catalog["apiVersion"].as_str().expect("apiVersion");
1819        assert!(
1820            semver_ok(api_version),
1821            "apiVersion must be semver, got {api_version}"
1822        );
1823        assert_eq!(catalog["jsonrpc"], "2.0");
1824
1825        let defs = catalog["$defs"].as_object().expect("$defs object");
1826        let methods = catalog["methods"].as_array().expect("methods array");
1827        assert!(
1828            methods.len() >= 23,
1829            "catalog should list the frozen surface (>= 23 methods)"
1830        );
1831
1832        let mut seen = std::collections::HashSet::new();
1833        for m in methods {
1834            let name = m["name"].as_str().expect("method name");
1835            assert!(name.starts_with("rigorix."), "bad namespace: {name}");
1836            assert!(seen.insert(name.to_string()), "duplicate method: {name}");
1837
1838            assert!(
1839                matches!(m["kind"].as_str(), Some("query" | "command")),
1840                "{name}: bad kind"
1841            );
1842            assert!(
1843                matches!(m["auth"].as_str(), Some("public" | "session" | "admin")),
1844                "{name}: bad auth level"
1845            );
1846            assert!(
1847                matches!(
1848                    m["stability"].as_str(),
1849                    Some("frozen" | "draft" | "deprecated")
1850                ),
1851                "{name}: bad stability"
1852            );
1853            let since = m["since"].as_str().expect("since");
1854            assert!(semver_ok(since), "{name}: since not semver: {since}");
1855
1856            for slot in ["params", "result"] {
1857                let reference = m[slot]["$ref"]
1858                    .as_str()
1859                    .unwrap_or_else(|| panic!("{name}: missing {slot}.$ref"));
1860                let key = reference.rsplit('/').next().unwrap_or_default();
1861                assert!(
1862                    defs.contains_key(key),
1863                    "{name}: {slot} $ref '{reference}' does not resolve in $defs"
1864                );
1865            }
1866        }
1867
1868        // The push channel must reference the frozen events schema, and the
1869        // advertised event-name set must match that schema's discriminants
1870        // (ADR-0002 / SDK-C1).
1871        let push = &catalog["transport"]["push"];
1872        assert_eq!(push["kind"], "sse", "push kind");
1873        assert_eq!(push["endpoint"], "/events", "push endpoint");
1874        let push_schema = push["schema"].as_str().expect("transport.push.schema");
1875        let push_text = schema_text(push_schema).expect("push schema");
1876        let push_events: serde_json::Value =
1877            serde_json::from_str(&push_text).expect("events schema parses");
1878        build_validator(push_schema, &push_events).unwrap_or_else(|e| panic!("{push_schema}: {e}"));
1879        let mut declared: Vec<&str> = push["events"]
1880            .as_array()
1881            .expect("push.events")
1882            .iter()
1883            .map(|v| v.as_str().expect("event name"))
1884            .collect();
1885        declared.sort_unstable();
1886        let mut known: Vec<&str> = Vec::new();
1887        for variant in push_events["oneOf"].as_array().expect("events oneOf") {
1888            let key = variant["$ref"]
1889                .as_str()
1890                .expect("variant $ref")
1891                .rsplit('/')
1892                .next()
1893                .expect("$defs key");
1894            for part in push_events["$defs"][key]["allOf"]
1895                .as_array()
1896                .expect("allOf")
1897            {
1898                if let Some(c) = part["properties"]["event"]["const"].as_str() {
1899                    known.push(c);
1900                }
1901            }
1902        }
1903        known.sort_unstable();
1904        assert_eq!(
1905            declared, known,
1906            "catalog transport.push.events must match events.json discriminants"
1907        );
1908
1909        // SDK-C5 / ADR-0001 D3: the closed-namespace rule is documented and the
1910        // previously-undeclared `rigorix.auth.verify` is now declared.
1911        assert!(
1912            catalog["description"]
1913                .as_str()
1914                .is_some_and(|d| d.contains("CLOSED")),
1915            "catalog.json must document the closed `rigorix.*` namespace"
1916        );
1917        let auth_verify = methods
1918            .iter()
1919            .find(|m| m["name"] == "rigorix.auth.verify")
1920            .expect("rigorix.auth.verify must be declared in the frozen catalog");
1921        assert_eq!(auth_verify["kind"], "query");
1922        assert_eq!(auth_verify["auth"], "session");
1923        assert!(
1924            auth_verify["mcpTool"].is_null(),
1925            "auth.verify is server-only"
1926        );
1927        for slot in ["params", "result"] {
1928            let reference = auth_verify[slot]["$ref"]
1929                .as_str()
1930                .unwrap_or_else(|| panic!("auth.verify: missing {slot}.$ref"));
1931            let key = reference.rsplit('/').next().unwrap_or_default();
1932            assert!(
1933                defs.contains_key(key),
1934                "auth.verify {slot} $ref '{reference}' does not resolve in $defs"
1935            );
1936        }
1937
1938        // SDK-CATALOG-AUDIT / ADR-016 Phase B: the three ledger methods the
1939        // enterprise registers must be declared (query / session / no MCP tool).
1940        for name in [
1941            "rigorix.audit.head",
1942            "rigorix.audit.history",
1943            "rigorix.audit.overdue",
1944        ] {
1945            let method = methods
1946                .iter()
1947                .find(|m| m["name"] == name)
1948                .unwrap_or_else(|| panic!("{name} must be declared in the frozen catalog"));
1949            assert_eq!(method["kind"], "query", "{name}: kind");
1950            assert_eq!(method["auth"], "session", "{name}: auth");
1951            assert!(method["mcpTool"].is_null(), "{name} is server-only");
1952            for slot in ["params", "result"] {
1953                let reference = method[slot]["$ref"]
1954                    .as_str()
1955                    .unwrap_or_else(|| panic!("{name}: missing {slot}.$ref"));
1956                let key = reference.rsplit('/').next().unwrap_or_default();
1957                assert!(
1958                    defs.contains_key(key),
1959                    "{name}: {slot} $ref '{reference}' does not resolve in $defs"
1960                );
1961            }
1962        }
1963        // `audit.history` reuses the frozen history-slice shape by `$id`.
1964        assert_eq!(
1965            defs["auditHistoryResult"]["$ref"], HISTORY_SLICE_SCHEMA_ID,
1966            "rigorix.audit.history must reuse api/history-slice.json"
1967        );
1968    }
1969
1970    // The error taxonomy and its code mapping must stay in sync: every
1971    // `data.type` has a code and vice versa (ADR-0001 D6).
1972    #[test]
1973    fn error_taxonomy_codes_consistent() {
1974        let text = schema_text("api/errors.json").expect("errors.json");
1975        let errors: serde_json::Value = serde_json::from_str(&text).expect("errors parses");
1976
1977        let types: Vec<&str> = errors["$defs"]["errorType"]["enum"]
1978            .as_array()
1979            .expect("errorType enum")
1980            .iter()
1981            .map(|v| v.as_str().expect("string"))
1982            .collect();
1983        let codes = errors["x-error-codes"].as_object().expect("x-error-codes");
1984
1985        for t in &types {
1986            assert!(codes.contains_key(*t), "error type '{t}' has no code");
1987        }
1988        for key in codes.keys() {
1989            assert!(
1990                types.contains(&key.as_str()),
1991                "code mapping '{key}' is not a declared error type"
1992            );
1993        }
1994    }
1995
1996    // ─── ADR-016 audit integrity (SDK-AUDIT-A / #12) ─────────────────────
1997    //
1998    // The chained fixtures are produced by the REAL rigorix-oss engine
1999    // (ADR-016 Phase A, #902) with the fixed fixture key. The anchor artifacts
2000    // (receipt / slice / checkpoint) have no anchor implementation yet — they
2001    // are contract fixtures signed with a deterministic TEST-ONLY Ed25519 key
2002    // (see `generate_anchor_fixtures`).
2003    const FIXTURE_KEY: &str = "fixture-hmac-key-2026";
2004    /// Deterministic TEST-ONLY Ed25519 seed (never a production key).
2005    const ANCHOR_SECRET: [u8; 32] = [7u8; 32];
2006
2007    fn anchor_signing_key() -> ed25519_dalek::SigningKey {
2008        ed25519_dalek::SigningKey::from_bytes(&ANCHOR_SECRET)
2009    }
2010
2011    fn anchor_public_hex() -> String {
2012        hex::encode(anchor_signing_key().verifying_key().to_bytes())
2013    }
2014
2015    /// Where the ignored `generate_anchor_fixtures` writes (repo checkout only).
2016    fn integrity_dir() -> std::path::PathBuf {
2017        Path::new(env!("CARGO_MANIFEST_DIR")).join("../../schemas/fixtures/integrity")
2018    }
2019
2020    /// Read a fixture through the published resolution path (env -> embedded).
2021    fn read_envelopes(name: &str) -> Vec<AuditEnvelope> {
2022        let text = read_json(name);
2023        serde_json::from_str(&text).unwrap_or_else(|e| panic!("{name}: {e}"))
2024    }
2025
2026    fn read_json(name: &str) -> String {
2027        fixture_text(&format!("integrity/{name}"))
2028    }
2029
2030    /// The standalone guarantee (SDK-VERIFIER-PUBLISH): with no
2031    /// `RIGORIX_SDK_SCHEMAS`, every contract entry point resolves from the
2032    /// embedded `rigorix-schemas` corpus — signature, catalog subset, chain.
2033    #[test]
2034    fn embedded_corpus_smoke() {
2035        let json = fixture_text("envelope/envelope-minimal-signed.json");
2036        verify_signature(&json, FIXTURE_KEY).expect("embedded engine fixture verifies");
2037        verify_catalog_subset(&["rigorix.plan", "rigorix.auth.verify"])
2038            .expect("embedded catalog contains the declared subset");
2039        let chain = read_envelopes("chain.json");
2040        verify_chain(&chain).expect("embedded chain verifies");
2041    }
2042
2043    #[test]
2044    fn integrity_chain_fixtures_verify() {
2045        let envelopes = read_envelopes("chain.json");
2046        assert!(envelopes.len() >= 3, "expected a >=3-envelope chain");
2047
2048        // Each engine-signed envelope verifies byte-exact (HMAC) + conforms to
2049        // envelope.json (which now carries the ADR-016 chain fields).
2050        let values: Vec<serde_json::Value> =
2051            serde_json::from_str(&read_json("chain.json")).expect("chain array parses");
2052        for value in &values {
2053            let one = value.to_string();
2054            verify_signature(&one, FIXTURE_KEY).unwrap_or_else(|e| panic!("fixture hmac: {e}"));
2055            validate_schema(&one).unwrap_or_else(|e| panic!("envelope schema: {e}"));
2056        }
2057
2058        // Chain continuity: genesis 0, contiguous, prev_hash links.
2059        verify_chain(&envelopes).expect("valid chain must verify");
2060        assert!(envelopes
2061            .iter()
2062            .all(|e| e.history_integrity == Some(HistoryIntegrity::LocalUnanchored)));
2063        for pair in envelopes.windows(2) {
2064            assert_eq!(
2065                Some(envelope_hash_of(&pair[0]).unwrap()),
2066                pair[1].prev_hash,
2067                "prev_hash must be the predecessor's canonical hash"
2068            );
2069        }
2070        assert_eq!(envelopes[0].sequence, Some(0));
2071        assert!(envelopes[0].prev_hash.is_none(), "genesis has no prev_hash");
2072    }
2073
2074    #[test]
2075    fn integrity_broken_chain_is_rejected() {
2076        let envelopes = read_envelopes("broken-chain.json");
2077        let err = verify_chain(&envelopes).expect_err("an uncovered gap must fail");
2078        assert!(matches!(err, VerifyError::ChainBroken { .. }), "{err:?}");
2079    }
2080
2081    #[test]
2082    fn chain_detects_altered_predecessor_and_duplicate_sequence() {
2083        // An altered predecessor link (prev_hash no longer matches the hash).
2084        let mut envelopes = read_envelopes("chain.json");
2085        envelopes[2].prev_hash = Some("0".repeat(64));
2086        let err = verify_chain(&envelopes).expect_err("altered prev_hash must fail");
2087        assert!(matches!(err, VerifyError::ChainBroken { .. }), "{err:?}");
2088
2089        // A duplicated sequence number (insertion).
2090        let mut envelopes = read_envelopes("chain.json");
2091        envelopes[2].sequence = Some(1);
2092        let err = verify_chain(&envelopes).expect_err("duplicate sequence must fail");
2093        assert!(matches!(err, VerifyError::ChainBroken { .. }), "{err:?}");
2094    }
2095
2096    #[test]
2097    fn checkpoint_covers_broken_chain_gap() {
2098        let envelopes = read_envelopes("broken-chain.json");
2099        let text = read_json("compaction-checkpoint.json");
2100        let checkpoint: CompactionCheckpoint = serde_json::from_str(&text).expect("checkpoint");
2101
2102        // Strict verification fails; the signed checkpoint covers the gap.
2103        assert!(verify_chain(&envelopes).is_err());
2104        verify_chain_with_checkpoints(
2105            &envelopes,
2106            std::slice::from_ref(&checkpoint),
2107            &anchor_public_hex(),
2108        )
2109        .expect("a checkpoint-covered gap must verify");
2110        validate_schema_file("api/compaction-checkpoint.json", &text).expect("checkpoint schema");
2111
2112        // A forged checkpoint (wrong new_head, re-signed with a different key)
2113        // neither verifies nor covers the gap.
2114        let mut forged = checkpoint.clone();
2115        forged.new_head = "0".repeat(64);
2116        assert!(verify_chain_with_checkpoints(
2117            &envelopes,
2118            std::slice::from_ref(&forged),
2119            &anchor_public_hex()
2120        )
2121        .is_err());
2122    }
2123
2124    #[test]
2125    fn history_slice_fixture_verifies() {
2126        let text = read_json("history-slice.json");
2127        let slice: HistorySlice = serde_json::from_str(&text).expect("slice parses");
2128        verify_history_slice(&slice, &anchor_public_hex()).expect("anchor signature");
2129        validate_schema_file("api/history-slice.json", &text).expect("history-slice schema");
2130        assert!(!slice.actions.is_empty(), "slice carries prior actions");
2131
2132        // A forged slice (tampered action) is rejected.
2133        let mut forged = slice.clone();
2134        forged.actions[0].node = "forged_node".to_string();
2135        assert!(verify_history_slice(&forged, &anchor_public_hex()).is_err());
2136    }
2137
2138    #[test]
2139    fn ledger_receipt_fixture_verifies() {
2140        let text = read_json("ledger-receipt.json");
2141        let receipt: LedgerReceipt = serde_json::from_str(&text).expect("receipt parses");
2142        verify_ledger_receipt(&receipt, &anchor_public_hex()).expect("anchor signature");
2143        validate_schema_file("api/ledger-receipt.json", &text).expect("ledger-receipt schema");
2144
2145        let mut forged = receipt.clone();
2146        forged.envelope_hash = "0".repeat(64);
2147        assert!(verify_ledger_receipt(&forged, &anchor_public_hex()).is_err());
2148    }
2149
2150    // ─── Effect commitment artifact (ADR-019 / SDK 0.7.0) ────────────────
2151    //
2152    // Contract-first fixtures: the engine does not emit this artifact yet, so
2153    // the read-back bodies are fixed inputs and the digests are recomputed by
2154    // `verify_settlement_evidence` exactly as the engine computes them.
2155
2156    fn read_effect(name: &str) -> (String, EffectRecordArtifact) {
2157        let text = fixture_text(&format!("effect/{name}"));
2158        let artifact: EffectRecordArtifact =
2159            serde_json::from_str(&text).unwrap_or_else(|e| panic!("{name}: {e}"));
2160        (text, artifact)
2161    }
2162
2163    /// The accepted fixture set is pinned exactly: deleting a fixture or adding
2164    /// an unverified one fails. A lower-bound count (`>= 5`) would let the loop
2165    /// silently shrink, which is the same defect as an unpinned rejection.
2166    const ACCEPTED_EFFECT_FIXTURES: &[&str] = &[
2167        "ambiguous-unsettled.json",
2168        "committed-l1-l3.json",
2169        "dispatched-with-deadline.json",
2170        "not-committed-l2-l3.json",
2171        "resolved-ambiguous.json",
2172    ];
2173
2174    /// Where a rejected fixture must be stopped. `Schema` cases are also
2175    /// asserted to fail the structural verifier, so the independent re-check is
2176    /// exercised even when the schema catches the violation first.
2177    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2178    enum RejectionLayer {
2179        Schema,
2180        Structural,
2181        ReadbackDigestMismatch,
2182        ReadbackMissing,
2183    }
2184
2185    /// Every rejected fixture, and the layer that must reject it. This table and
2186    /// the `rejected-*.json` files must be equal as sets: a fixture without a
2187    /// case is inert coverage, and a case without a fixture is a stale claim.
2188    const REJECTED_EFFECT_FIXTURES: &[(&str, RejectionLayer)] = &[
2189        (
2190            "rejected-terminal-without-evidence.json",
2191            RejectionLayer::Schema,
2192        ),
2193        (
2194            "rejected-nonterminal-with-settlement.json",
2195            RejectionLayer::Schema,
2196        ),
2197        (
2198            "rejected-dispatched-without-deadline.json",
2199            RejectionLayer::Schema,
2200        ),
2201        ("rejected-verdict-mismatch.json", RejectionLayer::Schema),
2202        (
2203            "rejected-readback-mismatch.json",
2204            RejectionLayer::ReadbackDigestMismatch,
2205        ),
2206        (
2207            "rejected-readback-missing.json",
2208            RejectionLayer::ReadbackMissing,
2209        ),
2210        (
2211            "rejected-settlement-with-none-level.json",
2212            RejectionLayer::Structural,
2213        ),
2214    ];
2215
2216    fn accepted_fixture_names() -> Vec<String> {
2217        fixture_json_names("effect")
2218            .into_iter()
2219            .filter(|name| !name.starts_with("rejected-"))
2220            .collect()
2221    }
2222
2223    fn rejected_fixture_names() -> Vec<String> {
2224        fixture_json_names("effect")
2225            .into_iter()
2226            .filter(|name| name.starts_with("rejected-"))
2227            .collect()
2228    }
2229
2230    fn sorted(mut names: Vec<String>) -> Vec<String> {
2231        names.sort();
2232        names
2233    }
2234
2235    /// Every accepted fixture is pinned, validates against the frozen schema,
2236    /// and passes both verification levels (readback only when bytes are present).
2237    #[test]
2238    fn effect_record_fixtures_verify() {
2239        let on_disk = sorted(accepted_fixture_names());
2240        let pinned: Vec<String> = ACCEPTED_EFFECT_FIXTURES
2241            .iter()
2242            .map(|name| (*name).to_string())
2243            .collect();
2244        assert_eq!(
2245            on_disk,
2246            sorted(pinned),
2247            "every accepted fixture must be pinned and every pinned fixture must exist"
2248        );
2249
2250        for name in ACCEPTED_EFFECT_FIXTURES {
2251            let (text, artifact) = read_effect(name);
2252            validate_schema_file("api/effect-record.json", &text)
2253                .unwrap_or_else(|e| panic!("{name}: schema: {e}"));
2254            verify_effect_record(&artifact).unwrap_or_else(|e| panic!("{name}: structural: {e}"));
2255            if artifact
2256                .settlement
2257                .as_ref()
2258                .is_some_and(|s| s.readback.is_some())
2259            {
2260                verify_settlement_evidence(&artifact)
2261                    .unwrap_or_else(|e| panic!("{name}: readback: {e}"));
2262            }
2263        }
2264    }
2265
2266    /// The two axes are independent: `l1` durability + `l3` settlement is legal
2267    /// and must round-trip. This is the #1182 regression in schema form.
2268    #[test]
2269    fn effect_record_keeps_durability_and_settlement_orthogonal() {
2270        let (_, artifact) = read_effect("committed-l1-l3.json");
2271        assert_eq!(artifact.levels.durability, Durability::L1);
2272        assert_eq!(artifact.levels.settlement, SettlementLevel::L3);
2273        verify_settlement_evidence(&artifact).expect("valid l1 + l3 artifact");
2274    }
2275
2276    /// Every rejected fixture is pinned to a case, and every case rejects at the
2277    /// layer it claims. Adding `rejected-zzz-probe.json` without a case fails
2278    /// the set equality below; adding a case without a fixture fails too.
2279    #[test]
2280    fn effect_record_rejected_fixtures_are_pinned_and_rejected() {
2281        let on_disk = sorted(rejected_fixture_names());
2282        let pinned: Vec<String> = REJECTED_EFFECT_FIXTURES
2283            .iter()
2284            .map(|(name, _)| (*name).to_string())
2285            .collect();
2286        assert_eq!(
2287            on_disk,
2288            sorted(pinned),
2289            "every rejected fixture must have a case and every case must have a fixture"
2290        );
2291
2292        for (name, layer) in REJECTED_EFFECT_FIXTURES {
2293            let (text, artifact) = read_effect(name);
2294
2295            let schema = validate_schema_file("api/effect-record.json", &text);
2296            let structural = verify_effect_record(&artifact);
2297
2298            match layer {
2299                RejectionLayer::Schema => {
2300                    assert!(schema.is_err(), "{name}: schema must reject");
2301                    let err = structural.expect_err("structural must also reject");
2302                    assert!(
2303                        matches!(err, VerifyError::EffectInvariant { .. }),
2304                        "{name}: {err:?}"
2305                    );
2306                }
2307                RejectionLayer::Structural => {
2308                    schema.unwrap_or_else(|e| panic!("{name}: schema should accept: {e}"));
2309                    let err = structural.expect_err("structural must reject");
2310                    assert!(
2311                        matches!(err, VerifyError::EffectInvariant { .. }),
2312                        "{name}: {err:?}"
2313                    );
2314                }
2315                RejectionLayer::ReadbackDigestMismatch => {
2316                    schema.unwrap_or_else(|e| panic!("{name}: schema should accept: {e}"));
2317                    structural.unwrap_or_else(|e| panic!("{name}: structural should accept: {e}"));
2318                    let err = verify_settlement_evidence(&artifact)
2319                        .expect_err("readback digest must not match");
2320                    assert!(
2321                        matches!(err, VerifyError::ReadbackDigestMismatch { .. }),
2322                        "{name}: {err:?}"
2323                    );
2324                }
2325                RejectionLayer::ReadbackMissing => {
2326                    schema.unwrap_or_else(|e| panic!("{name}: schema should accept: {e}"));
2327                    structural.unwrap_or_else(|e| panic!("{name}: structural should accept: {e}"));
2328                    let err = verify_settlement_evidence(&artifact)
2329                        .expect_err("readback bytes must be required");
2330                    assert!(
2331                        matches!(err, VerifyError::ReadbackMissing),
2332                        "{name}: {err:?}"
2333                    );
2334                }
2335            }
2336        }
2337    }
2338
2339    /// Regenerates the three anchor-artifact fixtures. The envelope chain
2340    /// fixtures are engine-produced and must NOT be regenerated here.
2341    #[test]
2342    #[ignore = "fixture generator — run with --ignored to regenerate anchor fixtures"]
2343    fn generate_anchor_fixtures() {
2344        use ed25519_dalek::Signer;
2345
2346        let key = anchor_signing_key();
2347        let dir = integrity_dir();
2348        let chain = read_envelopes("chain.json");
2349        let head = chain.last().expect("chain non-empty");
2350
2351        // History slice over the chain's actions.
2352        let mut slice = HistorySlice {
2353            scope: "local".to_string(),
2354            since: chain[0].timestamp,
2355            actions: chain
2356                .iter()
2357                .flat_map(|envelope| {
2358                    envelope.events.iter().filter_map(|event| {
2359                        let node = event
2360                            .payload
2361                            .as_ref()?
2362                            .get("step_name")?
2363                            .as_str()?
2364                            .to_string();
2365                        Some(HistoryActionRef {
2366                            node,
2367                            principal: envelope.author.clone(),
2368                            at: event.occurred_at,
2369                            effect_key: envelope.effect_key.clone(),
2370                        })
2371                    })
2372                })
2373                .collect(),
2374            head_hash: envelope_hash_of(head).expect("head hash"),
2375            sig: None,
2376        };
2377        let bytes = history_slice_signing_bytes(&slice).expect("slice bytes");
2378        slice.sig = Some(hex::encode(key.sign(&bytes).to_bytes()));
2379        std::fs::write(
2380            dir.join("history-slice.json"),
2381            format!("{}\n", serde_json::to_string_pretty(&slice).unwrap()),
2382        )
2383        .expect("write history slice");
2384
2385        // Ledger receipt for the chain head.
2386        let mut receipt = LedgerReceipt {
2387            ledger_id: "local-ledger".to_string(),
2388            envelope_hash: envelope_hash_of(head).expect("head hash"),
2389            sequence: head.sequence.expect("head sequence"),
2390            recorded_at: head.timestamp,
2391            sig: None,
2392        };
2393        let bytes = ledger_receipt_signing_bytes(&receipt).expect("receipt bytes");
2394        receipt.sig = Some(hex::encode(key.sign(&bytes).to_bytes()));
2395        std::fs::write(
2396            dir.join("ledger-receipt.json"),
2397            format!("{}\n", serde_json::to_string_pretty(&receipt).unwrap()),
2398        )
2399        .expect("write ledger receipt");
2400
2401        // Compaction checkpoint covering the broken-chain gap (seq 1..=1).
2402        let broken = read_envelopes("broken-chain.json");
2403        let after = &broken[1];
2404        let mut checkpoint = CompactionCheckpoint {
2405            sequence_from: 1,
2406            sequence_to: 1,
2407            reason: "gdpr-erasure".to_string(),
2408            prior_head: envelope_hash_of(&broken[0]).expect("prior hash"),
2409            new_head: after.prev_hash.clone().expect("successor link"),
2410            sig: None,
2411        };
2412        let bytes = compaction_checkpoint_signing_bytes(&checkpoint).expect("checkpoint bytes");
2413        checkpoint.sig = Some(hex::encode(key.sign(&bytes).to_bytes()));
2414        std::fs::write(
2415            dir.join("compaction-checkpoint.json"),
2416            format!("{}\n", serde_json::to_string_pretty(&checkpoint).unwrap()),
2417        )
2418        .expect("write compaction checkpoint");
2419    }
2420
2421    // ─── Catalog parity / closed namespace (ADR-0001 D3; SDK-C5 #15,
2422    //     SDK-CATALOG-AUDIT #20) ────────────────────────────────────────
2423    //
2424    // Every method a server registers must be declared in the frozen catalog;
2425    // a server implements a SUBSET, never an extension. The enterprise
2426    // Execution API's 13-method set is the canonical positive case.
2427    #[test]
2428    fn catalog_subset_guard_rejects_undeclared_method() {
2429        let enterprise = [
2430            "rigorix.plan",
2431            "rigorix.validatePlan",
2432            "rigorix.run",
2433            "rigorix.approve",
2434            "rigorix.auth.verify",
2435            "rigorix.policy.bundle",
2436            "rigorix.audit.read",
2437            "rigorix.audit.list",
2438            "rigorix.audit.summary",
2439            "rigorix.audit.head",
2440            "rigorix.audit.history",
2441            "rigorix.audit.overdue",
2442            "rigorix.system.version",
2443        ];
2444        verify_catalog_subset(&enterprise).expect("a declared subset must pass");
2445
2446        let err = verify_catalog_subset(&["rigorix.auth.bogus"]).unwrap_err();
2447        assert!(
2448            matches!(err, VerifyError::UndeclaredMethod(ref m) if m == "rigorix.auth.bogus"),
2449            "{err:?}"
2450        );
2451    }
2452
2453    // The consequence-gating §4.3 catalog addition (SDK #44): the method is
2454    // declared with the frozen shape, its result is the STANDALONE bundle file
2455    // (not an inline shape), and that bundle `$ref`s the one canonical envelope
2456    // dialect — no second envelope shape. Additive within the closed namespace.
2457    #[test]
2458    fn catalog_declares_authority_fact_projection_additively() {
2459        let text = schema_text("api/catalog.json").expect("catalog.json");
2460        let catalog: serde_json::Value = serde_json::from_str(&text).expect("catalog parses");
2461        let method = catalog["methods"]
2462            .as_array()
2463            .expect("methods")
2464            .iter()
2465            .find(|m| m["name"] == "rigorix.audit.authorityFacts")
2466            .expect("rigorix.audit.authorityFacts must be declared");
2467        assert_eq!(method["kind"], "query");
2468        assert_eq!(
2469            method["auth"], "session",
2470            "an OSS capability is a session method, not an enterprise (admin) scope"
2471        );
2472        assert_eq!(method["mcpTool"], "rigorix_audit_authority_facts");
2473        assert_eq!(method["params"]["$ref"], "#/$defs/authorityFactsParams");
2474        assert_eq!(method["result"]["$ref"], "#/$defs/authorityFactsResult");
2475
2476        // `authorityFactsResult` addresses the standalone bundle by `$id`; the
2477        // catalog's `$defs` hold method-local shapes, and canonical artifacts
2478        // are standalone files with an `$id` (as with `auditHistoryResult`).
2479        assert_eq!(
2480            catalog["$defs"]["authorityFactsResult"]["$ref"],
2481            AUTHORITY_FACT_BUNDLE_SCHEMA_ID
2482        );
2483
2484        // The bundle's `envelopes[]` is the ONE canonical envelope dialect.
2485        let bundle_text = schema_text("api/authority-fact-bundle.json").expect("bundle schema");
2486        let bundle: serde_json::Value = serde_json::from_str(&bundle_text).expect("bundle parses");
2487        assert_eq!(
2488            bundle["properties"]["envelopes"]["items"]["$ref"], ENVELOPE_SCHEMA_ID,
2489            "the bundle must $ref envelope.json (no second envelope dialect)"
2490        );
2491
2492        // The new name is a declared subset member (a server may serve it).
2493        verify_catalog_subset(&["rigorix.audit.authorityFacts"])
2494            .expect("the projection method must be a declared subset member");
2495    }
2496
2497    fn semver_ok(s: &str) -> bool {
2498        let parts: Vec<&str> = s.split('.').collect();
2499        parts.len() == 3 && parts.iter().all(|p| p.parse::<u64>().is_ok())
2500    }
2501
2502    /// #1222: `scope_check` is part of the envelope dialect. Unknown fields are
2503    /// dropped on re-serialization, so a verifier that lacks the field produces
2504    /// different canonical bytes and rejects a correctly signed envelope.
2505    #[test]
2506    fn scope_check_survives_canonicalization() {
2507        let raw = r#"{
2508            "execution_id": "8c1d5eac-8935-4960-82cf-199df61d2539",
2509            "timestamp": "2026-10-30T12:00:00Z",
2510            "template_id": "t",
2511            "planning_hash": "h",
2512            "total_tokens": 0,
2513            "duration_ms": 0,
2514            "events": [],
2515            "signature": null,
2516            "evidence_degraded": false,
2517            "scope_check": "checked"
2518        }"#;
2519        let envelope: AuditEnvelope = serde_json::from_str(raw).expect("parse");
2520        assert_eq!(envelope.scope_check, Some(ScopeCheckStatus::Checked));
2521        let canonical = String::from_utf8(canonical_bytes(raw).expect("canonical")).expect("utf8");
2522        assert!(
2523            canonical.contains(r#""scope_check":"checked""#),
2524            "the field must be in the signed bytes: {canonical}"
2525        );
2526    }
2527}