crtx 0.1.1

CLI for the Cortex supervisory memory substrate.
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
//! `cortex reflect` — produce a `SessionReflection` candidate via an LLM
//! adapter.
//!
//! Reflection at lane 1.C is **read-only** with respect to the local data
//! dir: the command constructs a deterministic [`cortex_llm::LlmRequest`]
//! from `--trace`, dispatches it via [`cortex_llm::ReplayAdapter`], and
//! prints the response payload to stdout. Nothing is written to the SQLite
//! store, the JSONL ledger, or any other on-disk surface. The store /
//! candidate-promotion path lives in a later lane (cortex-reflect own
//! pipeline + cortex-store wiring).
//!
//! ## Adapter selection
//!
//! `--model` is the **adapter** selector, not the upstream model name. At
//! lane 1.C only `replay` is wired:
//!
//! | `--model` | Adapter                                                       |
//! |-----------|---------------------------------------------------------------|
//! | `replay`  | [`cortex_llm::ReplayAdapter`], BLAKE3-signed fixture index.   |
//!
//! Live backends (Claude, Ollama) plug into the same `--model` switch in a
//! later lane. When that happens, `replay` stays the CI default so unit
//! tests do not spend tokens.
//!
//! ## Fixture-integrity contract
//!
//! [`cortex_llm::ReplayAdapter::new`] verifies every fixture's BLAKE3 hash
//! against `INDEX.toml` at adapter-construction time. Any mismatch raises
//! [`cortex_llm::LlmError::FixtureIntegrityFailed`], which we map to
//! [`Exit::QuarantinedInput`] (`5`) — the operator-visible signal that the
//! local fixture set has drifted from its signed manifest and the run was
//! refused for safety. THREATS row T-RM-1 covers the rationale.
//!
//! ## ADR 0026 admission envelope at the CLI boundary
//!
//! The CLI composes an ADR 0026 [`PolicyDecision`] over the reflection
//! response before printing anything candidate-shaped. Three contributors
//! participate:
//!
//! - [`RULE_ADMISSION_DECISION`] — derived from
//!   [`cortex_reflect::validate_reflection_admission`]. `AdmitCandidate` →
//!   `Allow`, AXIOM-side `Quarantine` → `Quarantine`, AXIOM-side `Reject` →
//!   `Reject` (ADR 0038, ADR 0024 §3).
//! - [`RULE_FIXTURE_INTEGRITY`] — ADR 0014 integrity check. Reaching this
//!   point means the BLAKE3 check at adapter construction (and the per-call
//!   recheck) passed; otherwise the run already returned
//!   [`Exit::QuarantinedInput`] before composition. The contributor records
//!   `Allow` to make the integrity decision explainable in the emitted
//!   policy outcome.
//! - [`RULE_ADAPTER_AUTHORITY_CLASS`] — ADR 0019 tier classification of the
//!   reflection adapter. `replay` is a deterministic fixture replay and
//!   classifies as [`AuthorityClass::Derived`]; reflection cannot itself
//!   promote, which the composed `Allow` for candidate emission reflects.
//!   Live adapters (Claude, Ollama) plug into this contributor when they
//!   land and may downgrade the outcome.
//!
//! On `Reject` the CLI exits [`Exit::QuarantinedInput`] without printing
//! candidate-shaped output. On `Quarantine` the CLI prints a diagnostic
//! envelope whose `payload` is `null` and whose `policy_outcome` carries the
//! composed decision; the operator sees the reasons but no candidate body.
//! On `Allow` / `Warn` / `BreakGlass` the CLI prints the full envelope with
//! the reflection payload alongside the composed `policy_outcome`.

use std::fmt::Write as _;
use std::path::PathBuf;

