crtx-core 0.1.1

Core IDs, errors, and schema constants for Cortex.
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
//! Claim ceilings and reportability metadata.
//!
//! Cortex must distinguish local development mechanics from signed,
//! externally anchored, or authority-grade claims. This module provides the
//! small lattice used by higher layers to downgrade mixed evidence to the
//! weakest truthful claim.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::proof::ProofState;

/// Runtime mode that bounds what Cortex may truthfully claim.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum RuntimeMode {
    /// Runtime mode was not supplied or could not be verified.
    Unknown,
    /// Development-only execution. No durable authority claim should escape.
    Dev,
    /// Remote API call (e.g. Anthropic, external hosted model) whose response
    /// is unsigned and whose provenance cannot be locally verified. Trust
    /// ceiling is lower than `LocalUnsigned` because the execution boundary
    /// is outside the operator's machine. See ADR 0037 and ADR 0048 prep.
    RemoteUnsigned,
    /// Local unsigned append or local-only metadata.
    LocalUnsigned,
    /// Signed local ledger evidence is available.
    SignedLocalLedger,
    /// Signed evidence is bound to an external anchor surface.
    ExternallyAnchored,
    /// Authority-grade mode: signed, anchored, policy-gated, and suitable for
    /// high-authority reporting.
    AuthorityGrade,
}

impl RuntimeMode {
    /// Highest claim ceiling this runtime mode can support.
    #[must_use]
    pub const fn claim_ceiling(self) -> ClaimCeiling {
        match self {
            Self::Unknown => ClaimCeiling::DevOnly,
            Self::Dev => ClaimCeiling::DevOnly,
            Self::RemoteUnsigned => ClaimCeiling::LocalUnsigned,
            Self::LocalUnsigned => ClaimCeiling::LocalUnsigned,
            Self::SignedLocalLedger => ClaimCeiling::SignedLocalLedger,
            Self::ExternallyAnchored => ClaimCeiling::ExternallyAnchored,
            Self::AuthorityGrade => ClaimCeiling::AuthorityGrade,
        }
    }
}

/// Authority class of the evidence supporting a claim.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum AuthorityClass {
    /// Source may be observed but must not influence durable authority.
    Untrusted,
    /// Derived artifact such as a summary or reflection candidate.
    Derived,
    /// Audit-visible observed source with local influence only.
    Observed,
    /// Operator-approved source for bounded automation.
    Verified,
    /// Human root of trust or policy-equivalent authority for this deployment.
    Operator,
}

/// Proof state as it participates in claim reporting.
///
/// `Unknown` is explicit because ADR 0037 forbids silently treating absent
/// proof closure as local unsigned authority.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ClaimProofState {
    /// No proof closure was supplied.
    Unknown,
    /// The proof closure is broken and can support diagnostics only.
    Broken,
    /// The proof closure is incomplete but no broken edge was observed.
    Partial,
    /// Every required proof edge for the claim passed.
    FullChainVerified,
}

impl ClaimProofState {
    /// Highest claim ceiling this proof state can support.
    #[must_use]
    pub const fn claim_ceiling(self) -> ClaimCeiling {
        match self {
            Self::Unknown | Self::Broken => ClaimCeiling::DevOnly,
            Self::Partial => ClaimCeiling::LocalUnsigned,
            Self::FullChainVerified => ClaimCeiling::AuthorityGrade,
        }
    }
}

impl From<ProofState> for ClaimProofState {
    fn from(value: ProofState) -> Self {
        match value {
            ProofState::FullChainVerified => Self::FullChainVerified,
            ProofState::Partial => Self::Partial,
            ProofState::Broken => Self::Broken,
        }
    }
}

impl AuthorityClass {
    /// Highest claim ceiling this authority class can support.
    #[must_use]
    pub const fn claim_ceiling(self) -> ClaimCeiling {
        match self {
            Self::Untrusted => ClaimCeiling::DevOnly,
            Self::Derived | Self::Observed => ClaimCeiling::LocalUnsigned,
            Self::Verified => ClaimCeiling::SignedLocalLedger,
            Self::Operator => ClaimCeiling::AuthorityGrade,
        }
    }

