crtx-runtime 0.1.0

Child agent execution, tool/process wrapper, and run capture.
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
//! Runtime claim compiler for truth-ceiling enforcement.

use cortex_core::{
    AuthorityClass, ClaimCeiling, ClaimProofState, PolicyDecision, PolicyOutcome, ReportableClaim,
    RuntimeMode,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Runtime claim class with a minimum authority ceiling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RuntimeClaimKind {
    /// Diagnostic claim about a local failure or unknown.
    Diagnostic,
    /// Advisory local claim.
    Advisory,
    /// Trusted run-history claim.
    TrustedHistory,
    /// Export authority claim.
    Export,
    /// Promotion or durable authority claim.
    Promotion,
    /// Release-readiness claim.
    ReleaseReadiness,
    /// Compliance evidence claim.
    ComplianceEvidence,
    /// Cross-system trust decision claim.
    CrossSystemTrust,
}

impl RuntimeClaimKind {
    /// Minimum effective ceiling needed to emit this claim affirmatively.
    #[must_use]
    pub const fn required_ceiling(self) -> ClaimCeiling {
        match self {
            Self::Diagnostic | Self::Advisory => ClaimCeiling::DevOnly,
            Self::TrustedHistory => ClaimCeiling::SignedLocalLedger,
            Self::Export => ClaimCeiling::ExternallyAnchored,
            Self::Promotion
            | Self::ReleaseReadiness
            | Self::ComplianceEvidence
            | Self::CrossSystemTrust => ClaimCeiling::AuthorityGrade,
        }
    }
}

/// Compiled runtime claim with weakest-link ceiling and allow/deny decision.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompiledRuntimeClaim {
    /// Claim text.
    pub claim: String,
    /// Runtime claim kind.
    pub kind: RuntimeClaimKind,
    /// Runtime mode supplied by the caller.
    pub runtime_mode: RuntimeMode,
    /// Authority class supplied by the caller.
    pub authority_class: AuthorityClass,
    /// Proof state supplied by proof closure.
    pub proof_state: ClaimProofState,
    /// Requested claim ceiling.
    pub requested_ceiling: ClaimCeiling,
    /// Effective weakest-link ceiling.
    pub effective_ceiling: ClaimCeiling,
    /// Minimum ceiling for this claim kind.
    pub required_ceiling: ClaimCeiling,
    /// Whether the claim may be emitted affirmatively.
    pub allowed: bool,
    /// Downgrade or denial reasons.
    pub reasons: Vec<String>,
}

/// Use requested for development-ledger data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DevelopmentLedgerUse {
    /// Local diagnostic inspection by the operator.
    LocalDiagnostic,
    /// Audit export artifact.
    AuditExport,
    /// Compliance evidence generation.
    ComplianceEvidence,
    /// Cross-system trust decision.
    CrossSystemTrustDecision,
    /// External reporting.
    ExternalReporting,
}

impl DevelopmentLedgerUse {
    /// Stable payload string for this use.
    #[must_use]
    pub const fn wire_str(self) -> &'static str {
        match self {
            Self::LocalDiagnostic => "local_diagnostic",
            Self::AuditExport => "audit_export",
            Self::ComplianceEvidence => "compliance_evidence",
            Self::CrossSystemTrustDecision => "cross_system_trust_decision",
            Self::ExternalReporting => "external_reporting",
        }
    }
}

/// Decision for using one event payload in a requested authority surface.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DevelopmentLedgerUseDecision {
    /// Requested use.
    pub requested_use: DevelopmentLedgerUse,
    /// Whether this event payload may be used for that surface.
    pub allowed: bool,
    /// Decision reason.
    pub reason: String,
}

/// Fail-closed decision for a proof-bearing runtime claim surface.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuntimeClaimPreflight {
    /// Compiled claim evidence and weakest-link ceiling.
    pub claim: CompiledRuntimeClaim,
    /// Whether the requested surface may proceed.
    pub allowed: bool,
    /// Operator-facing decision reason.
    pub reason: String,
}

