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
// 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

//! Escalation pathways including Sybil adjudication (CR-001 section 8.6).

use exo_core::{Did, Timestamp};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::{detector::DetectionSignal, error::EscalationError};

/// Pathway through which a detected threat is escalated for resolution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum EscalationPath {
    Standard,
    SybilAdjudication,
    Emergency,
    Constitutional,
}

impl EscalationPath {
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Standard => "Standard",
            Self::SybilAdjudication => "SybilAdjudication",
            Self::Emergency => "Emergency",
            Self::Constitutional => "Constitutional",
        }
    }
}

/// Stages of the Sybil adjudication path.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SybilStage {
    Detection,
    Triage,
    Quarantine,
    EvidentaryReview,
    ClearanceDowngrade,
    Reinstatement,
    AuditLog,
}

impl SybilStage {
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Detection => "Detection",
            Self::Triage => "Triage",
            Self::Quarantine => "Quarantine",
            Self::EvidentaryReview => "EvidentaryReview",
            Self::ClearanceDowngrade => "ClearanceDowngrade",
            Self::Reinstatement => "Reinstatement",
            Self::AuditLog => "AuditLog",
        }
    }
}

/// Lifecycle status of an escalation case.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CaseStatus {
    Open,
    InProgress,
    PendingReview,
    Resolved,
    Closed,
}

/// Priority ranking of an escalation case, derived from signal confidence.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum CasePriority {
    Low,
    Medium,
    High,
    Critical,
}

/// A tracked escalation case linking detection signals to resolution stages.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EscalationCase {
    pub id: Uuid,
    pub path: EscalationPath,
    pub status: CaseStatus,
    pub priority: CasePriority,
    pub stages_completed: Vec<String>,
    pub evidence: Vec<[u8; 32]>,
    pub assignee: Option<Did>,
    pub created: Timestamp,
}

/// Deterministic input for opening an escalation case.
///
/// The case id and creation timestamp are supplied by the caller from the
/// surrounding HLC/provenance context. Escalation case creation never reads
/// randomness or wall-clock time internally.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EscalationCaseInput {
    pub id: Uuid,
    pub created: Timestamp,
    pub signal: DetectionSignal,
    pub path: EscalationPath,
}

/// Escalate a detection signal along a specific path.
///
/// # Errors
/// Returns an error when caller-supplied provenance fields are placeholders or
/// the detection signal is outside its documented bounds.
pub fn escalate(input: EscalationCaseInput) -> Result<EscalationCase, EscalationError> {
    if input.id == Uuid::nil() {
        return Err(EscalationError::InvalidProvenance {
            reason: "escalation case id must be caller-supplied and non-nil".into(),
        });
    }
    if input.signal.source.trim().is_empty() {
        return Err(EscalationError::InvalidSignal(
            "detection signal source must not be empty".into(),
        ));
    }
    if input.signal.confidence > 100 {
        return Err(EscalationError::InvalidSignal(
            "detection signal confidence must be between 0 and 100".into(),
        ));
    }
    if input.signal.evidence_hash == [0u8; 32] {
        return Err(EscalationError::InvalidProvenance {
            reason: "escalation case requires a non-zero evidence hash".into(),
        });
    }

    let priority = match input.signal.confidence {
        0..=30 => CasePriority::Low,
        31..=60 => CasePriority::Medium,
        61..=85 => CasePriority::High,
        _ => CasePriority::Critical,
    };

    let initial_stage = match &input.path {
        EscalationPath::SybilAdjudication => SybilStage::Detection.to_string(),
        EscalationPath::Emergency => "emergency_activated".to_string(),
        EscalationPath::Constitutional => "constitutional_review".to_string(),
        EscalationPath::Standard => "intake".to_string(),
    };

    Ok(EscalationCase {
        id: input.id,
        path: input.path,
        status: CaseStatus::Open,
        priority,
        stages_completed: vec![initial_stage],
        evidence: vec![input.signal.evidence_hash],
        assignee: None,
        created: input.created,
    })
}

/// Advance a Sybil adjudication case to the next stage.
pub fn advance_sybil_stage(
    case: &mut EscalationCase,
    stage: SybilStage,
) -> Result<(), EscalationError> {
    if case.path != EscalationPath::SybilAdjudication {
        return Err(EscalationError::InvalidStateTransition {
            from: case.path.as_str().to_owned(),
            to: stage.as_str().to_owned(),
        });
    }
    case.stages_completed.push(stage.to_string());
    if stage == SybilStage::AuditLog {
        case.status = CaseStatus::Resolved;
    } else {
        case.status = CaseStatus::InProgress;
    }
    Ok(())
}

