exochain-escalation 0.2.0-beta

EXOCHAIN constitutional trust fabric โ€” operational nervous system: detection, triage, kanban, HITL, Sybil adjudication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Challenge paths for Sybil adjudication โ€” CR-001 section 8.5.
//!
//! Any credible allegation of one of the four formal Sybil challenge grounds
//! is admitted through `admit_challenge`, which immediately places the
//! contested action in `ContestStatus::PauseEligible` and opens an audit
//! trail.  The caller then signals the CGR Kernel that the action is under
//! active challenge by setting `active_challenge_reason` on the
//! `AdjudicationContext`. The kernel can return `Verdict::Escalated` for
//! otherwise valid or reviewable authority/quorum cases, but final
//! constitutional denials still take precedence.

use exo_core::{Did, PublicKey, SecretKey, Signature, Timestamp, crypto};
use exo_identity::did::did_from_public_key;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::error::EscalationError;

// ---------------------------------------------------------------------------
// Challenge grounds (CR-001 ยง8.5)
// ---------------------------------------------------------------------------

/// The four formal Sybil challenge grounds recognised by EXOCHAIN.
///
/// Any credible allegation on any of these grounds is admissible and places
/// the contested action in a pause-eligible hold pending review.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SybilChallengeGround {
    /// One underlying actor or control plane appears as multiple independent
    /// approvers, reviewers, or DIDs.
    ConcealedCommonControl,
    /// Multiple actors behave in lockstep so as to inflate apparent consensus
    /// or quorum without genuine independent judgment.
    CoordinatedManipulation,
    /// The counted quorum is tainted by non-independent, coordinated, or
    /// synthetic participants.
    QuorumContamination,
    /// A synthetic (AI-generated) opinion or entity is presented as if it
    /// were an independent human participant.
    SyntheticHumanMisrepresentation,
}

impl std::fmt::Display for SybilChallengeGround {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ConcealedCommonControl => write!(f, "ConcealedCommonControl"),
            Self::CoordinatedManipulation => write!(f, "CoordinatedManipulation"),
            Self::QuorumContamination => write!(f, "QuorumContamination"),
            Self::SyntheticHumanMisrepresentation => write!(f, "SyntheticHumanMisrepresentation"),
        }
    }
}

// ---------------------------------------------------------------------------
// Contest status
// ---------------------------------------------------------------------------

/// Lifecycle status of a contested action.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ContestStatus {
    /// Challenge admitted; action is paused pending review.  Callers MUST
    /// propagate this into `AdjudicationContext::active_challenge_reason` so
    /// the CGR Kernel can return `Verdict::Escalated` when no final
    /// constitutional denial is present.
    PauseEligible,
    /// Evidentiary review is in progress.
    UnderReview,
    /// Challenge resolved: the contested action may proceed (or was reversed).
    Resolved,
    /// Challenge dismissed: insufficient grounds; action is unblocked.
    Dismissed,
}

impl ContestStatus {
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::PauseEligible => "PauseEligible",
            Self::UnderReview => "UnderReview",
            Self::Resolved => "Resolved",
            Self::Dismissed => "Dismissed",
        }
    }
}

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

// ---------------------------------------------------------------------------
// Challenge admission provenance
// ---------------------------------------------------------------------------

/// Canonical domain for Ed25519 signatures admitting Sybil challenges.
pub const CHALLENGE_ADMISSION_DOMAIN: &str = "exo.escalation.challenge.admission.v1";

/// The signable, deterministic challenge-admission payload.
///
/// A caller supplies every piece of identity, timing, and authority context.
/// This module only verifies the signed payload and materializes the hold.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChallengeAdmission {
    pub hold_id: Uuid,
    pub action_id: [u8; 32],
    pub ground: SybilChallengeGround,
    pub admitted_at: Timestamp,
    pub admitted_by: Did,
    pub admitter_public_key: PublicKey,
    pub evidence_hash: [u8; 32],
    pub authority_chain_hash: [u8; 32],
}

/// A challenge admission plus the admitting actor's Ed25519 signature.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SignedChallengeAdmission {
    pub admission: ChallengeAdmission,
    pub admission_signature: Signature,
}