/// Decides whether a run-event payload may be used for the requested surface.
#[must_use]
pub fn development_ledger_use_decision(
    payload: &Value,
    requested_use: DevelopmentLedgerUse,
) -> DevelopmentLedgerUseDecision {
    let ledger_authority = payload.get("ledger_authority").and_then(Value::as_str);
    let signed_ledger_authority = payload
        .get("signed_ledger_authority")
        .and_then(Value::as_bool);
    let forbidden = payload
        .get("forbidden_uses")
        .and_then(Value::as_array)
        .is_some_and(|uses| {
            uses.iter()
                .any(|value| value.as_str() == Some(requested_use.wire_str()))
        });
    if requested_use == DevelopmentLedgerUse::LocalDiagnostic {
        return DevelopmentLedgerUseDecision {
            requested_use,
            allowed: true,
            reason: "local diagnostics do not upgrade development-ledger authority".into(),
        };
    }

    if forbidden {
        DevelopmentLedgerUseDecision {
            requested_use,
            allowed: false,
            reason: format!("ledger data is forbidden for {}", requested_use.wire_str()),
        }
    } else if ledger_authority == Some("development") || signed_ledger_authority == Some(false) {
        DevelopmentLedgerUseDecision {
            requested_use,
            allowed: false,
            reason: format!(
                "development-ledger data is forbidden for {}",
                requested_use.wire_str()
            ),
        }
    } else if ledger_authority == Some("signed_local")
        || (signed_ledger_authority == Some(true)
            && !matches!(
                ledger_authority,
                Some("externally_anchored" | "authority_grade")
            ))
    {
        DevelopmentLedgerUseDecision {
            requested_use,
            allowed: false,
            reason: format!(
                "signed-local ledger data is forbidden for {} without external authority",
                requested_use.wire_str()
            ),
        }
    } else {
        DevelopmentLedgerUseDecision {
            requested_use,
            allowed: true,
            reason: "payload does not declare this requested use as forbidden".into(),
        }
    }
}

/// Compile a runtime claim and decide whether it may be emitted affirmatively.
#[must_use]
pub fn compile_runtime_claim(
    claim: impl Into<String>,
    kind: RuntimeClaimKind,
    runtime_mode: RuntimeMode,
    authority_class: AuthorityClass,
    proof_state: ClaimProofState,
    requested_ceiling: ClaimCeiling,
) -> CompiledRuntimeClaim {
    let reportable = ReportableClaim::new(
        claim,
        runtime_mode,
        authority_class,
        proof_state,
        requested_ceiling,
    );
    let required_ceiling = kind.required_ceiling();
    let effective_ceiling = reportable.effective_ceiling();
    let allowed = effective_ceiling >= required_ceiling;
    let mut reasons = reportable.downgrade_reasons().to_vec();
    if !allowed {
        reasons.push(format!(
            "{kind:?} requires {required_ceiling:?}, but effective ceiling is {effective_ceiling:?}"
        ));
    }

    CompiledRuntimeClaim {
        claim: reportable.claim().to_string(),
        kind,
        runtime_mode: reportable.runtime_mode(),
        authority_class: reportable.authority_class(),
        proof_state: reportable.proof_state(),
        requested_ceiling: reportable.requested_ceiling(),
        effective_ceiling,
        required_ceiling,
        allowed,
        reasons,
    }
}

/// Preflight a proof-bearing runtime claim before a command emits, exports, or
/// persists an authority-bearing result.
#[must_use]
pub fn runtime_claim_preflight(
    claim: impl Into<String>,
    kind: RuntimeClaimKind,
    runtime_mode: RuntimeMode,
    authority_class: AuthorityClass,
    proof_state: ClaimProofState,
    requested_ceiling: ClaimCeiling,
) -> RuntimeClaimPreflight {
    let compiled = compile_runtime_claim(
        claim,
        kind,
        runtime_mode,
        authority_class,
        proof_state,
        requested_ceiling,
    );
    let reason = if compiled.allowed {
        let effective_ceiling = compiled.effective_ceiling;
        format!("{kind:?} allowed at effective ceiling {effective_ceiling:?}")
    } else {
        compiled.reasons.last().cloned().unwrap_or_else(|| {
            let effective_ceiling = compiled.effective_ceiling;
            let required_ceiling = compiled.required_ceiling;
            format!("{kind:?} denied because effective ceiling {effective_ceiling:?} is below required {required_ceiling:?}")
        })
    };

    RuntimeClaimPreflight {
        allowed: compiled.allowed,
        claim: compiled,
        reason,
    }
}