    /// Weakest authority class from an iterator.
    #[must_use]
    pub fn weakest<I>(classes: I) -> Option<Self>
    where
        I: IntoIterator<Item = Self>,
    {
        classes.into_iter().min()
    }
}

/// Maximum truthful reporting level for a claim.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ClaimCeiling {
    /// Development-only; not reportable as durable evidence.
    DevOnly,
    /// Local unsigned mechanics only.
    LocalUnsigned,
    /// Signed local ledger claim.
    SignedLocalLedger,
    /// Externally anchored ledger claim.
    ExternallyAnchored,
    /// Authority-grade claim suitable for high-authority reporting.
    AuthorityGrade,
}

impl ClaimCeiling {
    /// Weakest ceiling from an iterator.
    #[must_use]
    pub fn weakest<I>(ceilings: I) -> Option<Self>
    where
        I: IntoIterator<Item = Self>,
    {
        ceilings.into_iter().min()
    }

    /// Weaken this ceiling to the weaker of two ceilings.
    #[must_use]
    pub fn mix_to_weakest(self, other: Self) -> Self {
        self.min(other)
    }
}

/// Metadata for a claim that may be shown, exported, or used as authority.
///
/// `effective_ceiling` is private and always recomputed from runtime mode,
/// authority class, and requested ceiling. Callers can ask for a high ceiling,
/// but they cannot construct a reportable claim above its weakest evidence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ReportableClaim {
    claim: String,
    runtime_mode: RuntimeMode,
    authority_class: AuthorityClass,
    proof_state: ClaimProofState,
    requested_ceiling: ClaimCeiling,
    effective_ceiling: ClaimCeiling,
    downgrade_reasons: Vec<String>,
}

impl ReportableClaim {
    /// Construct claim metadata with the effective ceiling clamped to the
    /// weakest supporting signal.
    #[must_use]
    pub fn new(
        claim: impl Into<String>,
        runtime_mode: RuntimeMode,
        authority_class: AuthorityClass,
        proof_state: ClaimProofState,
        requested_ceiling: ClaimCeiling,
    ) -> Self {
        let mut downgrade_reasons = Vec::new();
        let effective_ceiling = effective_ceiling(
            runtime_mode,
            authority_class,
            proof_state,
            requested_ceiling,
        );

        if effective_ceiling < requested_ceiling {
            downgrade_reasons.push(format!(
                "requested ceiling {requested_ceiling:?} downgraded to {effective_ceiling:?}"
            ));
        }
        if proof_state != ClaimProofState::FullChainVerified {
            downgrade_reasons.push(format!(
                "proof state {proof_state:?} limits authority claims"
            ));
        }

        Self {
            claim: claim.into(),
            runtime_mode,
            authority_class,
            proof_state,
            requested_ceiling,
            effective_ceiling,
            downgrade_reasons,
        }
    }

    /// Claim text.
    #[must_use]
    pub fn claim(&self) -> &str {
        &self.claim
    }

    /// Runtime mode used to evaluate this claim.
    #[must_use]
    pub const fn runtime_mode(&self) -> RuntimeMode {
        self.runtime_mode
    }

    /// Authority class used to evaluate this claim.
    #[must_use]
    pub const fn authority_class(&self) -> AuthorityClass {
        self.authority_class
    }

    /// Proof state used to evaluate this claim.
    #[must_use]
    pub const fn proof_state(&self) -> ClaimProofState {
        self.proof_state
    }

    /// Ceiling requested by the producer.
    #[must_use]
    pub const fn requested_ceiling(&self) -> ClaimCeiling {
        self.requested_ceiling
    }

    /// Effective ceiling after weakest-link downgrade.
    #[must_use]
    pub const fn effective_ceiling(&self) -> ClaimCeiling {
        self.effective_ceiling
    }

    /// Reasons this claim was downgraded.
    #[must_use]
    pub fn downgrade_reasons(&self) -> &[String] {
        &self.downgrade_reasons
    }

    /// Return a copy downgraded to the supplied ceiling.
    #[must_use]
    pub fn downgraded_to(mut self, ceiling: ClaimCeiling, reason: impl Into<String>) -> Self {
        self.requested_ceiling = self.requested_ceiling.min(ceiling);
        self.effective_ceiling = effective_ceiling(
            self.runtime_mode,
            self.authority_class,
            self.proof_state,
            self.requested_ceiling,
        );
        self.downgrade_reasons.push(reason.into());
        self
    }

