crtx-memory 0.1.1

Memory lifecycle, salience, decay policies, and contradiction objects.
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! Field-level pai-axiom trust exchange admission for Cortex (ADR 0042 / 0043).
//!
//! This module consumes the typed envelopes from
//! `cortex_core::axiom_trust` and runs the admission gate at the
//! decomposed-field granularity. The existing
//! [`crate::admission::AxiomMemoryAdmissionRequest`] still handles the
//! generic ADR 0038 admission envelope; this module is the *receiver-side*
//! field-level enforcement that the pai-axiom P6 acceptance request packet
//! requires.
//!
//! ## Hard structural refusals
//!
//! - `lifecycle != candidate_only` → reject.
//! - `same_loop_promotion_allowed == true` → reject.
//! - `durable_truth_promotion == eligible_after_independent_validation` or
//!   `full_execution_authority == eligible_after_independent_validation` →
//!   reject (Cortex authority limit; ADR 0026 §4 hard wall).
//! - Expired or revoked token → reject.
//! - Missing required field-level contributor → reject.
//!
//! ## Quarantine paths
//!
//! - Quarantined or unknown quarantine state → quarantine with the named
//!   `axiom.admission.quarantine.propagated` invariant.
//! - Derived-from-quarantined per lineage → quarantine.
//! - Target-domain validation required and not `Pass` → quarantine.
//!
//! Every `AdmitCandidate` decision carries an explicit `forbidden_uses`
//! array — Cortex never lets AXIOM evidence imply durable truth.

use chrono::{DateTime, Utc};
use cortex_core::{
    compose_policy_outcomes, ArtifactLifecycleState, AuthorityFeedbackLoop, AxiomExecutionTrust,
    ContextProofStateValue, ContextRedactionStatus, CortexContextTrust, ExecutionPolicyResult,
    NamedQuarantineOutputs, PolicyContribution, PolicyDecision, PolicyOutcome, QuarantineOutput,
    RepoTrustResult, TargetDomainValidationResult, TokenRevocationResult, TrustExchangeFieldError,
};
use serde::{Deserialize, Serialize};

/// Required lifecycle assertion for a pai-axiom trust exchange admission.
///
/// Cortex admits only `candidate_only` — any other lifecycle is a hard
/// structural refusal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AdmissionLifecycle {
    /// Candidate-only admission (the only admissible value).
    CandidateOnly,
    /// Validated lifecycle — not admissible at the Cortex receiver.
    Validated,
    /// Promoted lifecycle — not admissible at the Cortex receiver.
    Promoted,
    /// Stale lifecycle — not admissible at the Cortex receiver.
    Stale,
    /// Quarantined lifecycle — not admissible at the Cortex receiver.
    Quarantined,
    /// Lifecycle missing or unknown — not admissible.
    Unknown,
}

impl AdmissionLifecycle {
    /// Whether this lifecycle is the only admissible value.
    #[must_use]
    pub const fn is_candidate_only(self) -> bool {
        matches!(self, Self::CandidateOnly)
    }
}

/// Cortex-side admission request driven by the pai-axiom trust exchange
/// envelopes (ADR 0042/0043).
#[derive(Debug, Clone, PartialEq)]
pub struct AxiomTrustExchangeAdmissionRequest {
    /// Cortex context trust envelope (when supplied at the boundary).
    pub cortex_context_trust: Option<CortexContextTrust>,
    /// pai-axiom execution trust envelope.
    pub axiom_execution_trust: AxiomExecutionTrust,
    /// Authority feedback loop record (when supplied).
    pub authority_feedback_loop: Option<AuthorityFeedbackLoop>,
    /// Explicit lifecycle assertion supplied by the caller.
    pub lifecycle: AdmissionLifecycle,
    /// Timestamp the admission gate uses as "now" for staleness checks.
    pub now: DateTime<Utc>,
    /// Operator-supplied lineage marker: `true` when an upstream entry
    /// in the artifact's lineage was already `Quarantined`.
    pub derived_from_quarantined: bool,
}