use clap::Args;
use cortex_core::{
    compose_policy_outcomes, AuthorityClass, PolicyContribution, PolicyDecision, PolicyOutcome,
    TraceId,
};
use cortex_llm::{
    blake3_hex, LlmAdapter, LlmError, LlmMessage, LlmRequest, LlmRole, ReplayAdapter,
};
use cortex_memory::AdmissionDecision;
use cortex_reflect::{admission_request_for_memory, parse_reflection, SessionReflection};
use serde::Serialize;
use serde_json::json;

use crate::exit::Exit;

/// Rule id for the ADR 0026 contributor that carries the AXIOM-side
/// admission decision through to the reflect CLI's policy outcome.
pub const RULE_ADMISSION_DECISION: &str = "reflect.admission_decision";
/// Rule id for the ADR 0014 fixture-integrity contributor at the reflect CLI
/// boundary.
pub const RULE_FIXTURE_INTEGRITY: &str = "reflect.fixture_integrity";
/// Rule id for the ADR 0019 adapter-authority-class contributor at the
/// reflect CLI boundary.
pub const RULE_ADAPTER_AUTHORITY_CLASS: &str = "reflect.adapter_authority_class";

/// `cortex reflect` flags.
#[derive(Debug, Args)]
pub struct ReflectArgs {
    /// Trace identifier. The trace is opaque at lane 1.C — the request body
    /// echoes it verbatim into a deterministic prompt so fixture matching
    /// stays stable.
    #[arg(long, value_name = "TRACE_ID")]
    pub trace: TraceId,

    /// Adapter selector. Currently only `replay` is wired.
    #[arg(long, value_name = "MODEL")]
    pub model: String,

    /// Override the fixtures directory used by the replay adapter.
    /// Defaults to `$CORTEX_FIXTURES_DIR` if set, else
    /// `crates/cortex-cli/tests/fixtures/replay/` resolved from the binary's
    /// manifest dir.
    #[arg(long = "fixtures-dir", value_name = "DIR")]
    pub fixtures_dir: Option<PathBuf>,
}

/// CLI envelope printed by `cortex reflect`.
///
/// The envelope is the operator-visible result. It always carries a composed
/// [`PolicyDecision`] under `policy_outcome`. The reflection payload is
/// included under `payload` only when the composed outcome permits
/// candidate-shaped output (`Allow`, `Warn`, `BreakGlass`); `Quarantine`
/// suppresses the candidate body and surfaces the AXIOM diagnostic under
/// `diagnostic` instead.
#[derive(Debug, Serialize)]
struct ReflectEnvelope {
    /// Reflection payload, present when admission allows candidate emission.
    #[serde(skip_serializing_if = "Option::is_none")]
    payload: Option<serde_json::Value>,
    /// Optional structured diagnostic describing why the candidate body was
    /// suppressed.
    #[serde(skip_serializing_if = "Option::is_none")]
    diagnostic: Option<serde_json::Value>,
    /// Composed ADR 0026 policy outcome for this reflection.
    policy_outcome: PolicyDecision,
}

