crtx-reflect 0.1.1

Reflection orchestration, prompts, candidate parsing, and schema validation.
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
//! Reflection-to-memory admission checks.
//!
//! Reflection can propose Cortex memories, but it cannot bypass the memory
//! admission boundary. Valid reflection JSON is still treated as an evidence
//! submission until the deterministic admission request admits it as a
//! candidate-only memory.

use std::fmt;

use cortex_core::ProofState as CoreProofState;
use cortex_memory::{
    AdmissionDecision, AdmissionProofState, AdmissionRejectionReason, AxiomImportClass,
    AxiomMemoryAdmissionRequest, CandidateState, ContradictionScan, DurableAdmissionRefusal,
    EvidenceClass, PhaseContext, RedactionStatus, SourceAnchor, SourceAnchorKind, ToolProvenance,
    AXIOM_ADMISSION_PROOF_CLOSURE_INVARIANT,
};

use crate::schema::{MemoryCandidate, SessionReflection};

/// Stable invariant key surfaced when the reflection durable-write gate
/// refuses durable promotion because the typed cross-axis
/// [`cortex_core::ProofClosureReport`] for at least one reflected memory
/// is not [`cortex_core::ProofState::FullChainVerified`].
///
/// ADR 0036 forbids reflection-origin candidate creation to land as a
/// durable write when the proof closure is `Partial`, `Broken`, or
/// `Unknown`. The reflect admission layer fails closed before any
/// orchestrator routes the reflection to a durable persistence surface.
pub const REFLECTION_ADMISSION_PROOF_CLOSURE_INVARIANT: &str =
    "cortex_reflect.admission.proof_closure";

/// Reflection admission outcome for non-admitted memory candidates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReflectionAdmissionDisposition {
    /// The candidate is unsafe to retain as a reflection memory.
    Reject,
    /// The candidate is not admissible, but the raw reflection should be retained.
    Quarantine,
}

impl fmt::Display for ReflectionAdmissionDisposition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Reject => f.write_str("reject"),
            Self::Quarantine => f.write_str("quarantine"),
        }
    }
}

/// Admission failure for one reflected memory candidate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReflectionAdmissionError {
    /// Zero-based index into `SessionReflection::memory_candidates`.
    pub memory_index: usize,
    /// Whether the gate rejected or quarantined the candidate.
    pub disposition: ReflectionAdmissionDisposition,
    /// Deterministic admission reasons.
    pub reasons: Vec<AdmissionRejectionReason>,
}

impl fmt::Display for ReflectionAdmissionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let memory_index = self.memory_index;
        let disposition = self.disposition;
        let reasons = &self.reasons;
        write!(
            f,
            "memory_candidates[{memory_index}] admission {disposition}: {reasons:?}"
        )
    }
}

impl std::error::Error for ReflectionAdmissionError {}

/// Validate that every reflected memory candidate can enter Cortex only as a
/// candidate admitted by the AXIOM-to-Cortex memory gate.
pub fn validate_reflection_admission(
    reflection: &SessionReflection,
    adapter_id: &str,
    raw_hash: &str,
) -> Result<(), ReflectionAdmissionError> {
    for (memory_index, memory) in reflection.memory_candidates.iter().enumerate() {
        let request = admission_request_for_memory(reflection, memory, adapter_id, raw_hash);
        match request.admission_decision() {
            AdmissionDecision::AdmitCandidate => {}
            AdmissionDecision::Reject { reasons } => {
                return Err(ReflectionAdmissionError {
                    memory_index,
                    disposition: ReflectionAdmissionDisposition::Reject,
                    reasons,
                });
            }
            AdmissionDecision::Quarantine { reasons } => {
                return Err(ReflectionAdmissionError {
                    memory_index,
                    disposition: ReflectionAdmissionDisposition::Quarantine,
                    reasons,
                });
            }
        }
    }

    Ok(())
}