impl AxiomTrustExchangeAdmissionRequest {
    /// Construct a minimal admission request with `now = Utc::now()`.
    #[must_use]
    pub fn new(axiom_execution_trust: AxiomExecutionTrust, lifecycle: AdmissionLifecycle) -> Self {
        Self {
            cortex_context_trust: None,
            axiom_execution_trust,
            authority_feedback_loop: None,
            lifecycle,
            now: Utc::now(),
            derived_from_quarantined: false,
        }
    }

    /// Attach an optional Cortex context trust envelope.
    #[must_use]
    pub fn with_cortex_context_trust(mut self, ctx: CortexContextTrust) -> Self {
        self.cortex_context_trust = Some(ctx);
        self
    }

    /// Attach an optional authority feedback loop record.
    #[must_use]
    pub fn with_authority_feedback_loop(mut self, loop_record: AuthorityFeedbackLoop) -> Self {
        self.authority_feedback_loop = Some(loop_record);
        self
    }

    /// Override the gate's `now` reference (otherwise [`Utc::now`] at
    /// construction time).
    #[must_use]
    pub const fn with_now(mut self, now: DateTime<Utc>) -> Self {
        self.now = now;
        self
    }

    /// Mark this admission request as derived from a quarantined lineage.
    #[must_use]
    pub const fn with_derived_from_quarantined(mut self, derived: bool) -> Self {
        self.derived_from_quarantined = derived;
        self
    }