    /// Mix this claim with another claim and return the weakest truthful
    /// metadata for the combined assertion.
    #[must_use]
    pub fn mix_to_weakest(mut self, other: &Self, claim: impl Into<String>) -> Self {
        self.claim = claim.into();
        self.runtime_mode = self.runtime_mode.min(other.runtime_mode);
        self.authority_class = self.authority_class.min(other.authority_class);
        self.proof_state = self.proof_state.min(other.proof_state);
        self.requested_ceiling = self.requested_ceiling.min(other.requested_ceiling);
        self.effective_ceiling = self.effective_ceiling.min(other.effective_ceiling);
        self.downgrade_reasons
            .extend(other.downgrade_reasons.iter().cloned());
        self.downgrade_reasons
            .push("mixed claim downgraded to weakest contributing claim".into());
        self
    }
}

/// Compute the effective ceiling for the supplied signals.
#[must_use]
pub fn effective_ceiling(
    runtime_mode: RuntimeMode,
    authority_class: AuthorityClass,
    proof_state: ClaimProofState,
    requested_ceiling: ClaimCeiling,
) -> ClaimCeiling {
    ClaimCeiling::weakest([
        runtime_mode.claim_ceiling(),
        authority_class.claim_ceiling(),
        proof_state.claim_ceiling(),
        requested_ceiling,
    ])
    .expect("fixed-size ceiling set is non-empty")
}

/// Compute the weakest authority class for mixed evidence.
#[must_use]
pub fn mix_authority_to_weakest<I>(classes: I) -> Option<AuthorityClass>
where
    I: IntoIterator<Item = AuthorityClass>,
{
    AuthorityClass::weakest(classes)
}

/// Compute the weakest claim ceiling for mixed evidence.
#[must_use]
pub fn mix_claims_to_weakest<I>(ceilings: I) -> Option<ClaimCeiling>
where
    I: IntoIterator<Item = ClaimCeiling>,
{
    ClaimCeiling::weakest(ceilings)
}