// ---------------------------------------------------------------------------
// ContestHold
// ---------------------------------------------------------------------------

/// A hold placed on a contested action upon challenge admission.
///
/// Every state transition appends an entry to `audit_log`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContestHold {
    pub id: Uuid,
    /// Identifies the action under challenge (matches kernel `action_id`).
    pub action_id: [u8; 32],
    pub ground: SybilChallengeGround,
    pub status: ContestStatus,
    pub admitted_at: Timestamp,
    pub admitted_by: Did,
    pub admitter_public_key: PublicKey,
    pub evidence_hash: [u8; 32],
    pub authority_chain_hash: [u8; 32],
    pub admission_signature: Signature,
    /// Append-only audit trail of status transitions.
    pub audit_log: Vec<String>,
}

impl ContestHold {
    /// Returns a human-readable reason string suitable for embedding in
    /// `AdjudicationContext::active_challenge_reason`.
    #[must_use]
    pub fn escalation_reason(&self) -> String {
        format!(
            "SybilChallenge/{}: action {:?} is pause-eligible under active review",
            self.ground, self.action_id
        )
    }
}

// ---------------------------------------------------------------------------
// Challenge admission
// ---------------------------------------------------------------------------

/// Build the canonical CBOR payload signed for challenge admission.
///
/// # Errors
/// Returns `EscalationError::SerializationFailed` if canonical CBOR encoding
/// fails.
pub fn challenge_admission_payload(
    admission: &ChallengeAdmission,
) -> Result<Vec<u8>, EscalationError> {
    let payload = (
        CHALLENGE_ADMISSION_DOMAIN,
        &admission.hold_id,
        &admission.action_id,
        &admission.ground,
        &admission.admitted_at,
        &admission.admitted_by,
        &admission.admitter_public_key,
        &admission.evidence_hash,
        &admission.authority_chain_hash,
    );
    let mut encoded = Vec::new();
    ciborium::into_writer(&payload, &mut encoded).map_err(|e| {
        EscalationError::SerializationFailed {
            context: "challenge admission payload".into(),
            reason: e.to_string(),
        }
    })?;
    Ok(encoded)
}

/// Sign a challenge admission with the admitting actor's Ed25519 key.
///
/// # Errors
/// Returns an error if required provenance fields are placeholders or if the
/// canonical payload cannot be serialized.
pub fn sign_challenge_admission(
    admission: ChallengeAdmission,
    secret_key: &SecretKey,
) -> Result<SignedChallengeAdmission, EscalationError> {
    validate_challenge_admission_metadata(&admission)?;
    let payload = challenge_admission_payload(&admission)?;
    Ok(SignedChallengeAdmission {
        admission,
        admission_signature: crypto::sign(&payload, secret_key),
    })
}

/// Verify a signed Sybil challenge admission.
///
/// # Errors
/// Returns an error if provenance metadata is placeholder-like, if the
/// signature is empty/zero, or if Ed25519 verification fails.
pub fn verify_challenge_admission(
    signed: &SignedChallengeAdmission,
) -> Result<(), EscalationError> {
    validate_challenge_admission_metadata(&signed.admission)?;
    if signed.admission_signature.is_empty() {
        return Err(EscalationError::InvalidSignature {
            signer: signed.admission.admitted_by.to_string(),
            reason: "challenge admission signature is empty or all-zero".into(),
        });
    }
    let payload = challenge_admission_payload(&signed.admission)?;
    if !crypto::verify(
        &payload,
        &signed.admission_signature,
        &signed.admission.admitter_public_key,
    ) {
        return Err(EscalationError::InvalidSignature {
            signer: signed.admission.admitted_by.to_string(),
            reason: "challenge admission signature does not verify".into(),
        });
    }
    Ok(())
}