    /// Compute the deterministic admission decision for this request.
    #[must_use]
    pub fn decide(&self) -> TrustExchangeAdmission {
        let mut rejects: Vec<TrustExchangeFieldError> = Vec::new();
        let mut quarantines: Vec<TrustExchangeFieldError> = Vec::new();
        let mut named_quarantine_outputs = NamedQuarantineOutputs::default();

        // 1. Structural lifecycle gate.
        if !self.lifecycle.is_candidate_only() {
            rejects.push(TrustExchangeFieldError::new(
                "axiom.admission.lifecycle.must_be_candidate_only",
                "Cortex admits pai-axiom trust exchange only as candidate_only",
            ));
        }

        // 2. Structural same-loop refusal.
        if let Some(loop_record) = &self.authority_feedback_loop {
            if loop_record.violates_same_loop_invariant() {
                rejects.push(TrustExchangeFieldError::new(
                    "authority_feedback_loop.same_loop_promotion_must_be_false",
                    "same_loop_promotion_allowed must be false at the Cortex receiver",
                ));
            }
            if loop_record.claims_durable_authority() {
                rejects.push(TrustExchangeFieldError::new(
                    "authority_feedback_loop.authority_claims.over_authorized",
                    "Cortex refuses durable_truth_promotion or full_execution_authority claims",
                ));
            }
        }

        // 3. Field-level validation. Pull errors into reject bucket.
        if let Err(errors) = self.axiom_execution_trust.validate() {
            rejects.extend(errors);
        }
        if let Some(ctx) = &self.cortex_context_trust {
            if let Err(errors) = ctx.validate() {
                rejects.extend(errors);
            }
        }
        if let Some(loop_record) = &self.authority_feedback_loop {
            if let Err(errors) = loop_record.validate() {
                rejects.extend(errors);
            }
        }

        // 4. Quarantine propagation on the cortex_context_trust side.
        if let Some(ctx) = &self.cortex_context_trust {
            if ctx.quarantine_state.propagates_quarantine() {
                let invariant = "axiom.admission.quarantine.propagated".to_string();
                let reason = format!(
                    "cortex_context_trust.quarantine_state == {:?}",
                    ctx.quarantine_state
                );
                quarantines.push(TrustExchangeFieldError::new(
                    invariant.clone(),
                    reason.clone(),
                ));
                named_quarantine_outputs.source_context = Some(
                    QuarantineOutput::new(invariant, reason)
                        .with_source_ref("cortex_context_trust"),
                );
            }
            if matches!(ctx.redaction_state.status, ContextRedactionStatus::Redacted)
                && ctx.redaction_state.blocks_critical_premise.unwrap_or(false)
            {
                quarantines.push(TrustExchangeFieldError::new(
                    "cortex_context_trust.redaction_state.blocks_critical_premise",
                    "redaction removed critical premise; treated as quarantine",
                ));
            }
        }

        // 5. Token revocation and expiry.
        if self
            .axiom_execution_trust
            .token_scope
            .revocation_result
            .must_reject()
        {
            let invariant = match self.axiom_execution_trust.token_scope.revocation_result {
                TokenRevocationResult::Revoked => "axiom_execution_trust.token_scope.revoked",
                TokenRevocationResult::Inactive => "axiom_execution_trust.token_scope.inactive",
                _ => "axiom_execution_trust.token_scope.invalid_state",
            };
            rejects.push(TrustExchangeFieldError::new(
                invariant,
                "capability token must be active for Cortex admission",
            ));
            named_quarantine_outputs.token_revocation = Some(QuarantineOutput::new(
                invariant,
                "capability token must be active for Cortex admission",
            ));
        }
        if self.axiom_execution_trust.token_expired_at(self.now) {
            rejects.push(TrustExchangeFieldError::new(
                "axiom_execution_trust.token_scope.expired",
                "capability token expires_at is in the past for the supplied now",
            ));
            named_quarantine_outputs.token_revocation = Some(QuarantineOutput::new(
                "axiom_execution_trust.token_scope.expired",
                "capability token is expired",
            ));
        }

        // 6. Repo trust.
        if matches!(
            self.axiom_execution_trust.repo_trust.result,
            RepoTrustResult::Untrusted
        ) {
            quarantines.push(TrustExchangeFieldError::new(
                "axiom_execution_trust.repo_trust.untrusted",
                "repo_trust.result == untrusted is propagated as quarantine",
            ));
            named_quarantine_outputs.repo_trust = Some(QuarantineOutput::new(
                "axiom_execution_trust.repo_trust.untrusted",
                "repo trust untrusted",
            ));
        }

        // 7. Policy denial.
        if matches!(
            self.axiom_execution_trust.policy_decision.result,
            ExecutionPolicyResult::Deny
        ) {
            rejects.push(TrustExchangeFieldError::new(
                "axiom_execution_trust.policy_decision.deny",
                "policy_decision.result == deny is a hard receiver refusal",
            ));
            named_quarantine_outputs.policy_denial = Some(QuarantineOutput::new(
                "axiom_execution_trust.policy_decision.deny",
                "policy denied",
            ));
        }

        // 8. Target-domain validation.
        if let Some(loop_record) = &self.authority_feedback_loop {
            if loop_record.target_domain_validation.required
                && !matches!(
                    loop_record.target_domain_validation.result,
                    TargetDomainValidationResult::Pass
                )
            {
                quarantines.push(TrustExchangeFieldError::new(
                    "authority_feedback_loop.target_domain_validation.not_pass",
                    "target_domain_validation.result must be pass for clean admission",
                ));
                named_quarantine_outputs.target_validation = Some(QuarantineOutput::new(
                    "authority_feedback_loop.target_domain_validation.not_pass",
                    "target domain validation not pass",
                ));
            }

            // Derived artifact quarantine.
            if loop_record
                .returned_artifacts
                .iter()
                .any(|a| matches!(a.lifecycle_state, ArtifactLifecycleState::Quarantined))
            {
                quarantines.push(TrustExchangeFieldError::new(
                    "authority_feedback_loop.returned_artifacts.quarantined",
                    "at least one returned artifact lifecycle_state == quarantined",
                ));
                named_quarantine_outputs.derived_artifact = Some(QuarantineOutput::new(
                    "authority_feedback_loop.returned_artifacts.quarantined",
                    "derived artifact quarantined",
                ));
            }

            if loop_record.quarantine_state.propagates_quarantine() {
                quarantines.push(TrustExchangeFieldError::new(
                    "axiom.admission.quarantine.propagated",
                    "authority_feedback_loop.quarantine_state propagates",
                ));
                named_quarantine_outputs.contradiction = Some(QuarantineOutput::new(
                    "axiom.admission.quarantine.propagated",
                    "feedback loop quarantine state",
                ));
            }
        }

        // 9. Operator-supplied lineage hint.
        if self.derived_from_quarantined {
            quarantines.push(TrustExchangeFieldError::new(
                "axiom.admission.quarantine.derived_from_quarantined",
                "operator marked admission lineage as derived_from_quarantined",
            ));
            named_quarantine_outputs.source_context = Some(QuarantineOutput::new(
                "axiom.admission.quarantine.derived_from_quarantined",
                "lineage trace indicates quarantined ancestor",
            ));
        }

        // 10. Cortex context proof state contradicts the loop's quarantine guarantee.
        if let Some(ctx) = &self.cortex_context_trust {
            if matches!(
                ctx.proof_state.state,
                ContextProofStateValue::Failed | ContextProofStateValue::Missing
            ) {
                rejects.push(TrustExchangeFieldError::new(
                    "cortex_context_trust.proof_state.state.unusable",
                    "proof_state.state failed or missing is a hard refusal",
                ));
            }
        }

        let forbidden_uses = forbidden_uses_for_candidate();
        let policy_decision = compose_decision_outcomes(&rejects, &quarantines);

        if !rejects.is_empty() {
            TrustExchangeAdmission::Reject {
                rejects,
                quarantines,
                named_quarantine_outputs,
                policy_decision,
            }
        } else if !quarantines.is_empty() {
            TrustExchangeAdmission::Quarantine {
                quarantines,
                named_quarantine_outputs,
                policy_decision,
                forbidden_uses,
            }
        } else {
            TrustExchangeAdmission::AdmitCandidate {
                forbidden_uses,
                policy_decision,
            }
        }
    }
}