/// Refusal returned by [`require_reflection_durable_admission_allowed`].
///
/// Carries the index of the memory candidate that failed the durable-write
/// gate plus the underlying [`DurableAdmissionRefusal`] from the AXIOM
/// admission proof-closure check. The stable invariant
/// [`REFLECTION_ADMISSION_PROOF_CLOSURE_INVARIANT`] is surfaced in the
/// `Display` impl so log lines can be grepped for the invariant key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReflectionDurableAdmissionRefusal {
    /// Zero-based index into `SessionReflection::memory_candidates`.
    pub memory_index: usize,
    /// AXIOM admission durable refusal carrying the observed proof state.
    pub axiom_refusal: DurableAdmissionRefusal,
}

impl fmt::Display for ReflectionDurableAdmissionRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let memory_index = self.memory_index;
        let axiom_refusal = &self.axiom_refusal;
        write!(
            f,
            "invariant={REFLECTION_ADMISSION_PROOF_CLOSURE_INVARIANT} memory_candidates[{memory_index}] {axiom_refusal}"
        )
    }
}

impl std::error::Error for ReflectionDurableAdmissionRefusal {}

/// ADR 0036 fail-closed gate at the reflection durable-write boundary.
///
/// `validate_reflection_admission` answers "is this reflection's memory
/// candidate set safe to retain as a candidate?". The durable gate
/// answers the *stronger* question "is the typed cross-axis proof closure
/// for each candidate fully verified, so the orchestrator may promote it
/// to a durable write?".
///
/// Returns `Ok(())` only when every reflected memory's
/// [`AxiomMemoryAdmissionRequest::require_durable_admission_allowed`]
/// passes. On first failure, returns
/// [`ReflectionDurableAdmissionRefusal`] carrying the failing memory
/// index. The stable invariant
/// [`REFLECTION_ADMISSION_PROOF_CLOSURE_INVARIANT`] documents the gate
/// for downstream consumers.
///
/// The print boundary (read-only diagnostic surfaces that render
/// reflection JSON without persisting) is intentionally **not** gated
/// here — only callers that perform a durable write of the reflected
/// memory candidates should invoke this function.
pub fn require_reflection_durable_admission_allowed(
    reflection: &SessionReflection,
    adapter_id: &str,
    raw_hash: &str,
) -> Result<(), ReflectionDurableAdmissionRefusal> {
    for (memory_index, memory) in reflection.memory_candidates.iter().enumerate() {
        let request = admission_request_for_memory(reflection, memory, adapter_id, raw_hash);
        if let Err(axiom_refusal) = request.require_durable_admission_allowed() {
            return Err(ReflectionDurableAdmissionRefusal {
                memory_index,
                axiom_refusal,
            });
        }
    }
    Ok(())
}

/// Return the observed [`CoreProofState`] for the reflected memory at
/// `memory_index`. Useful for surfaces that want to record the proof
/// state on a refusal without re-running the admission request builder.
#[must_use]
pub fn reflection_memory_proof_state(
    reflection: &SessionReflection,
    memory_index: usize,
    adapter_id: &str,
    raw_hash: &str,
) -> Option<CoreProofState> {
    let memory = reflection.memory_candidates.get(memory_index)?;
    let request = admission_request_for_memory(reflection, memory, adapter_id, raw_hash);
    Some(request.proof_closure_report().state())
}

/// Re-export of the upstream stable invariant key for callers that want
/// to grep for either the reflection-level or the upstream AXIOM-level
/// invariant.
#[must_use]
pub const fn axiom_admission_proof_closure_invariant() -> &'static str {
    AXIOM_ADMISSION_PROOF_CLOSURE_INVARIANT
}

/// Build the deterministic admission request for one reflected memory.
#[must_use]
pub fn admission_request_for_memory(
    reflection: &SessionReflection,
    memory: &MemoryCandidate,
    adapter_id: &str,
    raw_hash: &str,
) -> AxiomMemoryAdmissionRequest {
    let source_anchors = source_anchors_for_memory(reflection, memory);
    let proof_state = if source_anchors.is_empty() {
        AdmissionProofState::Unknown
    } else {
        AdmissionProofState::Partial
    };

    AxiomMemoryAdmissionRequest {
        candidate_state: CandidateState::Candidate,
        evidence_class: EvidenceClass::Inferred,
        phase_context: PhaseContext::Check,
        tool_provenance: ToolProvenance::new(
            format!("cortex-reflect:{adapter_id}"),
            raw_hash,
            AxiomImportClass::AgentProcedure,
        ),
        source_anchors,
        redaction_status: RedactionStatus::Abstracted,
        proof_state,
        contradiction_scan: contradiction_scan_for_reflection(reflection),
        explicit_non_promotion: true,
    }
}