/// Reinstate a Sybil adjudication case with explicit clearance evidence.
///
/// A non-zero `clearance_evidence` hash is REQUIRED — CR-001 §8.6 mandates
/// that reinstatement without evidence is rejected to prevent automatic or
/// evidence-free restoration of contested actors.
///
/// On success, the evidence hash is appended to `case.evidence` and the case
/// advances to `SybilStage::Reinstatement`.
pub fn reinstate(
    case: &mut EscalationCase,
    clearance_evidence: [u8; 32],
) -> Result<(), EscalationError> {
    if case.path != EscalationPath::SybilAdjudication {
        return Err(EscalationError::InvalidStateTransition {
            from: case.path.as_str().to_owned(),
            to: "Reinstatement".into(),
        });
    }
    if clearance_evidence == [0u8; 32] {
        return Err(EscalationError::IncompleteCase {
            reason: "reinstatement requires explicit clearance evidence (non-zero hash)".into(),
        });
    }
    case.evidence.push(clearance_evidence);
    advance_sybil_stage(case, SybilStage::Reinstatement)
}

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

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

    fn signal(confidence: u8, st: SignalType) -> DetectionSignal {
        DetectionSignal {
            source: "test".into(),
            signal_type: st,
            confidence,
            evidence_hash: [1u8; 32],
            timestamp: Timestamp::new(1000, 0),
        }
    }
    fn uuid(byte: u8) -> Uuid {
        Uuid::from_bytes([byte; 16])
    }
    fn case_input(
        id_marker: u8,
        confidence: u8,
        st: SignalType,
        path: EscalationPath,
    ) -> EscalationCaseInput {
        EscalationCaseInput {
            id: uuid(id_marker),
            created: Timestamp::new(2000, 0),
            signal: signal(confidence, st),
            path,
        }
    }

    #[test]
    fn escalate_standard() {
        let c = escalate(case_input(
            1,
            40,
            SignalType::AnomalousPattern,
            EscalationPath::Standard,
        ))
        .unwrap();
        assert_eq!(c.path, EscalationPath::Standard);
        assert_eq!(c.status, CaseStatus::Open);
        assert_eq!(c.priority, CasePriority::Medium);
        assert!(c.stages_completed.contains(&"intake".to_string()));
        assert_eq!(c.evidence, vec![[1u8; 32]]);
        assert_eq!(c.id, uuid(1));
        assert_eq!(c.created, Timestamp::new(2000, 0));
    }

    #[test]
    fn escalate_is_deterministic_for_same_input() {
        let input = case_input(
            2,
            40,
            SignalType::AnomalousPattern,
            EscalationPath::Standard,
        );
        let first = escalate(input.clone()).unwrap();
        let second = escalate(input).unwrap();

        assert_eq!(first.id, second.id);
        assert_eq!(first.created, second.created);
        assert_eq!(first.stages_completed, second.stages_completed);
        assert_eq!(first.evidence, second.evidence);
    }

    #[test]
    fn escalate_rejects_placeholder_provenance() {
        let mut input = case_input(
            3,
            40,
            SignalType::AnomalousPattern,
            EscalationPath::Standard,
        );
        input.id = Uuid::nil();
        assert!(escalate(input.clone()).is_err());

        input.id = uuid(3);
        input.signal.evidence_hash = [0u8; 32];
        assert!(escalate(input).is_err());
    }

    #[test]
    fn escalate_sybil() {
        let c = escalate(case_input(
            4,
            75,
            SignalType::SybilSuspicion,
            EscalationPath::SybilAdjudication,
        ))
        .unwrap();
        assert_eq!(c.path, EscalationPath::SybilAdjudication);
        assert_eq!(c.priority, CasePriority::High);
        assert!(c.stages_completed.contains(&"Detection".to_string()));
    }
    #[test]
    fn escalate_emergency() {
        let c = escalate(case_input(
            5,
            95,
            SignalType::EmergencyCondition,
            EscalationPath::Emergency,
        ))
        .unwrap();
        assert_eq!(c.priority, CasePriority::Critical);
    }
    #[test]
    fn escalate_constitutional() {
        let c = escalate(case_input(
            6,
            60,
            SignalType::ConsentViolation,
            EscalationPath::Constitutional,
        ))
        .unwrap();
        assert!(
            c.stages_completed
                .contains(&"constitutional_review".to_string())
        );
    }
    #[test]
    fn priority_from_confidence() {
        assert_eq!(
            escalate(case_input(
                7,
                20,
                SignalType::AnomalousPattern,
                EscalationPath::Standard
            ))
            .unwrap()
            .priority,
            CasePriority::Low
        );
        assert_eq!(
            escalate(case_input(
                8,
                50,
                SignalType::AnomalousPattern,
                EscalationPath::Standard
            ))
            .unwrap()
            .priority,
            CasePriority::Medium
        );
        assert_eq!(
            escalate(case_input(
                9,
                70,
                SignalType::AnomalousPattern,
                EscalationPath::Standard
            ))
            .unwrap()
            .priority,
            CasePriority::High
        );
        assert_eq!(
            escalate(case_input(
                10,
                90,
                SignalType::AnomalousPattern,
                EscalationPath::Standard
            ))
            .unwrap()
            .priority,
            CasePriority::Critical
        );
    }
    #[test]
    fn advance_sybil_stages() {
        let mut c = escalate(case_input(
            11,
            75,
            SignalType::SybilSuspicion,
            EscalationPath::SybilAdjudication,
        ))
        .unwrap();
        assert!(advance_sybil_stage(&mut c, SybilStage::Triage).is_ok());
        assert_eq!(c.status, CaseStatus::InProgress);
        assert!(advance_sybil_stage(&mut c, SybilStage::Quarantine).is_ok());
        assert!(advance_sybil_stage(&mut c, SybilStage::EvidentaryReview).is_ok());
        assert!(advance_sybil_stage(&mut c, SybilStage::ClearanceDowngrade).is_ok());
        assert!(advance_sybil_stage(&mut c, SybilStage::Reinstatement).is_ok());
        assert!(advance_sybil_stage(&mut c, SybilStage::AuditLog).is_ok());
        assert_eq!(c.status, CaseStatus::Resolved);
        assert_eq!(c.stages_completed.len(), 7); // Detection + 6 stages
    }
    #[test]
    fn advance_non_sybil_fails() {
        let mut c = escalate(case_input(
            12,
            50,
            SignalType::AnomalousPattern,
            EscalationPath::Standard,
        ))
        .unwrap();
        assert!(advance_sybil_stage(&mut c, SybilStage::Triage).is_err());
    }

    // ── reinstate() tests ──────────────────────────────────────────────────────

    fn sybil_case_at_clearance_downgrade() -> EscalationCase {
        let mut c = escalate(case_input(
            13,
            80,
            SignalType::SybilSuspicion,
            EscalationPath::SybilAdjudication,
        ))
        .unwrap();
        for stage in [
            SybilStage::Triage,
            SybilStage::Quarantine,
            SybilStage::EvidentaryReview,
            SybilStage::ClearanceDowngrade,
        ] {
            advance_sybil_stage(&mut c, stage).unwrap();
        }
        c
    }

    #[test]
    fn reinstate_requires_nonzero_evidence() {
        let mut c = sybil_case_at_clearance_downgrade();
        assert!(reinstate(&mut c, [0u8; 32]).is_err());
    }

    #[test]
    fn reinstate_with_valid_evidence_succeeds() {
        let mut c = sybil_case_at_clearance_downgrade();
        let evidence = [0xCEu8; 32];
        assert!(reinstate(&mut c, evidence).is_ok());
        assert!(c.stages_completed.contains(&"Reinstatement".to_string()));
        assert!(c.evidence.contains(&evidence));
    }

    #[test]
    fn reinstate_fails_on_non_sybil_path() {
        let mut c = escalate(case_input(
            14,
            50,
            SignalType::AnomalousPattern,
            EscalationPath::Standard,
        ))
        .unwrap();
        assert!(reinstate(&mut c, [0xAAu8; 32]).is_err());
    }
    #[test]
    fn sybil_stage_display() {
        assert_eq!(SybilStage::Detection.to_string(), "Detection");
        assert_eq!(SybilStage::AuditLog.to_string(), "AuditLog");
    }

    #[test]
    fn escalation_labels_do_not_depend_on_debug_formatting() {
        assert_eq!(
            EscalationPath::SybilAdjudication.as_str(),
            "SybilAdjudication"
        );
        assert_eq!(
            SybilStage::ClearanceDowngrade.as_str(),
            "ClearanceDowngrade"
        );

        let source = include_str!("escalation.rs");
        let production = source
            .split("#[cfg(test)]")
            .next()
            .expect("production section");
        assert!(
            !production.contains("format!(\"{:?}\", case.path)"),
            "escalation path errors must use explicit stable labels"
        );
        assert!(
            !production.contains("format!(\"{stage:?}\")"),
            "Sybil stage errors must use explicit stable labels"
        );
        assert!(
            !production.contains("write!(f, \"{self:?}\")"),
            "Sybil stage Display must use explicit stable labels"
        );
    }
}