/// Final admission decision for a pai-axiom trust exchange admission.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TrustExchangeAdmission {
    /// Admitted only as a Cortex memory candidate.
    AdmitCandidate {
        /// Authority-bearing uses forbidden on every AdmitCandidate path.
        forbidden_uses: Vec<ForbiddenUse>,
        /// ADR 0026 composed policy decision.
        policy_decision: PolicyDecision,
    },
    /// Quarantine path — record retained but cannot promote.
    Quarantine {
        /// Stable invariant failures triggering quarantine.
        quarantines: Vec<TrustExchangeFieldError>,
        /// Named per-source quarantine outputs (ADR 0042 §7).
        named_quarantine_outputs: NamedQuarantineOutputs,
        /// ADR 0026 composed policy decision.
        policy_decision: PolicyDecision,
        /// Forbidden uses still apply to quarantined records.
        forbidden_uses: Vec<ForbiddenUse>,
    },
    /// Hard refusal — no record retained as candidate.
    Reject {
        /// Stable invariant failures triggering rejection.
        rejects: Vec<TrustExchangeFieldError>,
        /// Co-occurring quarantine signals (for diagnostics only).
        quarantines: Vec<TrustExchangeFieldError>,
        /// Named per-source quarantine outputs (ADR 0042 §7).
        named_quarantine_outputs: NamedQuarantineOutputs,
        /// ADR 0026 composed policy decision.
        policy_decision: PolicyDecision,
    },
}

impl TrustExchangeAdmission {
    /// Stable machine-readable name of the decision branch.
    #[must_use]
    pub const fn decision_name(&self) -> &'static str {
        match self {
            Self::AdmitCandidate { .. } => "admit_candidate",
            Self::Quarantine { .. } => "quarantine",
            Self::Reject { .. } => "reject",
        }
    }

    /// Returns the named quarantine outputs of the decision when present.
    #[must_use]
    pub fn named_quarantine_outputs(&self) -> Option<&NamedQuarantineOutputs> {
        match self {
            Self::AdmitCandidate { .. } => None,
            Self::Quarantine {
                named_quarantine_outputs,
                ..
            }
            | Self::Reject {
                named_quarantine_outputs,
                ..
            } => Some(named_quarantine_outputs),
        }
    }

    /// Returns the composed ADR 0026 policy decision.
    #[must_use]
    pub fn policy_decision(&self) -> &PolicyDecision {
        match self {
            Self::AdmitCandidate {
                policy_decision, ..
            }
            | Self::Quarantine {
                policy_decision, ..
            }
            | Self::Reject {
                policy_decision, ..
            } => policy_decision,
        }
    }

    /// Returns the stable invariant names contributing to this decision.
    #[must_use]
    pub fn invariants(&self) -> Vec<&str> {
        match self {
            Self::AdmitCandidate { .. } => Vec::new(),
            Self::Quarantine { quarantines, .. } => {
                quarantines.iter().map(|e| e.invariant.as_str()).collect()
            }
            Self::Reject {
                rejects,
                quarantines,
                ..
            } => rejects
                .iter()
                .chain(quarantines.iter())
                .map(|e| e.invariant.as_str())
                .collect(),
        }
    }

    /// Returns the `forbidden_uses` carried on candidate or quarantined
    /// records. Always present even on quarantine to preserve the
    /// candidate-only invariant.
    #[must_use]
    pub fn forbidden_uses(&self) -> Option<&[ForbiddenUse]> {
        match self {
            Self::AdmitCandidate { forbidden_uses, .. }
            | Self::Quarantine { forbidden_uses, .. } => Some(forbidden_uses),
            Self::Reject { .. } => None,
        }
    }
}