fn validate_challenge_admission_metadata(
    admission: &ChallengeAdmission,
) -> Result<(), EscalationError> {
    if admission.hold_id == Uuid::nil() {
        return Err(EscalationError::InvalidProvenance {
            reason: "challenge hold id must be caller-supplied and non-nil".into(),
        });
    }
    if admission.action_id == [0u8; 32] {
        return Err(EscalationError::InvalidProvenance {
            reason: "challenge action id must be non-zero".into(),
        });
    }
    if admission.evidence_hash == [0u8; 32] {
        return Err(EscalationError::InvalidProvenance {
            reason: "challenge admission requires non-zero evidence hash".into(),
        });
    }
    if admission.authority_chain_hash == [0u8; 32] {
        return Err(EscalationError::InvalidProvenance {
            reason: "challenge admission requires non-zero authority chain hash".into(),
        });
    }
    if admission.admitter_public_key == PublicKey::from_bytes([0u8; 32]) {
        return Err(EscalationError::InvalidProvenance {
            reason: "challenge admission requires a non-zero Ed25519 public key".into(),
        });
    }
    let derived_did = did_from_public_key(&admission.admitter_public_key).map_err(|e| {
        EscalationError::InvalidProvenance {
            reason: format!("challenge admission admitter public key did derivation failed: {e}"),
        }
    })?;
    if derived_did != admission.admitted_by {
        return Err(EscalationError::InvalidProvenance {
            reason: "challenge admission admitted_by DID is not bound to admitter public key"
                .into(),
        });
    }
    Ok(())
}

/// Admit a credible, signed Sybil challenge and return a `ContestHold` in
/// `PauseEligible` status.
///
/// The caller is responsible for:
/// 1. Storing the `ContestHold` in a durable audit store.
/// 2. Passing `hold.escalation_reason()` into the kernel's
///    `AdjudicationContext::active_challenge_reason` so the CGR Kernel
///    can return `Verdict::Escalated` while review is pending. Final denials
///    such as kernel mutation or human-override suppression still return
///    `Verdict::Denied`.
///
/// The hold id and `admitted_at` are supplied by the caller to avoid internal
/// randomness or clock calls.
///
/// # Errors
/// Returns an error if the admission signature or provenance metadata is
/// invalid.
pub fn admit_challenge(signed: SignedChallengeAdmission) -> Result<ContestHold, EscalationError> {
    verify_challenge_admission(&signed)?;
    let admission = signed.admission;
    let entry = format!(
        "admitted at {:?}: ground {} by {} evidence {:?}",
        admission.admitted_at, admission.ground, admission.admitted_by, admission.evidence_hash
    );
    Ok(ContestHold {
        id: admission.hold_id,
        action_id: admission.action_id,
        ground: admission.ground,
        status: ContestStatus::PauseEligible,
        admitted_at: admission.admitted_at,
        admitted_by: admission.admitted_by,
        admitter_public_key: admission.admitter_public_key,
        evidence_hash: admission.evidence_hash,
        authority_chain_hash: admission.authority_chain_hash,
        admission_signature: signed.admission_signature,
        audit_log: vec![entry],
    })
}

/// Advance a contest hold to `UnderReview`.
pub fn begin_review(hold: &mut ContestHold, at: Timestamp) -> Result<(), EscalationError> {
    if hold.status != ContestStatus::PauseEligible {
        return Err(EscalationError::InvalidStateTransition {
            from: hold.status.as_str().to_owned(),
            to: "UnderReview".into(),
        });
    }
    hold.audit_log.push(format!("review started at {at:?}"));
    hold.status = ContestStatus::UnderReview;
    Ok(())
}

/// Resolve a contest hold (challenge sustained or action reversed).
pub fn resolve_hold(
    hold: &mut ContestHold,
    at: Timestamp,
    outcome: &str,
) -> Result<(), EscalationError> {
    match hold.status {
        ContestStatus::PauseEligible | ContestStatus::UnderReview => {
            hold.audit_log
                .push(format!("resolved at {at:?}: {outcome}"));
            hold.status = ContestStatus::Resolved;
            Ok(())
        }
        _ => Err(EscalationError::InvalidStateTransition {
            from: hold.status.as_str().to_owned(),
            to: "Resolved".into(),
        }),
    }
}