/// Preflight a proof-bearing runtime claim and include an ADR 0026 policy
/// decision in the ceiling computation.
#[must_use]
pub fn runtime_claim_preflight_with_policy(
    claim: impl Into<String>,
    kind: RuntimeClaimKind,
    runtime_mode: RuntimeMode,
    authority_class: AuthorityClass,
    proof_state: ClaimProofState,
    requested_ceiling: ClaimCeiling,
    policy: &PolicyDecision,
) -> RuntimeClaimPreflight {
    let mut preflight = runtime_claim_preflight(
        claim,
        kind,
        runtime_mode,
        authority_class,
        proof_state,
        requested_ceiling,
    );
    let policy_ceiling = policy.final_outcome.claim_ceiling();
    if policy_ceiling < preflight.claim.effective_ceiling {
        preflight.claim.effective_ceiling = policy_ceiling;
        let final_outcome = policy.final_outcome;
        preflight.claim.reasons.push(format!(
            "policy outcome {final_outcome:?} limits authority claims"
        ));
    }
    if matches!(
        policy.final_outcome,
        PolicyOutcome::Reject | PolicyOutcome::Quarantine
    ) {
        preflight.allowed = false;
        let final_outcome = policy.final_outcome;
        preflight.reason = format!("policy outcome {final_outcome:?} fails closed for {kind:?}");
    } else {
        preflight.allowed = preflight.claim.effective_ceiling >= preflight.claim.required_ceiling;
        if !preflight.allowed {
            let required_ceiling = preflight.claim.required_ceiling;
            let effective_ceiling = preflight.claim.effective_ceiling;
            preflight.reason = format!(
                "{kind:?} requires {required_ceiling:?}, but effective ceiling is {effective_ceiling:?}"
            );
        }
    }
    preflight
}

/// Return an error message when a proof-bearing claim cannot satisfy its
/// requested authority surface.
pub fn require_runtime_claim(
    claim: impl Into<String>,
    kind: RuntimeClaimKind,
    runtime_mode: RuntimeMode,
    authority_class: AuthorityClass,
    proof_state: ClaimProofState,
    requested_ceiling: ClaimCeiling,
) -> Result<RuntimeClaimPreflight, RuntimeClaimPreflight> {
    let preflight = runtime_claim_preflight(
        claim,
        kind,
        runtime_mode,
        authority_class,
        proof_state,
        requested_ceiling,
    );
    if preflight.allowed {
        Ok(preflight)
    } else {
        Err(preflight)
    }
}