/// Run reflect; returns the CLI exit code.
pub fn run(args: ReflectArgs) -> Exit {
    if args.model != "replay" {
        eprintln!(
            "cortex reflect: unsupported --model `{}`. Only `replay` is wired at lane 1.C.",
            args.model
        );
        return Exit::Usage;
    }

    let fixtures_dir = resolve_fixtures_dir(args.fixtures_dir);
    let adapter = match ReplayAdapter::new(&fixtures_dir) {
        Ok(a) => a,
        Err(LlmError::FixtureIntegrityFailed(msg)) => {
            eprintln!("cortex reflect: fixture integrity failed: {msg}");
            return Exit::QuarantinedInput;
        }
        Err(e) => {
            eprintln!("cortex reflect: replay adapter setup failed: {e}");
            return Exit::Internal;
        }
    };

    let req = build_request(&args.trace);
    // Drive the future on a single-threaded Tokio runtime — the CLI is
    // synchronous from the user's perspective and we do not want to pull in
    // the workspace's full `tokio = "rt-multi-thread"` here.
    let rt = match tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
    {
        Ok(r) => r,
        Err(e) => {
            eprintln!("cortex reflect: tokio runtime: {e}");
            return Exit::Internal;
        }
    };
    let resp = match rt.block_on(adapter.complete(req)) {
        Ok(r) => r,
        Err(LlmError::FixtureIntegrityFailed(msg)) => {
            eprintln!("cortex reflect: fixture integrity failed: {msg}");
            return Exit::QuarantinedInput;
        }
        Err(LlmError::NoFixture { model, prompt_hash }) => {
            eprintln!(
                "cortex reflect: no replay fixture for model={model} prompt_hash={prompt_hash}"
            );
            return Exit::PreconditionUnmet;
        }
        Err(e) => {
            eprintln!("cortex reflect: adapter error: {e}");
            return Exit::Internal;
        }
    };

    // Compose the ADR 0026 admission envelope at the CLI boundary before any
    // candidate-shaped output is printed. The payload JSON we ultimately
    // hand to the operator is taken from `parsed_json` when present and
    // falls back to a fresh parse of `resp.text`.
    let adapter_id = adapter.adapter_id();
    let raw_hash = blake3_hex(resp.text.as_bytes());
    let payload_value = parsed_payload(&resp);
    let admission_summary = evaluate_admission(&payload_value, adapter_id, &raw_hash);
    let policy_outcome = compose_reflect_policy(&admission_summary);

    let envelope = match policy_outcome.final_outcome {
        PolicyOutcome::Allow | PolicyOutcome::Warn | PolicyOutcome::BreakGlass => ReflectEnvelope {
            payload: Some(payload_value),
            diagnostic: None,
            policy_outcome,
        },
        PolicyOutcome::Quarantine => ReflectEnvelope {
            payload: None,
            diagnostic: Some(admission_diagnostic_json(&admission_summary)),
            policy_outcome,
        },
        PolicyOutcome::Reject => {
            eprintln!(
                "cortex reflect: admission rejected: {}",
                admission_summary.reason_label()
            );
            return Exit::QuarantinedInput;
        }
    };

    let mut out = String::new();
    // Pretty-print with a trailing newline so the byte-for-byte fixture
    // comparison is line-friendly.
    writeln!(
        &mut out,
        "{}",
        serde_json::to_string_pretty(&envelope)
            .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into())
    )
    .ok();
    print!("{out}");
    Exit::Ok
}

/// Build the deterministic reflection request for the given trace.
///
/// Determinism is critical: the replay adapter matches by `(model,
/// prompt_hash)`, and the prompt hash is over `(system, messages,
/// temperature, max_tokens, json_schema)`. Any drift here invalidates the
/// signed fixture, so the prompt body is intentionally minimal and
/// trace-keyed.
pub fn build_request(trace: &TraceId) -> LlmRequest {
    LlmRequest {
        model: "claude-3-5-sonnet-20240620".into(),
        system: "Cortex reflection v1: produce a SessionReflection JSON for the given trace."
            .into(),
        messages: vec![LlmMessage {
            role: LlmRole::User,
            content: format!("trace: {trace}"),
        }],
        temperature: 0.0,
        max_tokens: 1024,
        json_schema: None,
        timeout_ms: 30_000,
    }
}

/// Resolve the fixtures directory.
///
/// Resolution order:
///   1. Explicit `--fixtures-dir` flag.
///   2. `$CORTEX_FIXTURES_DIR` environment override.
///   3. `crates/cortex-cli/tests/fixtures/replay/` adjacent to the binary's
///      manifest. This makes `cargo run -p cortex` Just Work for the demo
///      walkthrough in `README.md`.
fn resolve_fixtures_dir(explicit: Option<PathBuf>) -> PathBuf {
    if let Some(p) = explicit {
        return p;
    }
    if let Some(p) = std::env::var_os("CORTEX_FIXTURES_DIR") {
        return PathBuf::from(p);
    }
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("replay")
}