/// Dismiss a contest hold (insufficient grounds; action unblocked).
pub fn dismiss_hold(
    hold: &mut ContestHold,
    at: Timestamp,
    reason: &str,
) -> Result<(), EscalationError> {
    match hold.status {
        ContestStatus::PauseEligible | ContestStatus::UnderReview => {
            hold.audit_log
                .push(format!("dismissed at {at:?}: {reason}"));
            hold.status = ContestStatus::Dismissed;
            Ok(())
        }
        _ => Err(EscalationError::InvalidStateTransition {
            from: hold.status.as_str().to_owned(),
            to: "Dismissed".into(),
        }),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;

    fn action_id() -> [u8; 32] {
        [7u8; 32]
    }
    fn ts(ms: u64) -> Timestamp {
        Timestamp::new(ms, 0)
    }
    fn did(n: &str) -> Did {
        Did::new(&format!("did:exo:{n}")).unwrap()
    }
    fn uuid(byte: u8) -> Uuid {
        Uuid::from_bytes([byte; 16])
    }
    fn keypair(seed: u8) -> exo_core::crypto::KeyPair {
        exo_core::crypto::KeyPair::from_secret_bytes([seed; 32]).unwrap()
    }
    fn admission_with(
        hold_id: Uuid,
        ground: SybilChallengeGround,
        keypair: &exo_core::crypto::KeyPair,
    ) -> ChallengeAdmission {
        ChallengeAdmission {
            hold_id,
            action_id: action_id(),
            ground,
            admitted_at: ts(1000),
            admitted_by: did_from_public_key(keypair.public_key()).unwrap(),
            admitter_public_key: *keypair.public_key(),
            evidence_hash: [0xEEu8; 32],
            authority_chain_hash: [0xACu8; 32],
        }
    }
    fn signed_admission() -> SignedChallengeAdmission {
        let keypair = keypair(7);
        sign_challenge_admission(
            admission_with(
                uuid(1),
                SybilChallengeGround::ConcealedCommonControl,
                &keypair,
            ),
            keypair.secret_key(),
        )
        .unwrap()
    }

    #[test]
    fn admit_creates_pause_eligible_hold() {
        let hold = admit_challenge(signed_admission()).unwrap();
        let keypair = keypair(7);
        assert_eq!(hold.status, ContestStatus::PauseEligible);
        assert_eq!(hold.ground, SybilChallengeGround::ConcealedCommonControl);
        assert_eq!(hold.action_id, action_id());
        assert_eq!(hold.id, uuid(1));
        assert_eq!(
            hold.admitted_by,
            did_from_public_key(keypair.public_key()).unwrap()
        );
        assert_eq!(hold.evidence_hash, [0xEEu8; 32]);
        assert_eq!(hold.authority_chain_hash, [0xACu8; 32]);
        assert!(!hold.admission_signature.is_empty());
        assert!(!hold.audit_log.is_empty());
    }

    #[test]
    fn admit_challenge_is_deterministic_for_same_input() {
        let signed = signed_admission();
        let first = admit_challenge(signed.clone()).unwrap();
        let second = admit_challenge(signed).unwrap();

        assert_eq!(first.id, second.id);
        assert_eq!(first.admitted_at, second.admitted_at);
        assert_eq!(first.admission_signature, second.admission_signature);
    }

    #[test]
    fn verify_challenge_admission_accepts_valid_signature() {
        let signed = signed_admission();
        assert!(verify_challenge_admission(&signed).is_ok());
    }

    #[test]
    fn verify_challenge_admission_rejects_empty_and_zero_signatures() {
        let mut signed = signed_admission();
        signed.admission_signature = Signature::Empty;
        assert!(verify_challenge_admission(&signed).is_err());

        signed.admission_signature = Signature::Ed25519([0u8; 64]);
        assert!(verify_challenge_admission(&signed).is_err());
    }

    #[test]
    fn verify_challenge_admission_rejects_fake_non_empty_signature() {
        let mut signed = signed_admission();
        signed.admission_signature = Signature::Ed25519([0xABu8; 64]);
        assert!(verify_challenge_admission(&signed).is_err());
        assert!(admit_challenge(signed).is_err());
    }

    #[test]
    fn verify_challenge_admission_rejects_wrong_key() {
        let signer_keypair = keypair(7);
        let wrong_keypair = keypair(8);
        let mut signed = sign_challenge_admission(
            admission_with(
                uuid(2),
                SybilChallengeGround::CoordinatedManipulation,
                &signer_keypair,
            ),
            signer_keypair.secret_key(),
        )
        .unwrap();
        signed.admission.admitter_public_key = *wrong_keypair.public_key();
        assert!(verify_challenge_admission(&signed).is_err());
    }

    #[test]
    fn verify_challenge_admission_rejects_mismatched_admitter_did_key() {
        let attacker_keypair = keypair(9);
        let mut admission = admission_with(
            uuid(9),
            SybilChallengeGround::QuorumContamination,
            &attacker_keypair,
        );
        admission.admitted_by = did("victim-reviewer");
        let payload = challenge_admission_payload(&admission).unwrap();
        let signed = SignedChallengeAdmission {
            admission,
            admission_signature: crypto::sign(&payload, attacker_keypair.secret_key()),
        };

        assert!(verify_challenge_admission(&signed).is_err());
    }

    #[test]
    fn verify_challenge_admission_rejects_tampered_payload() {
        let mut signed = signed_admission();
        signed.admission.evidence_hash = [0xFEu8; 32];
        assert!(verify_challenge_admission(&signed).is_err());
    }

    #[test]
    fn verify_challenge_admission_rejects_replay_to_other_action() {
        let mut signed = signed_admission();
        signed.admission.action_id = [0x99u8; 32];
        assert!(verify_challenge_admission(&signed).is_err());
    }

    #[test]
    fn challenge_admission_payload_is_domain_separated_and_deterministic() {
        let keypair = keypair(7);
        let admission = admission_with(
            uuid(3),
            SybilChallengeGround::SyntheticHumanMisrepresentation,
            &keypair,
        );
        let first = challenge_admission_payload(&admission).unwrap();
        let second = challenge_admission_payload(&admission).unwrap();
        assert_eq!(first, second);
        assert_ne!(first, action_id().to_vec());
        assert!(
            first
                .windows(CHALLENGE_ADMISSION_DOMAIN.len())
                .any(|window| window == CHALLENGE_ADMISSION_DOMAIN.as_bytes())
        );
    }

    #[test]
    fn admit_challenge_rejects_placeholder_provenance() {
        let keypair = keypair(7);
        let mut admission = admission_with(
            Uuid::nil(),
            SybilChallengeGround::ConcealedCommonControl,
            &keypair,
        );
        assert!(sign_challenge_admission(admission.clone(), keypair.secret_key()).is_err());

        admission.hold_id = uuid(4);
        admission.action_id = [0u8; 32];
        assert!(sign_challenge_admission(admission.clone(), keypair.secret_key()).is_err());

        admission.action_id = action_id();
        admission.evidence_hash = [0u8; 32];
        assert!(sign_challenge_admission(admission.clone(), keypair.secret_key()).is_err());

        admission.evidence_hash = [0xEEu8; 32];
        admission.authority_chain_hash = [0u8; 32];
        assert!(sign_challenge_admission(admission, keypair.secret_key()).is_err());
    }

    #[test]
    fn escalation_reason_contains_ground() {
        let keypair = keypair(7);
        let hold = admit_challenge(
            sign_challenge_admission(
                admission_with(
                    uuid(5),
                    SybilChallengeGround::CoordinatedManipulation,
                    &keypair,
                ),
                keypair.secret_key(),
            )
            .unwrap(),
        )
        .unwrap();
        let reason = hold.escalation_reason();
        assert!(reason.contains("CoordinatedManipulation"));
        assert!(reason.contains("SybilChallenge"));
    }

    #[test]
    fn begin_review_transitions_from_pause_eligible() {
        let keypair = keypair(7);
        let mut hold = admit_challenge(
            sign_challenge_admission(
                admission_with(uuid(6), SybilChallengeGround::QuorumContamination, &keypair),
                keypair.secret_key(),
            )
            .unwrap(),
        )
        .unwrap();
        assert!(begin_review(&mut hold, ts(2000)).is_ok());
        assert_eq!(hold.status, ContestStatus::UnderReview);
        assert_eq!(hold.audit_log.len(), 2);
    }

    #[test]
    fn begin_review_fails_if_not_pause_eligible() {
        let mut hold = admit_challenge(signed_admission()).unwrap();
        hold.status = ContestStatus::Resolved;
        assert!(begin_review(&mut hold, ts(2000)).is_err());
    }

    #[test]
    fn resolve_hold_from_pause_eligible() {
        let keypair = keypair(7);
        let mut hold = admit_challenge(
            sign_challenge_admission(
                admission_with(
                    uuid(7),
                    SybilChallengeGround::SyntheticHumanMisrepresentation,
                    &keypair,
                ),
                keypair.secret_key(),
            )
            .unwrap(),
        )
        .unwrap();
        assert!(resolve_hold(&mut hold, ts(3000), "challenge sustained").is_ok());
        assert_eq!(hold.status, ContestStatus::Resolved);
    }

    #[test]
    fn resolve_hold_from_under_review() {
        let mut hold = admit_challenge(signed_admission()).unwrap();
        begin_review(&mut hold, ts(2000)).unwrap();
        assert!(resolve_hold(&mut hold, ts(3000), "action reversed").is_ok());
        assert_eq!(hold.status, ContestStatus::Resolved);
    }

    #[test]
    fn dismiss_hold_unblocks_action() {
        let keypair = keypair(7);
        let mut hold = admit_challenge(
            sign_challenge_admission(
                admission_with(
                    uuid(8),
                    SybilChallengeGround::CoordinatedManipulation,
                    &keypair,
                ),
                keypair.secret_key(),
            )
            .unwrap(),
        )
        .unwrap();
        assert!(dismiss_hold(&mut hold, ts(2000), "insufficient evidence").is_ok());
        assert_eq!(hold.status, ContestStatus::Dismissed);
    }

    #[test]
    fn dismiss_after_resolved_fails() {
        let keypair = keypair(7);
        let mut hold = admit_challenge(
            sign_challenge_admission(
                admission_with(uuid(9), SybilChallengeGround::QuorumContamination, &keypair),
                keypair.secret_key(),
            )
            .unwrap(),
        )
        .unwrap();
        resolve_hold(&mut hold, ts(2000), "done").unwrap();
        assert!(dismiss_hold(&mut hold, ts(3000), "late").is_err());
    }

    #[test]
    fn all_four_grounds_admissible() {
        let keypair = keypair(7);
        let mut hold_id_marker = 10u8;
        for ground in [
            SybilChallengeGround::ConcealedCommonControl,
            SybilChallengeGround::CoordinatedManipulation,
            SybilChallengeGround::QuorumContamination,
            SybilChallengeGround::SyntheticHumanMisrepresentation,
        ] {
            let hold = admit_challenge(
                sign_challenge_admission(
                    admission_with(uuid(hold_id_marker), ground.clone(), &keypair),
                    keypair.secret_key(),
                )
                .unwrap(),
            )
            .unwrap();
            assert_eq!(hold.status, ContestStatus::PauseEligible);
            hold_id_marker = hold_id_marker.saturating_add(1);
        }
    }

    #[test]
    fn audit_log_grows_with_transitions() {
        let mut hold = admit_challenge(signed_admission()).unwrap();
        assert_eq!(hold.audit_log.len(), 1);
        begin_review(&mut hold, ts(2000)).unwrap();
        assert_eq!(hold.audit_log.len(), 2);
        resolve_hold(&mut hold, ts(3000), "confirmed").unwrap();
        assert_eq!(hold.audit_log.len(), 3);
    }

    #[test]
    fn ground_display() {
        assert_eq!(
            SybilChallengeGround::ConcealedCommonControl.to_string(),
            "ConcealedCommonControl"
        );
        assert_eq!(
            SybilChallengeGround::SyntheticHumanMisrepresentation.to_string(),
            "SyntheticHumanMisrepresentation"
        );
    }

    #[test]
    fn contest_status_labels_do_not_depend_on_debug_formatting() {
        assert_eq!(ContestStatus::PauseEligible.as_str(), "PauseEligible");
        assert_eq!(ContestStatus::Dismissed.to_string(), "Dismissed");

        let source = include_str!("challenge.rs");
        let production = source
            .split("#[cfg(test)]")
            .next()
            .expect("production section");
        assert!(
            !production.contains("format!(\"{:?}\", hold.status)"),
            "contest status errors must use explicit stable labels"
        );
    }
}