/// Return an error when policy or proof/runtime ceilings cannot satisfy the
/// requested authority surface.
pub fn require_runtime_claim_with_policy(
    claim: impl Into<String>,
    kind: RuntimeClaimKind,
    runtime_mode: RuntimeMode,
    authority_class: AuthorityClass,
    proof_state: ClaimProofState,
    requested_ceiling: ClaimCeiling,
    policy: &PolicyDecision,
) -> Result<RuntimeClaimPreflight, RuntimeClaimPreflight> {
    let preflight = runtime_claim_preflight_with_policy(
        claim,
        kind,
        runtime_mode,
        authority_class,
        proof_state,
        requested_ceiling,
        policy,
    );
    if preflight.allowed {
        Ok(preflight)
    } else {
        Err(preflight)
    }
}

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

    #[test]
    fn dev_fixture_cannot_emit_release_claim() {
        let claim = compile_runtime_claim(
            "ready for release",
            RuntimeClaimKind::ReleaseReadiness,
            RuntimeMode::Dev,
            AuthorityClass::Operator,
            ClaimProofState::FullChainVerified,
            ClaimCeiling::AuthorityGrade,
        );

        assert!(!claim.allowed);
        assert_eq!(claim.effective_ceiling, ClaimCeiling::DevOnly);
        assert!(claim
            .reasons
            .iter()
            .any(|reason| reason.contains("ReleaseReadiness requires AuthorityGrade")));
    }

    #[test]
    fn local_unsigned_run_cannot_emit_trusted_history() {
        let claim = compile_runtime_claim(
            "trusted run history",
            RuntimeClaimKind::TrustedHistory,
            RuntimeMode::LocalUnsigned,
            AuthorityClass::Operator,
            ClaimProofState::FullChainVerified,
            ClaimCeiling::AuthorityGrade,
        );

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

    #[test]
    fn unknown_runtime_cannot_emit_authority_claims() {
        for kind in [
            RuntimeClaimKind::Promotion,
            RuntimeClaimKind::TrustedHistory,
            RuntimeClaimKind::Export,
            RuntimeClaimKind::ComplianceEvidence,
            RuntimeClaimKind::ReleaseReadiness,
            RuntimeClaimKind::CrossSystemTrust,
        ] {
            let claim = compile_runtime_claim(
                "authority claim",
                kind,
                RuntimeMode::Unknown,
                AuthorityClass::Operator,
                ClaimProofState::FullChainVerified,
                ClaimCeiling::AuthorityGrade,
            );

            assert!(!claim.allowed, "{kind:?} must fail in unknown runtime");
            assert_eq!(claim.effective_ceiling, ClaimCeiling::DevOnly);
        }
    }

    #[test]
    fn signed_full_chain_can_emit_trusted_history() {
        let claim = compile_runtime_claim(
            "trusted run history",
            RuntimeClaimKind::TrustedHistory,
            RuntimeMode::SignedLocalLedger,
            AuthorityClass::Verified,
            ClaimProofState::FullChainVerified,
            ClaimCeiling::SignedLocalLedger,
        );

        assert!(claim.allowed);
        assert_eq!(claim.effective_ceiling, ClaimCeiling::SignedLocalLedger);
    }

    #[test]
    fn preflight_fails_closed_for_authority_surfaces_above_ceiling() {
        for kind in [
            RuntimeClaimKind::ReleaseReadiness,
            RuntimeClaimKind::Export,
            RuntimeClaimKind::Promotion,
            RuntimeClaimKind::ComplianceEvidence,
        ] {
            let preflight = runtime_claim_preflight(
                "authority surface",
                kind,
                RuntimeMode::LocalUnsigned,
                AuthorityClass::Observed,
                ClaimProofState::Partial,
                ClaimCeiling::AuthorityGrade,
            );

            assert!(!preflight.allowed, "{kind:?} must fail closed");
            assert_eq!(
                preflight.claim.effective_ceiling,
                ClaimCeiling::LocalUnsigned
            );
            assert!(
                preflight.reason.contains("requires")
                    || preflight.reason.contains("below required"),
                "preflight reason should explain the ceiling failure"
            );
        }
    }

    #[test]
    fn preflight_allows_promotion_only_at_authority_grade() {
        let preflight = runtime_claim_preflight(
            "attested doctrine promotion",
            RuntimeClaimKind::Promotion,
            RuntimeMode::AuthorityGrade,
            AuthorityClass::Operator,
            ClaimProofState::FullChainVerified,
            ClaimCeiling::AuthorityGrade,
        );

        assert!(preflight.allowed);
        assert_eq!(
            preflight.claim.effective_ceiling,
            ClaimCeiling::AuthorityGrade
        );
    }

    #[test]
    fn policy_reject_and_quarantine_downgrade_claim_preflight() {
        for outcome in [PolicyOutcome::Reject, PolicyOutcome::Quarantine] {
            let policy = PolicyDecision {
                final_outcome: outcome,
                contributing: Vec::new(),
                discarded: Vec::new(),
                break_glass: None,
            };
            let preflight = runtime_claim_preflight_with_policy(
                "trusted export",
                RuntimeClaimKind::Export,
                RuntimeMode::ExternallyAnchored,
                AuthorityClass::Operator,
                ClaimProofState::FullChainVerified,
                ClaimCeiling::ExternallyAnchored,
                &policy,
            );

            assert!(!preflight.allowed);
            assert_eq!(preflight.claim.effective_ceiling, ClaimCeiling::DevOnly);
            assert!(preflight.reason.contains("policy outcome"));
        }
    }

    #[test]
    fn policy_warn_does_not_soften_ceiling_failure() {
        let policy = PolicyDecision {
            final_outcome: PolicyOutcome::Warn,
            contributing: Vec::new(),
            discarded: Vec::new(),
            break_glass: None,
        };
        let preflight = runtime_claim_preflight_with_policy(
            "trusted history",
            RuntimeClaimKind::TrustedHistory,
            RuntimeMode::LocalUnsigned,
            AuthorityClass::Observed,
            ClaimProofState::Partial,
            ClaimCeiling::AuthorityGrade,
            &policy,
        );

        assert!(!preflight.allowed);
        assert_eq!(
            preflight.claim.effective_ceiling,
            ClaimCeiling::LocalUnsigned
        );
    }

    #[test]
    fn development_ledger_denies_all_forbidden_external_uses() {
        let payload = serde_json::json!({
            "ledger_authority": "development",
            "signed_ledger_authority": false,
            "forbidden_uses": [
                "audit_export",
                "compliance_evidence",
                "cross_system_trust_decision",
                "external_reporting"
            ]
        });

        for requested_use in [
            DevelopmentLedgerUse::AuditExport,
            DevelopmentLedgerUse::ComplianceEvidence,
            DevelopmentLedgerUse::CrossSystemTrustDecision,
            DevelopmentLedgerUse::ExternalReporting,
        ] {
            let decision = development_ledger_use_decision(&payload, requested_use);
            assert!(
                !decision.allowed,
                "{requested_use:?} should be forbidden for development ledger"
            );
        }
    }

    #[test]
    fn development_ledger_allows_local_diagnostic_only() {
        let payload = serde_json::json!({
            "ledger_authority": "development",
            "signed_ledger_authority": false,
            "forbidden_uses": ["audit_export"]
        });

        let decision =
            development_ledger_use_decision(&payload, DevelopmentLedgerUse::LocalDiagnostic);

        assert!(decision.allowed);
        assert!(decision.reason.contains("do not upgrade"));
    }

    #[test]
    fn externally_anchored_payload_is_not_blocked_by_ledger_gate() {
        let payload = serde_json::json!({
            "ledger_authority": "externally_anchored",
            "signed_ledger_authority": true,
            "forbidden_uses": []
        });

        let decision = development_ledger_use_decision(&payload, DevelopmentLedgerUse::AuditExport);

        assert!(decision.allowed);
    }

    #[test]
    fn signed_local_payload_still_honors_explicit_forbidden_uses() {
        let payload = serde_json::json!({
            "ledger_authority": "signed_local",
            "signed_ledger_authority": true,
            "trusted_run_history": true,
            "forbidden_uses": ["audit_export", "compliance_evidence"]
        });

        let audit = development_ledger_use_decision(&payload, DevelopmentLedgerUse::AuditExport);
        let compliance =
            development_ledger_use_decision(&payload, DevelopmentLedgerUse::ComplianceEvidence);
        let local =
            development_ledger_use_decision(&payload, DevelopmentLedgerUse::LocalDiagnostic);

        assert!(!audit.allowed);
        assert!(!compliance.allowed);
        assert!(local.allowed);
    }

    #[test]
    fn signed_local_payload_cannot_be_used_for_external_surfaces_without_forbidden_uses() {
        let payload = serde_json::json!({
            "ledger_authority": "signed_local",
            "signed_ledger_authority": true,
            "trusted_run_history": true
        });

        for requested_use in [
            DevelopmentLedgerUse::AuditExport,
            DevelopmentLedgerUse::ComplianceEvidence,
            DevelopmentLedgerUse::CrossSystemTrustDecision,
            DevelopmentLedgerUse::ExternalReporting,
        ] {
            let decision = development_ledger_use_decision(&payload, requested_use);
            assert!(
                !decision.allowed,
                "{requested_use:?} should be forbidden for signed-local ledger"
            );
            assert!(
                decision.reason.contains("signed-local ledger"),
                "reason should name signed-local boundary: {}",
                decision.reason
            );
        }
    }
}