/// Reflect the LLM response payload as a JSON value, preferring the parsed
/// form and falling back to a fresh `serde_json` parse of `resp.text`.
fn parsed_payload(resp: &cortex_llm::LlmResponse) -> serde_json::Value {
    if let Some(v) = resp.parsed_json.clone() {
        return v;
    }
    match serde_json::from_str(&resp.text) {
        Ok(v) => v,
        Err(_) => serde_json::Value::String(resp.text.clone()),
    }
}

/// Summary of the AXIOM-side admission decision used to build the
/// `reflect.admission_decision` contributor.
#[derive(Debug)]
struct AdmissionSummary {
    /// Final outcome contributed by this rule.
    outcome: PolicyOutcome,
    /// Operator-facing label describing the contribution.
    reason: &'static str,
    /// Optional reason list collected from the AXIOM admission gate.
    detail: Option<String>,
}

impl AdmissionSummary {
    fn allow() -> Self {
        Self {
            outcome: PolicyOutcome::Allow,
            reason: "AXIOM admission accepted reflection candidates",
            detail: None,
        }
    }

    fn quarantine(detail: String) -> Self {
        Self {
            outcome: PolicyOutcome::Quarantine,
            reason: "AXIOM admission quarantined reflection candidates",
            detail: Some(detail),
        }
    }

    fn reject(detail: String) -> Self {
        Self {
            outcome: PolicyOutcome::Reject,
            reason: "AXIOM admission rejected reflection candidates",
            detail: Some(detail),
        }
    }

    fn reason_label(&self) -> String {
        match &self.detail {
            Some(detail) => format!("{} ({detail})", self.reason),
            None => self.reason.to_string(),
        }
    }
}

/// Evaluate the AXIOM admission contributor for the reflection payload.
///
/// Parse failures fall through to `Reject` per ADR 0026 §3: there is no safe
/// intermediate artifact when the response cannot even be interpreted as a
/// `SessionReflection`.
fn evaluate_admission(
    payload: &serde_json::Value,
    adapter_id: &str,
    raw_hash: &str,
) -> AdmissionSummary {
    let reflection = match parse_reflection_value(payload) {
        Ok(r) => r,
        Err(detail) => {
            return AdmissionSummary::reject(format!("reflection parse failed: {detail}"));
        }
    };

    // Walk every memory candidate through `admission_request_for_memory` —
    // the same deterministic gate that `validate_reflection_admission` uses
    // — so we can fold both the rejected and quarantined dispositions into
    // explicit `Reject` vs `Quarantine` outcomes per ADR 0026 §3.
    let mut quarantine_detail: Option<String> = None;
    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 AdmissionSummary::reject(format!(
                    "memory_candidates[{memory_index}] reasons={reasons:?}"
                ));
            }
            AdmissionDecision::Quarantine { reasons } => {
                let detail = format!("memory_candidates[{memory_index}] reasons={reasons:?}");
                quarantine_detail.get_or_insert(detail);
            }
        }
    }

    if let Some(detail) = quarantine_detail {
        AdmissionSummary::quarantine(detail)
    } else {
        AdmissionSummary::allow()
    }
}

/// Parse a JSON value into a `SessionReflection`. Returns an operator-facing
/// failure detail on error.
fn parse_reflection_value(value: &serde_json::Value) -> Result<SessionReflection, String> {
    let body = serde_json::to_string(value).map_err(|err| err.to_string())?;
    parse_reflection(&body).map_err(|err| err.to_string())
}