/// Authority-bearing uses forbidden on every AdmitCandidate path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ForbiddenUse {
    /// Durable promotion to Cortex truth.
    DurablePromotion,
    /// Release acceptance evidence.
    ReleaseAcceptance,
    /// Runtime authority claim.
    RuntimeAuthority,
    /// Cortex truth claim.
    CortexTruth,
    /// Trusted run-history claim.
    TrustedHistory,
}

/// Forbidden uses array attached to every AdmitCandidate / Quarantine
/// decision. Cortex never grants AXIOM evidence durable authority.
#[must_use]
pub fn forbidden_uses_for_candidate() -> Vec<ForbiddenUse> {
    vec![
        ForbiddenUse::DurablePromotion,
        ForbiddenUse::ReleaseAcceptance,
        ForbiddenUse::RuntimeAuthority,
        ForbiddenUse::CortexTruth,
        ForbiddenUse::TrustedHistory,
    ]
}

fn compose_decision_outcomes(
    rejects: &[TrustExchangeFieldError],
    quarantines: &[TrustExchangeFieldError],
) -> PolicyDecision {
    let mut contributions: Vec<PolicyContribution> = Vec::new();
    for err in rejects {
        contributions.push(
            PolicyContribution::new(
                stable_policy_rule_id(&err.invariant),
                PolicyOutcome::Reject,
                err.reason.clone(),
            )
            .expect("stable invariant policy contribution is well-formed"),
        );
    }
    for err in quarantines {
        contributions.push(
            PolicyContribution::new(
                stable_policy_rule_id(&err.invariant),
                PolicyOutcome::Quarantine,
                err.reason.clone(),
            )
            .expect("stable invariant policy contribution is well-formed"),
        );
    }
    if contributions.is_empty() {
        contributions.push(
            PolicyContribution::new(
                "axiom.admission.trust_exchange.allow_candidate",
                PolicyOutcome::Allow,
                "pai-axiom trust exchange admitted as Cortex candidate only",
            )
            .expect("static policy contribution shape is valid"),
        );
    }
    compose_policy_outcomes(contributions, None)
}