fn source_anchors_for_memory(
    reflection: &SessionReflection,
    memory: &MemoryCandidate,
) -> Vec<SourceAnchor> {
    memory
        .source_episode_indexes
        .iter()
        .filter_map(|idx| reflection.episode_candidates.get(*idx))
        .flat_map(|episode| &episode.source_event_ids)
        .map(|event_id| SourceAnchor::new(event_id.to_string(), SourceAnchorKind::Event))
        .collect()
}

fn contradiction_scan_for_reflection(reflection: &SessionReflection) -> ContradictionScan {
    if reflection.contradictions.is_empty() {
        ContradictionScan::ScannedClean
    } else {
        ContradictionScan::OpenContradictions(
            reflection
                .contradictions
                .iter()
                .enumerate()
                .map(|(idx, _)| format!("reflection.contradictions[{idx}]"))
                .collect(),
        )
    }
}

#[cfg(test)]
mod tests {
    use cortex_core::TraceId;
    use cortex_memory::{AdmissionDecision, AdmissionRejectionReason};

    use super::*;
    use crate::schema::{EpisodeCandidate, InitialSalience, MemoryType};

    fn valid_reflection() -> SessionReflection {
        SessionReflection {
            trace_id: "trc_01ARZ3NDEKTSV4RRFFQ69G5FAV"
                .parse::<TraceId>()
                .expect("valid trace id"),
            episode_candidates: vec![EpisodeCandidate {
                summary: "Reflection summary".to_string(),
                source_event_ids: vec!["evt_01ARZ3NDEKTSV4RRFFQ69G5FAV"
                    .parse()
                    .expect("valid event id")],
                domains: vec!["agents".to_string()],
                entities: vec!["Cortex".to_string()],
                candidate_meaning: Some("candidate meaning".to_string()),
                confidence: 0.8,
            }],
            memory_candidates: vec![MemoryCandidate {
                memory_type: MemoryType::Strategic,
                claim: "Reflection memory remains candidate-only.".to_string(),
                source_episode_indexes: vec![0],
                applies_when: vec!["reflecting".to_string()],
                does_not_apply_when: vec!["promoting".to_string()],
                confidence: 0.8,
                initial_salience: InitialSalience {
                    reusability: 0.5,
                    consequence: 0.5,
                    emotional_charge: 0.0,
                },
            }],
            contradictions: Vec::new(),
            doctrine_suggestions: Vec::new(),
        }
    }

    #[test]
    fn reflected_memory_builds_candidate_only_admission_request() {
        let reflection = valid_reflection();
        let request = admission_request_for_memory(
            &reflection,
            &reflection.memory_candidates[0],
            "fixed",
            "hash_01",
        );

        assert_eq!(request.candidate_state, CandidateState::Candidate);
        assert_eq!(request.evidence_class, EvidenceClass::Inferred);
        assert_eq!(request.phase_context, PhaseContext::Check);
        assert_eq!(request.redaction_status, RedactionStatus::Abstracted);
        assert_eq!(request.proof_state, AdmissionProofState::Partial);
        assert!(request.explicit_non_promotion);
        assert_eq!(request.source_anchors.len(), 1);
        assert_eq!(
            request.admission_decision(),
            AdmissionDecision::AdmitCandidate
        );
    }

    #[test]
    fn reflected_memory_without_source_anchor_fails_admission() {
        let mut reflection = valid_reflection();
        reflection.episode_candidates[0].source_event_ids.clear();

        let err = validate_reflection_admission(&reflection, "fixed", "hash_01")
            .expect_err("missing anchors must fail admission");

        assert_eq!(err.memory_index, 0);
        assert_eq!(err.disposition, ReflectionAdmissionDisposition::Reject);
        assert!(err
            .reasons
            .contains(&AdmissionRejectionReason::SourceAnchorRequired));
        assert!(err
            .reasons
            .contains(&AdmissionRejectionReason::ProofStateRequired));
    }