/// Compose the ADR 0026 admission envelope at the reflect CLI boundary.
fn compose_reflect_policy(admission: &AdmissionSummary) -> PolicyDecision {
    let admission_contribution =
        PolicyContribution::new(RULE_ADMISSION_DECISION, admission.outcome, admission.reason)
            .expect("static reflect admission contribution is valid");

    // ADR 0014 fixture integrity: reaching this point means the adapter
    // constructed successfully (the BLAKE3-signed `INDEX.toml` check passed)
    // and the per-call replay returned a fixture whose payload bytes were
    // hash-verified. We record the explicit `Allow` so the explainability
    // surface in the emitted policy outcome documents the check.
    let fixture_contribution = PolicyContribution::new(
        RULE_FIXTURE_INTEGRITY,
        PolicyOutcome::Allow,
        "replay adapter fixture integrity verified at construction and per call",
    )
    .expect("static reflect fixture integrity contribution is valid");

    // ADR 0019 adapter authority class: the `replay` adapter is a
    // deterministic fixture replay (no live LLM), classified as Derived.
    // Reflection cannot itself promote — the composed `Allow` reflects that
    // candidate emission is the correct upper bound. Live adapters wire into
    // this contributor when they land.
    let authority_class = adapter_authority_class("replay");
    let authority_contribution = PolicyContribution::new(
        RULE_ADAPTER_AUTHORITY_CLASS,
        adapter_authority_class_outcome(authority_class),
        adapter_authority_class_reason(authority_class),
    )
    .expect("static reflect adapter authority class contribution is valid");

    compose_policy_outcomes(
        vec![
            admission_contribution,
            fixture_contribution,
            authority_contribution,
        ],
        None,
    )
}

/// Map a reflection adapter id to its ADR 0019 authority class.
fn adapter_authority_class(adapter_id: &str) -> AuthorityClass {
    match adapter_id {
        // `replay` is deterministic, fixture-driven, candidate-only.
        "replay" => AuthorityClass::Derived,
        // Conservative default for any future adapter id: Untrusted until an
        // ADR explicitly classifies it.
        _ => AuthorityClass::Untrusted,
    }
}

/// ADR 0019 outcome mapping for a reflection adapter's authority class.
///
/// `Derived` adapters may emit candidate-only output (Allow). `Untrusted`
/// adapters are not authorised to emit reflection output and fail closed
/// (Reject) at the CLI boundary.
fn adapter_authority_class_outcome(class: AuthorityClass) -> PolicyOutcome {
    match class {
        AuthorityClass::Derived | AuthorityClass::Observed => PolicyOutcome::Allow,
        AuthorityClass::Verified | AuthorityClass::Operator => PolicyOutcome::Allow,
        AuthorityClass::Untrusted => PolicyOutcome::Reject,
    }
}

fn adapter_authority_class_reason(class: AuthorityClass) -> &'static str {
    match class {
        AuthorityClass::Derived => {
            "reflection adapter classified as Derived; candidate-only emission allowed"
        }
        AuthorityClass::Observed => {
            "reflection adapter classified as Observed; candidate-only emission allowed"
        }
        AuthorityClass::Verified => {
            "reflection adapter classified as Verified; candidate-only emission allowed"
        }
        AuthorityClass::Operator => {
            "reflection adapter classified as Operator; candidate-only emission allowed"
        }
        AuthorityClass::Untrusted => {
            "reflection adapter classified as Untrusted; reflection emission refused"
        }
    }
}