fn stable_policy_rule_id(invariant: &str) -> String {
    // Policy rules use the same dot-pathed stable invariant id so operator
    // dashboards can correlate ADR 0026 outcomes with pai-axiom acceptance
    // tests without translation.
    format!("axiom.admission.trust_exchange.{invariant}")
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::TimeZone;
    use cortex_core::{
        parse_axiom_execution_trust, parse_cortex_context_trust, AmplificationRisk,
        ArtifactLifecycleState, AuthorityClaimStatus, ConfidenceCeiling, ContextQuarantineState,
        ExecutionPolicyResult, FeedbackAuthorityClaims, FeedbackAxiomAction,
        FeedbackInitiatingContext, FeedbackReturnedArtifact, RepoTrustResult, ReproducibilityLevel,
        TargetDomainValidation, TargetDomainValidationResult, AUTHORITY_FEEDBACK_LOOP_SCHEMA,
    };

    const VALID_CTX: &str =
        include_str!("../../cortex-core/tests/fixtures/pai-axiom/valid-cortex-context-trust.json");
    const VALID_EXEC: &str =
        include_str!("../../cortex-core/tests/fixtures/pai-axiom/valid-axiom-execution-trust.json");

    fn valid_loop_record() -> AuthorityFeedbackLoop {
        AuthorityFeedbackLoop {
            schema: AUTHORITY_FEEDBACK_LOOP_SCHEMA.to_string(),
            version: 1,
            authority_feedback_loop_ref: Some("loop_ref".to_string()),
            loop_id: "loop_valid".to_string(),
            started_at: Utc.with_ymd_and_hms(2026, 5, 4, 18, 0, 0).unwrap(),
            initiating_context: FeedbackInitiatingContext {
                context_id: "ctx_valid".to_string(),
                cortex_context_trust_ref: "ref://ctx".to_string(),
            },
            axiom_action: FeedbackAxiomAction {
                action_id: "action_valid".to_string(),
                axiom_execution_trust_ref: "ref://exec".to_string(),
            },
            returned_artifacts: vec![FeedbackReturnedArtifact {
                artifact_id: "art_valid".to_string(),
                lineage_ref: "lin_valid".to_string(),
                lifecycle_state: ArtifactLifecycleState::Candidate,
                reproducibility_level: ReproducibilityLevel::Observational,
            }],
            amplification_risk: AmplificationRisk::Low,
            independent_evidence_refs: vec!["evi://ind".to_string()],
            external_grounding_refs: vec!["gnd://ext".to_string()],
            contradiction_scan_ref: "scan_ref".to_string(),
            quarantine_state: ContextQuarantineState::Clear,
            confidence_ceiling: ConfidenceCeiling::Advisory,
            same_loop_promotion_allowed: false,
            authority_claims: FeedbackAuthorityClaims {
                durable_truth_promotion: AuthorityClaimStatus::Denied,
                full_execution_authority: AuthorityClaimStatus::Denied,
                review_required: true,
            },
            target_domain_validation: TargetDomainValidation {
                required: true,
                independent_validation_ref: Some("validation_ref".to_string()),
                result: TargetDomainValidationResult::Pass,
            },
            residual_risk: vec![],
        }
    }

    fn fixed_now() -> DateTime<Utc> {
        Utc.with_ymd_and_hms(2026, 5, 12, 0, 0, 0).unwrap()
    }

    fn valid_request() -> AxiomTrustExchangeAdmissionRequest {
        let exec = parse_axiom_execution_trust(VALID_EXEC).unwrap();
        let ctx = parse_cortex_context_trust(VALID_CTX).unwrap();
        AxiomTrustExchangeAdmissionRequest::new(exec, AdmissionLifecycle::CandidateOnly)
            .with_cortex_context_trust(ctx)
            .with_authority_feedback_loop(valid_loop_record())
            .with_now(fixed_now())
    }

    #[test]
    fn valid_request_admits_candidate_with_forbidden_uses() {
        let decision = valid_request().decide();
        assert_eq!(decision.decision_name(), "admit_candidate");
        let forbidden = decision
            .forbidden_uses()
            .expect("candidate has forbidden_uses");
        assert!(forbidden.contains(&ForbiddenUse::DurablePromotion));
        assert!(forbidden.contains(&ForbiddenUse::ReleaseAcceptance));
        assert!(forbidden.contains(&ForbiddenUse::RuntimeAuthority));
        assert!(forbidden.contains(&ForbiddenUse::CortexTruth));
        assert!(forbidden.contains(&ForbiddenUse::TrustedHistory));
        assert_eq!(
            decision.policy_decision().final_outcome,
            PolicyOutcome::Allow
        );
    }

    #[test]
    fn lifecycle_not_candidate_only_rejects() {
        let exec = parse_axiom_execution_trust(VALID_EXEC).unwrap();
        let req = AxiomTrustExchangeAdmissionRequest::new(exec, AdmissionLifecycle::Validated)
            .with_now(fixed_now());
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "reject");
        assert!(decision
            .invariants()
            .contains(&"axiom.admission.lifecycle.must_be_candidate_only"));
    }

    #[test]
    fn same_loop_promotion_true_rejects_structurally() {
        let mut req = valid_request();
        if let Some(loop_record) = req.authority_feedback_loop.as_mut() {
            loop_record.same_loop_promotion_allowed = true;
        }
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "reject");
        assert!(decision
            .invariants()
            .contains(&"authority_feedback_loop.same_loop_promotion_must_be_false"));
    }

    #[test]
    fn over_authorized_durable_truth_rejects() {
        let mut req = valid_request();
        if let Some(loop_record) = req.authority_feedback_loop.as_mut() {
            loop_record.authority_claims.durable_truth_promotion =
                AuthorityClaimStatus::EligibleAfterIndependentValidation;
        }
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "reject");
        assert!(decision
            .invariants()
            .contains(&"authority_feedback_loop.authority_claims.over_authorized"));
    }

    #[test]
    fn over_authorized_full_execution_authority_rejects() {
        let mut req = valid_request();
        if let Some(loop_record) = req.authority_feedback_loop.as_mut() {
            loop_record.authority_claims.full_execution_authority =
                AuthorityClaimStatus::EligibleAfterIndependentValidation;
        }
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "reject");
        assert!(decision
            .invariants()
            .contains(&"authority_feedback_loop.authority_claims.over_authorized"));
    }

    #[test]
    fn quarantine_state_propagated_quarantines() {
        let mut req = valid_request();
        req.cortex_context_trust
            .as_mut()
            .expect("ctx present")
            .quarantine_state = ContextQuarantineState::Quarantined;
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "quarantine");
        assert!(decision
            .invariants()
            .contains(&"axiom.admission.quarantine.propagated"));
        let outputs = decision.named_quarantine_outputs().unwrap();
        assert!(outputs.source_context.is_some());
        // Quarantine path STILL carries forbidden uses.
        assert!(decision
            .forbidden_uses()
            .unwrap()
            .contains(&ForbiddenUse::DurablePromotion));
    }

    #[test]
    fn derived_from_quarantined_quarantines() {
        let req = valid_request().with_derived_from_quarantined(true);
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "quarantine");
        assert!(decision
            .invariants()
            .contains(&"axiom.admission.quarantine.derived_from_quarantined"));
    }

    #[test]
    fn target_domain_validation_not_pass_quarantines() {
        let mut req = valid_request();
        if let Some(loop_record) = req.authority_feedback_loop.as_mut() {
            loop_record.target_domain_validation.result = TargetDomainValidationResult::Fail;
        }
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "quarantine");
        assert!(decision
            .invariants()
            .contains(&"authority_feedback_loop.target_domain_validation.not_pass"));
    }

    #[test]
    fn expired_token_rejects() {
        let mut req = valid_request();
        req.axiom_execution_trust.token_scope.expires_at =
            Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "reject");
        assert!(decision
            .invariants()
            .contains(&"axiom_execution_trust.token_scope.expired"));
    }

    #[test]
    fn revoked_token_rejects() {
        let mut req = valid_request();
        req.axiom_execution_trust.token_scope.revocation_result = TokenRevocationResult::Revoked;
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "reject");
        assert!(decision
            .invariants()
            .contains(&"axiom_execution_trust.token_scope.revoked"));
    }

    #[test]
    fn inactive_token_rejects() {
        let mut req = valid_request();
        req.axiom_execution_trust.token_scope.revocation_result = TokenRevocationResult::Inactive;
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "reject");
        assert!(decision
            .invariants()
            .contains(&"axiom_execution_trust.token_scope.inactive"));
    }

    #[test]
    fn untrusted_repo_quarantines() {
        let mut req = valid_request();
        req.axiom_execution_trust.repo_trust.result = RepoTrustResult::Untrusted;
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "quarantine");
        assert!(decision
            .invariants()
            .contains(&"axiom_execution_trust.repo_trust.untrusted"));
    }

    #[test]
    fn deny_policy_rejects() {
        let mut req = valid_request();
        req.axiom_execution_trust.policy_decision.result = ExecutionPolicyResult::Deny;
        let decision = req.decide();
        assert_eq!(decision.decision_name(), "reject");
        assert!(decision
            .invariants()
            .contains(&"axiom_execution_trust.policy_decision.deny"));
    }
}