    #[test]
    fn reflected_memory_with_open_contradiction_is_quarantined() {
        let mut reflection = valid_reflection();
        reflection
            .contradictions
            .push(serde_json::json!({"claim": "conflict"}));

        let err = validate_reflection_admission(&reflection, "fixed", "hash_01")
            .expect_err("open contradictions must fail admission");

        assert_eq!(err.memory_index, 0);
        assert_eq!(err.disposition, ReflectionAdmissionDisposition::Quarantine);
        assert_eq!(
            err.reasons,
            vec![AdmissionRejectionReason::OpenContradiction]
        );
    }

    // =========================================================================
    // Commit B — ADR 0036 reflection durable-write gate
    //
    // `validate_reflection_admission` answers the candidate-admission
    // question (per ADR 0038 admission rules). The durable-write gate
    // answers the stronger ADR 0036 question: is the typed cross-axis
    // proof closure FullChainVerified for every memory the orchestrator
    // is about to persist? The stable invariant is
    // `REFLECTION_ADMISSION_PROOF_CLOSURE_INVARIANT`. The print boundary
    // is intentionally not gated; only durable-write callers invoke
    // `require_reflection_durable_admission_allowed`.
    // =========================================================================

    #[test]
    fn reflection_durable_gate_refuses_default_partial_proof_state() {
        // Default reflection envelope has source anchors → AdmissionProofState::Partial,
        // which maps to CoreProofState::Partial. ADR 0036 forbids durable
        // promotion at Partial.
        let reflection = valid_reflection();
        let err = require_reflection_durable_admission_allowed(&reflection, "fixed", "hash_01")
            .expect_err("default reflection envelope is Partial; durable gate must refuse");
        assert_eq!(err.memory_index, 0);
        assert_eq!(err.axiom_refusal.proof_state, CoreProofState::Partial);
        assert!(
            err.to_string()
                .contains(REFLECTION_ADMISSION_PROOF_CLOSURE_INVARIANT),
            "refusal must carry stable invariant: {err}"
        );
        assert!(
            err.to_string()
                .contains(AXIOM_ADMISSION_PROOF_CLOSURE_INVARIANT),
            "refusal must also surface the upstream AXIOM admission invariant: {err}"
        );
    }

    #[test]
    fn reflection_durable_gate_refuses_when_lineage_is_missing() {
        // Without anchors, AdmissionProofState becomes Unknown.
        let mut reflection = valid_reflection();
        reflection.episode_candidates[0].source_event_ids.clear();

        let err = require_reflection_durable_admission_allowed(&reflection, "fixed", "hash_01")
            .expect_err("missing lineage must refuse durable promotion");
        assert_eq!(err.memory_index, 0);
        // Unknown maps to Partial in the typed report (see admission docs).
        assert_eq!(err.axiom_refusal.proof_state, CoreProofState::Partial);
    }

    #[test]
    fn reflection_memory_proof_state_helper_returns_observed_state() {
        let reflection = valid_reflection();
        let state = reflection_memory_proof_state(&reflection, 0, "fixed", "hash_01")
            .expect("memory exists");
        // Default reflection lineage → Partial typed proof state.
        assert_eq!(state, CoreProofState::Partial);

        // Out-of-bounds returns None rather than panicking, so callers
        // can defensively probe.
        assert!(reflection_memory_proof_state(&reflection, 99, "fixed", "hash_01").is_none());
    }

    #[test]
    fn reflection_durable_gate_invariant_key_is_stable() {
        assert_eq!(
            REFLECTION_ADMISSION_PROOF_CLOSURE_INVARIANT,
            "cortex_reflect.admission.proof_closure"
        );
        assert_eq!(
            axiom_admission_proof_closure_invariant(),
            AXIOM_ADMISSION_PROOF_CLOSURE_INVARIANT
        );
    }
}