/// Compute the weakest effective ceiling across reportable claims.
#[must_use]
pub fn mix_reportable_claims_to_weakest<'a, I>(claims: I) -> Option<ClaimCeiling>
where
    I: IntoIterator<Item = &'a ReportableClaim>,
{
    claims
        .into_iter()
        .map(ReportableClaim::effective_ceiling)
        .min()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn runtime_mode_caps_claim_ceiling() {
        assert_eq!(RuntimeMode::Unknown.claim_ceiling(), ClaimCeiling::DevOnly);
        assert_eq!(RuntimeMode::Dev.claim_ceiling(), ClaimCeiling::DevOnly);
        assert_eq!(
            RuntimeMode::RemoteUnsigned.claim_ceiling(),
            ClaimCeiling::LocalUnsigned
        );
        assert_eq!(
            RuntimeMode::LocalUnsigned.claim_ceiling(),
            ClaimCeiling::LocalUnsigned
        );
        assert_eq!(
            RuntimeMode::SignedLocalLedger.claim_ceiling(),
            ClaimCeiling::SignedLocalLedger
        );
        assert_eq!(
            RuntimeMode::ExternallyAnchored.claim_ceiling(),
            ClaimCeiling::ExternallyAnchored
        );
        assert_eq!(
            RuntimeMode::AuthorityGrade.claim_ceiling(),
            ClaimCeiling::AuthorityGrade
        );
    }

    #[test]
    fn authority_class_caps_claim_ceiling() {
        assert_eq!(
            AuthorityClass::Untrusted.claim_ceiling(),
            ClaimCeiling::DevOnly
        );
        assert_eq!(
            AuthorityClass::Derived.claim_ceiling(),
            ClaimCeiling::LocalUnsigned
        );
        assert_eq!(
            AuthorityClass::Observed.claim_ceiling(),
            ClaimCeiling::LocalUnsigned
        );
        assert_eq!(
            AuthorityClass::Verified.claim_ceiling(),
            ClaimCeiling::SignedLocalLedger
        );
        assert_eq!(
            AuthorityClass::Operator.claim_ceiling(),
            ClaimCeiling::AuthorityGrade
        );
    }

    #[test]
    fn reportable_claim_clamps_to_weakest_signal() {
        let claim = ReportableClaim::new(
            "phase 2 mechanics verified",
            RuntimeMode::LocalUnsigned,
            AuthorityClass::Operator,
            ClaimProofState::FullChainVerified,
            ClaimCeiling::AuthorityGrade,
        );

        assert_eq!(claim.effective_ceiling(), ClaimCeiling::LocalUnsigned);
        assert!(!claim.downgrade_reasons().is_empty());
    }

    #[test]
    fn verified_source_cannot_lift_dev_runtime() {
        let claim = ReportableClaim::new(
            "trusted run history",
            RuntimeMode::Dev,
            AuthorityClass::Verified,
            ClaimProofState::FullChainVerified,
            ClaimCeiling::SignedLocalLedger,
        );

        assert_eq!(claim.effective_ceiling(), ClaimCeiling::DevOnly);
    }

    #[test]
    fn proof_state_caps_claim_ceiling() {
        let partial = ReportableClaim::new(
            "operator action observed",
            RuntimeMode::AuthorityGrade,
            AuthorityClass::Operator,
            ClaimProofState::Partial,
            ClaimCeiling::AuthorityGrade,
        );
        let broken = ReportableClaim::new(
            "trusted run history",
            RuntimeMode::AuthorityGrade,
            AuthorityClass::Operator,
            ClaimProofState::Broken,
            ClaimCeiling::AuthorityGrade,
        );
        let unknown = ReportableClaim::new(
            "export-ready evidence",
            RuntimeMode::AuthorityGrade,
            AuthorityClass::Operator,
            ClaimProofState::Unknown,
            ClaimCeiling::AuthorityGrade,
        );

        assert_eq!(partial.effective_ceiling(), ClaimCeiling::LocalUnsigned);
        assert_eq!(broken.effective_ceiling(), ClaimCeiling::DevOnly);
        assert_eq!(unknown.effective_ceiling(), ClaimCeiling::DevOnly);
    }

    #[test]
    fn mixed_claims_use_weakest_effective_ceiling() {
        let strong = ReportableClaim::new(
            "anchored ledger tip",
            RuntimeMode::ExternallyAnchored,
            AuthorityClass::Operator,
            ClaimProofState::FullChainVerified,
            ClaimCeiling::ExternallyAnchored,
        );
        let weak = ReportableClaim::new(
            "development ledger append",
            RuntimeMode::LocalUnsigned,
            AuthorityClass::Observed,
            ClaimProofState::Partial,
            ClaimCeiling::AuthorityGrade,
        );

        assert_eq!(
            mix_reportable_claims_to_weakest([&strong, &weak]),
            Some(ClaimCeiling::LocalUnsigned)
        );

        let mixed = strong.mix_to_weakest(&weak, "combined claim");
        assert_eq!(mixed.effective_ceiling(), ClaimCeiling::LocalUnsigned);
    }

    #[test]
    fn runtime_mode_wire_strings_are_stable() {
        assert_eq!(
            serde_json::to_value(RuntimeMode::Unknown).unwrap(),
            serde_json::json!("unknown")
        );
        assert_eq!(
            serde_json::to_value(RuntimeMode::Dev).unwrap(),
            serde_json::json!("dev")
        );
        assert_eq!(
            serde_json::to_value(RuntimeMode::RemoteUnsigned).unwrap(),
            serde_json::json!("remote_unsigned")
        );
        assert_eq!(
            serde_json::to_value(RuntimeMode::LocalUnsigned).unwrap(),
            serde_json::json!("local_unsigned")
        );
        assert_eq!(
            serde_json::to_value(RuntimeMode::SignedLocalLedger).unwrap(),
            serde_json::json!("signed_local_ledger")
        );
        assert_eq!(
            serde_json::to_value(RuntimeMode::ExternallyAnchored).unwrap(),
            serde_json::json!("externally_anchored")
        );
        assert_eq!(
            serde_json::to_value(RuntimeMode::AuthorityGrade).unwrap(),
            serde_json::json!("authority_grade")
        );
    }
}