fn admission_diagnostic_json(admission: &AdmissionSummary) -> serde_json::Value {
    json!({
        "reason": admission.reason,
        "detail": admission.detail.as_deref().unwrap_or(""),
    })
}

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

    #[test]
    fn build_request_is_deterministic() {
        let t: TraceId = "trc_01ARZ3NDEKTSV4RRFFQ69G5FAW".parse().unwrap();
        let a = build_request(&t);
        let b = build_request(&t);
        assert_eq!(a.prompt_hash(), b.prompt_hash());
    }

    #[test]
    fn build_request_differs_per_trace() {
        let t1: TraceId = "trc_01ARZ3NDEKTSV4RRFFQ69G5FAW".parse().unwrap();
        let t2: TraceId = "trc_01ARZ3NDEKTSV4RRFFQ69G5FAX".parse().unwrap();
        assert_ne!(
            build_request(&t1).prompt_hash(),
            build_request(&t2).prompt_hash()
        );
    }

    #[test]
    fn compose_reflect_policy_allows_when_admission_allows() {
        let policy = compose_reflect_policy(&AdmissionSummary::allow());
        assert_eq!(policy.final_outcome, PolicyOutcome::Allow);
        // All three contributors must be present in the explainability set.
        let rule_ids: Vec<_> = policy
            .contributing
            .iter()
            .chain(policy.discarded.iter())
            .map(|contribution| contribution.rule_id.as_str().to_string())
            .collect();
        assert!(rule_ids.iter().any(|id| id == RULE_ADMISSION_DECISION));
        assert!(rule_ids.iter().any(|id| id == RULE_FIXTURE_INTEGRITY));
        assert!(rule_ids.iter().any(|id| id == RULE_ADAPTER_AUTHORITY_CLASS));
    }

    #[test]
    fn compose_reflect_policy_quarantines_when_admission_quarantines() {
        let policy =
            compose_reflect_policy(&AdmissionSummary::quarantine("open contradiction".into()));
        assert_eq!(policy.final_outcome, PolicyOutcome::Quarantine);
    }

    #[test]
    fn compose_reflect_policy_rejects_when_admission_rejects() {
        let policy =
            compose_reflect_policy(&AdmissionSummary::reject("missing source anchor".into()));
        assert_eq!(policy.final_outcome, PolicyOutcome::Reject);
    }

    #[test]
    fn evaluate_admission_returns_reject_for_unparseable_payload() {
        let payload = serde_json::json!({"not": "a session reflection"});
        let summary = evaluate_admission(&payload, "replay", "hash_test");
        assert_eq!(summary.outcome, PolicyOutcome::Reject);
    }

    #[test]
    fn evaluate_admission_allows_empty_session_reflection() {
        // The demo replay fixture: a SessionReflection with no memory
        // candidates. Admission has nothing to gate beyond the empty list, so
        // the contributor allows.
        let payload = serde_json::json!({
            "trace_id": "trc_01ARZ3NDEKTSV4RRFFQ69G5FAW",
            "episode_candidates": [],
            "memory_candidates": [],
            "contradictions": [],
            "doctrine_suggestions": []
        });
        let summary = evaluate_admission(&payload, "replay", "hash_test");
        assert_eq!(summary.outcome, PolicyOutcome::Allow);
    }

    #[test]
    fn evaluate_admission_quarantines_open_contradiction() {
        let payload = serde_json::json!({
            "trace_id": "trc_01ARZ3NDEKTSV4RRFFQ69G5FAW",
            "episode_candidates": [{
                "summary": "demo",
                "source_event_ids": ["evt_01ARZ3NDEKTSV4RRFFQ69G5FAV"],
                "domains": ["agents"],
                "entities": ["Cortex"],
                "candidate_meaning": null,
                "confidence": 0.5
            }],
            "memory_candidates": [{
                "memory_type": "strategic",
                "claim": "Reflection memory remains candidate-only.",
                "source_episode_indexes": [0],
                "applies_when": ["reflecting"],
                "does_not_apply_when": ["promoting"],
                "confidence": 0.8,
                "initial_salience": {
                    "reusability": 0.5,
                    "consequence": 0.5,
                    "emotional_charge": 0.0
                }
            }],
            "contradictions": [{"claim": "conflict"}],
            "doctrine_suggestions": []
        });
        let summary = evaluate_admission(&payload, "replay", "hash_test");
        assert_eq!(summary.outcome, PolicyOutcome::Quarantine);
    }

    #[test]
    fn adapter_authority_class_classifies_replay_as_derived() {
        assert_eq!(adapter_authority_class("replay"), AuthorityClass::Derived);
    }

    #[test]
    fn adapter_authority_class_defaults_unknown_adapters_to_untrusted() {
        assert_eq!(
            adapter_authority_class("unknown-future-adapter"),
            AuthorityClass::Untrusted
        );
        assert_eq!(
            adapter_authority_class_outcome(AuthorityClass::Untrusted),
            PolicyOutcome::Reject
        );
    }
}