crtx-retrieval 0.1.1

Hybrid retrieval over memory views (lexical + salience; vectors later).
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
//! Deterministic contradiction-resolution scaffold for retrieval.
//!
//! This module is intentionally read-only. Store and context-pack wiring can
//! adapt durable memory rows into these inputs later.

use std::collections::HashSet;

use cortex_core::{
    compose_policy_outcomes, CoreError, CoreResult, PolicyContribution, PolicyDecision,
    PolicyOutcome,
};

/// High-level result of attempting to resolve a conflict set.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolutionState {
    /// A single candidate is safe to consume as the resolved memory.
    Resolved,
    /// Multiple hypotheses must be surfaced because no safe winner exists.
    MultiHypothesis,
    /// Proof, claim-slot, or precedence evidence is insufficient.
    Unknown,
}

/// Coarse authority level supplied by the caller.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum AuthorityLevel {
    /// Low authority — observed or unverified.
    Low,
    /// Medium authority — partially verified.
    Medium,
    /// High authority — fully verified or operator-grade.
    High,
}

/// Authority proof closure hint for a candidate memory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProofClosureHint {
    /// All proof axes required by the caller passed.
    FullChainVerified,
    /// At least one proof axis is intentionally unavailable or development-grade.
    Partial,
    /// Proof state has not been established.
    Unknown,
    /// A proof axis failed with a named edge.
    Broken {
        /// Name of the proof axis that failed.
        edge: String,
    },
}

impl ProofClosureHint {
    fn is_full_chain_verified(&self) -> bool {
        matches!(self, Self::FullChainVerified)
    }
}

/// Authority and proof hints attached to a memory candidate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorityProofHint {
    /// Caller-provided authority level.
    pub authority: AuthorityLevel,
    /// Caller-provided proof closure result.
    pub proof: ProofClosureHint,
}

impl AuthorityProofHint {
    /// Returns true when a candidate has high authority and full proof closure.
    #[must_use]
    pub fn is_high_authority_verified(&self) -> bool {
        self.authority == AuthorityLevel::High && self.proof.is_full_chain_verified()
    }
}

/// Memory-shaped input for a caller-supplied contradiction set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConflictingMemoryInput {
    /// Durable memory identifier.
    pub memory_id: String,
    /// Stable belief-slot key when known.
    pub claim_key: Option<String>,
    /// Memory claim text.
    pub claim: String,
    /// Authority and proof hints for this memory.
    pub authority: AuthorityProofHint,
    /// Memory IDs this input is known to conflict with.
    pub conflicts_with: Vec<String>,
}

impl ConflictingMemoryInput {
    /// Creates a memory input with no explicit `conflicts_with` edges.
    #[must_use]
    pub fn new(
        memory_id: impl Into<String>,
        claim_key: Option<impl Into<String>>,
        claim: impl Into<String>,
        authority: AuthorityProofHint,
    ) -> Self {
        Self {
            memory_id: memory_id.into(),
            claim_key: claim_key.map(Into::into),
            claim: claim.into(),
            authority,
            conflicts_with: Vec::new(),
        }
    }

    /// Adds explicit conflict edges.
    #[must_use]
    pub fn with_conflicts(mut self, conflicts_with: Vec<String>) -> Self {
        self.conflicts_with = conflicts_with;
        self
    }
}

/// Explicit evidence that one candidate supersedes the others for this conflict set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrecedenceEvidence {
    /// Winning memory ID.
    pub winner_memory_id: String,
    /// Memory IDs explicitly superseded by `winner_memory_id`.
    pub loser_memory_ids: Vec<String>,
    /// Human- or policy-readable resolution reason.
    pub reason: String,
    /// Proof closure for the precedence evidence itself.
    pub proof: ProofClosureHint,
}

/// Machine-readable reason emitted by the resolver.
#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolutionReason {
    /// No candidate inputs were provided.
    NoInputs,
    /// Exactly one candidate was present; no conflict to resolve.
    SingleCandidate,
    /// All candidates share the same claim text.
    DuplicateClaim,
    /// An explicit precedence record nominated the winner.
    ExplicitPrecedence { winner_memory_id: String },
    /// Multiple candidates have conflicting claims.
    ConflictingClaims,
    /// A candidate is missing a required claim key.
    MissingClaimKey { memory_id: String },
    /// A candidate has only partial proof closure.
    PartialProof { memory_id: String },
    /// A candidate has unknown proof state.
    UnknownProof { memory_id: String },
    /// A candidate has a broken proof axis.
    BrokenProof { memory_id: String, edge: String },
    /// High-authority verified conflict requires explicit precedence before resolution.
    HighAuthorityVerifiedConflictRequiresPrecedence,
    /// Precedence evidence does not cover all losers.
    IncompletePrecedence {
        winner_memory_id: String,
        missing_loser_ids: Vec<String>,
    },
    /// Multiple candidates could claim precedence; winner is ambiguous.
    AmbiguousPrecedence { winner_memory_ids: Vec<String> },
}

impl ResolutionReason {
    const fn policy_rule_id(&self) -> &'static str {
        match self {
            Self::NoInputs => "retrieval.resolve.no_inputs",
            Self::SingleCandidate => "retrieval.resolve.single_candidate",
            Self::DuplicateClaim => "retrieval.resolve.duplicate_claim",
            Self::ExplicitPrecedence { .. } => "retrieval.resolve.explicit_precedence",
            Self::ConflictingClaims => "retrieval.resolve.conflicting_claims",
            Self::MissingClaimKey { .. } => "retrieval.resolve.missing_claim_key",
            Self::PartialProof { .. } => "retrieval.resolve.partial_proof",
            Self::UnknownProof { .. } => "retrieval.resolve.unknown_proof",
            Self::BrokenProof { .. } => "retrieval.resolve.broken_proof",
            Self::HighAuthorityVerifiedConflictRequiresPrecedence => {
                "retrieval.resolve.high_authority_conflict_requires_precedence"
            }
            Self::IncompletePrecedence { .. } => "retrieval.resolve.incomplete_precedence",
            Self::AmbiguousPrecedence { .. } => "retrieval.resolve.ambiguous_precedence",
        }
    }

    const fn policy_outcome(&self, state: ResolutionState) -> PolicyOutcome {
        match self {
            Self::SingleCandidate | Self::DuplicateClaim | Self::ExplicitPrecedence { .. }
                if matches!(state, ResolutionState::Resolved) =>
            {
                PolicyOutcome::Allow
            }
            Self::BrokenProof { .. } => PolicyOutcome::Reject,
            _ => PolicyOutcome::Quarantine,
        }
    }

    const fn policy_reason(&self) -> &'static str {
        match self {
            Self::NoInputs => "retrieval conflict resolver received no inputs",
            Self::SingleCandidate => "single candidate can be consumed",
            Self::DuplicateClaim => "duplicate claims resolved by deterministic authority ordering",
            Self::ExplicitPrecedence { .. } => "explicit full-chain precedence resolved conflict",
            Self::ConflictingClaims => "conflicting claims require multi-hypothesis handling",
            Self::MissingClaimKey { .. } => "candidate is missing claim-key evidence",
            Self::PartialProof { .. } => "candidate proof is partial",
            Self::UnknownProof { .. } => "candidate proof is unknown",
            Self::BrokenProof { .. } => "candidate proof is broken",
            Self::HighAuthorityVerifiedConflictRequiresPrecedence => {
                "high-authority verified conflict requires explicit precedence"
            }
            Self::IncompletePrecedence { .. } => "precedence evidence does not cover all losers",
            Self::AmbiguousPrecedence { .. } => "multiple precedence winners remain ambiguous",
        }
    }
}

/// Resolver output consumed by later retrieval/context-pack wiring.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolverOutput {
    /// Resolution state.
    pub state: ResolutionState,
    /// Selected candidate when `state == Resolved`.
    pub selected: Option<ConflictingMemoryInput>,
    /// Candidate hypotheses that must be surfaced to callers.
    pub hypotheses: Vec<ConflictingMemoryInput>,
    /// Reasons supporting the state.
    pub reasons: Vec<ResolutionReason>,
}

impl ResolverOutput {
    /// Derive the ADR 0026 policy decision for this resolver output.
    #[must_use]
    pub fn policy_decision(&self) -> PolicyDecision {
        if self.reasons.is_empty() {
            return compose_policy_outcomes(
                vec![PolicyContribution::new(
                    "retrieval.resolve.no_reason",
                    PolicyOutcome::Quarantine,
                    "resolver returned no reason and cannot be treated as clean authority",
                )
                .expect("static policy contribution is valid")],
                None,
            );
        }

        let contributions = self
            .reasons
            .iter()
            .map(|reason| {
                PolicyContribution::new(
                    reason.policy_rule_id(),
                    reason.policy_outcome(self.state),
                    reason.policy_reason(),
                )
                .expect("static policy contribution is valid")
            })
            .collect();
        compose_policy_outcomes(contributions, None)
    }

    /// Fail closed before a resolver output is consumed as a default,
    /// canonical retrieval result.
    ///
    /// Multi-hypothesis and unknown outputs may still be rendered explicitly,
    /// but they must not silently act as resolved support for promotion,
    /// active-memory updates, or default context-pack inclusion.
    pub fn require_default_use_allowed(&self) -> CoreResult<()> {
        let policy = self.policy_decision();
        match policy.final_outcome {
            PolicyOutcome::Reject | PolicyOutcome::Quarantine => {
                Err(CoreError::Validation(format!(
                    "retrieval resolver default use blocked by policy outcome {:?}",
                    policy.final_outcome
                )))
            }
            PolicyOutcome::Allow | PolicyOutcome::Warn | PolicyOutcome::BreakGlass => Ok(()),
        }
    }
}

/// Resolves a caller-supplied contradiction set without mutating memory.
#[must_use]
pub fn resolve_conflicts(
    inputs: &[ConflictingMemoryInput],
    precedence: &[PrecedenceEvidence],
) -> ResolverOutput {
    let candidates = sorted_candidates(inputs);
    if candidates.is_empty() {
        return ResolverOutput {
            state: ResolutionState::Unknown,
            selected: None,
            hypotheses: Vec::new(),
            reasons: vec![ResolutionReason::NoInputs],
        };
    }

    let mut reasons = proof_reasons(&candidates);
    reasons.extend(missing_claim_key_reasons(&candidates));
    if !reasons.is_empty() {
        return ResolverOutput {
            state: ResolutionState::Unknown,
            selected: None,
            hypotheses: candidates,
            reasons,
        };
    }

    if candidates.len() == 1 {
        return ResolverOutput {
            state: ResolutionState::Resolved,
            selected: candidates.first().cloned(),
            hypotheses: candidates,
            reasons: vec![ResolutionReason::SingleCandidate],
        };
    }

    if !has_conflict(&candidates) {
        let selected = strongest_candidate(&candidates);
        return ResolverOutput {
            state: ResolutionState::Resolved,
            selected: Some(selected),
            hypotheses: candidates,
            reasons: vec![ResolutionReason::DuplicateClaim],
        };
    }

    match valid_precedence_winner(&candidates, precedence) {
        PrecedenceMatch::One(winner) => ResolverOutput {
            state: ResolutionState::Resolved,
            selected: Some(winner.clone()),
            hypotheses: vec![winner.clone()],
            reasons: vec![ResolutionReason::ExplicitPrecedence {
                winner_memory_id: winner.memory_id,
            }],
        },
        PrecedenceMatch::Many(winner_memory_ids) => ResolverOutput {
            state: ResolutionState::MultiHypothesis,
            selected: None,
            hypotheses: candidates,
            reasons: vec![ResolutionReason::AmbiguousPrecedence { winner_memory_ids }],
        },
        PrecedenceMatch::Incomplete {
            winner_memory_id,
            missing_loser_ids,
        } => ResolverOutput {
            state: ResolutionState::MultiHypothesis,
            selected: None,
            hypotheses: candidates,
            reasons: vec![ResolutionReason::IncompletePrecedence {
                winner_memory_id,
                missing_loser_ids,
            }],
        },
        PrecedenceMatch::None => unresolved_conflict(candidates),
    }
}

fn unresolved_conflict(candidates: Vec<ConflictingMemoryInput>) -> ResolverOutput {
    let mut reasons = vec![ResolutionReason::ConflictingClaims];
    if high_authority_verified_conflict(&candidates) {
        reasons.push(ResolutionReason::HighAuthorityVerifiedConflictRequiresPrecedence);
    }

    ResolverOutput {
        state: ResolutionState::MultiHypothesis,
        selected: None,
        hypotheses: candidates,
        reasons,
    }
}

fn proof_reasons(candidates: &[ConflictingMemoryInput]) -> Vec<ResolutionReason> {
    let mut reasons = Vec::new();
    for candidate in candidates {
        match &candidate.authority.proof {
            ProofClosureHint::FullChainVerified => {}
            ProofClosureHint::Partial => reasons.push(ResolutionReason::PartialProof {
                memory_id: candidate.memory_id.clone(),
            }),
            ProofClosureHint::Unknown => reasons.push(ResolutionReason::UnknownProof {
                memory_id: candidate.memory_id.clone(),
            }),
            ProofClosureHint::Broken { edge } => reasons.push(ResolutionReason::BrokenProof {
                memory_id: candidate.memory_id.clone(),
                edge: edge.clone(),
            }),
        }
    }
    reasons
}

fn missing_claim_key_reasons(candidates: &[ConflictingMemoryInput]) -> Vec<ResolutionReason> {
    candidates
        .iter()
        .filter(|candidate| {
            candidate
                .claim_key
                .as_ref()
                .is_none_or(|claim_key| claim_key.trim().is_empty())
        })
        .map(|candidate| ResolutionReason::MissingClaimKey {
            memory_id: candidate.memory_id.clone(),
        })
        .collect()
}

fn has_conflict(candidates: &[ConflictingMemoryInput]) -> bool {
    let claims: HashSet<_> = candidates
        .iter()
        .map(|candidate| normalize_claim(&candidate.claim))
        .collect();
    if claims.len() > 1 {
        return true;
    }

    let ids: HashSet<_> = candidates
        .iter()
        .map(|candidate| candidate.memory_id.as_str())
        .collect();
    candidates.iter().any(|candidate| {
        candidate
            .conflicts_with
            .iter()
            .any(|conflict_id| ids.contains(conflict_id.as_str()))
    })
}

fn high_authority_verified_conflict(candidates: &[ConflictingMemoryInput]) -> bool {
    candidates
        .iter()
        .filter(|candidate| candidate.authority.is_high_authority_verified())
        .take(2)
        .count()
        > 1
}

fn strongest_candidate(candidates: &[ConflictingMemoryInput]) -> ConflictingMemoryInput {
    let mut sorted = candidates.to_vec();
    sorted.sort_by(|left, right| {
        right
            .authority
            .authority
            .cmp(&left.authority.authority)
            .then_with(|| left.memory_id.cmp(&right.memory_id))
    });
    sorted
        .into_iter()
        .next()
        .expect("strongest_candidate requires at least one candidate")
}

fn sorted_candidates(inputs: &[ConflictingMemoryInput]) -> Vec<ConflictingMemoryInput> {
    let mut candidates = inputs.to_vec();
    candidates.sort_by(|left, right| left.memory_id.cmp(&right.memory_id));
    candidates
}

fn normalize_claim(claim: &str) -> String {
    claim
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .to_ascii_lowercase()
}

enum PrecedenceMatch {
    One(ConflictingMemoryInput),
    Many(Vec<String>),
    Incomplete {
        winner_memory_id: String,
        missing_loser_ids: Vec<String>,
    },
    None,
}

fn valid_precedence_winner(
    candidates: &[ConflictingMemoryInput],
    precedence: &[PrecedenceEvidence],
) -> PrecedenceMatch {
    let candidate_ids: HashSet<_> = candidates
        .iter()
        .map(|candidate| candidate.memory_id.as_str())
        .collect();
    let mut complete_winners = Vec::new();
    let mut first_incomplete = None;

    for evidence in precedence
        .iter()
        .filter(|evidence| evidence.proof.is_full_chain_verified())
        .filter(|evidence| candidate_ids.contains(evidence.winner_memory_id.as_str()))
    {
        let loser_ids: HashSet<_> = evidence
            .loser_memory_ids
            .iter()
            .map(String::as_str)
            .collect();
        let mut missing_loser_ids: Vec<_> = candidate_ids
            .iter()
            .copied()
            .filter(|candidate_id| *candidate_id != evidence.winner_memory_id)
            .filter(|candidate_id| !loser_ids.contains(candidate_id))
            .map(str::to_string)
            .collect();
        missing_loser_ids.sort();

        if missing_loser_ids.is_empty() {
            complete_winners.push(evidence.winner_memory_id.clone());
        } else if first_incomplete.is_none() {
            first_incomplete = Some(PrecedenceMatch::Incomplete {
                winner_memory_id: evidence.winner_memory_id.clone(),
                missing_loser_ids,
            });
        }
    }

    complete_winners.sort();
    complete_winners.dedup();
    match complete_winners.len() {
        0 => first_incomplete.unwrap_or(PrecedenceMatch::None),
        1 => {
            let winner_id = &complete_winners[0];
            let winner = candidates
                .iter()
                .find(|candidate| &candidate.memory_id == winner_id)
                .expect("complete winner came from candidate IDs")
                .clone();
            PrecedenceMatch::One(winner)
        }
        _ => PrecedenceMatch::Many(complete_winners),
    }
}

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

    fn verified_high(memory_id: &str, claim: &str) -> ConflictingMemoryInput {
        ConflictingMemoryInput::new(
            memory_id,
            Some("slot/runtime"),
            claim,
            AuthorityProofHint {
                authority: AuthorityLevel::High,
                proof: ProofClosureHint::FullChainVerified,
            },
        )
    }

    #[test]
    fn conflicting_verified_memories_enter_multi_hypothesis() {
        let left = verified_high("mem_a", "Use replay adapter version 1");
        let right = verified_high("mem_b", "Use replay adapter version 2");

        let output = resolve_conflicts(&[left, right], &[]);

        assert_eq!(output.state, ResolutionState::MultiHypothesis);
        assert_eq!(
            output.policy_decision().final_outcome,
            PolicyOutcome::Quarantine
        );
        assert_eq!(output.selected, None);
        assert_eq!(output.hypotheses.len(), 2);
        assert!(output
            .reasons
            .contains(&ResolutionReason::HighAuthorityVerifiedConflictRequiresPrecedence));
    }

    #[test]
    fn unknown_proof_propagates_unknown() {
        let input = ConflictingMemoryInput::new(
            "mem_unknown",
            Some("slot/runtime"),
            "Use replay adapter version 1",
            AuthorityProofHint {
                authority: AuthorityLevel::High,
                proof: ProofClosureHint::Unknown,
            },
        );

        let output = resolve_conflicts(&[input], &[]);

        assert_eq!(output.state, ResolutionState::Unknown);
        assert_eq!(
            output.policy_decision().final_outcome,
            PolicyOutcome::Quarantine
        );
        assert_eq!(output.selected, None);
        assert!(output.reasons.contains(&ResolutionReason::UnknownProof {
            memory_id: "mem_unknown".into()
        }));
    }

    #[test]
    fn explicit_full_chain_precedence_resolves_conflict() {
        let left = verified_high("mem_a", "Use replay adapter version 1");
        let right = verified_high("mem_b", "Use replay adapter version 2");
        let precedence = PrecedenceEvidence {
            winner_memory_id: "mem_b".into(),
            loser_memory_ids: vec!["mem_a".into()],
            reason: "operator-attested supersession".into(),
            proof: ProofClosureHint::FullChainVerified,
        };

        let output = resolve_conflicts(&[left, right], &[precedence]);

        assert_eq!(output.state, ResolutionState::Resolved);
        assert_eq!(output.policy_decision().final_outcome, PolicyOutcome::Allow);
        assert_eq!(
            output
                .selected
                .as_ref()
                .map(|candidate| candidate.memory_id.as_str()),
            Some("mem_b")
        );
        assert_eq!(
            output.reasons,
            [ResolutionReason::ExplicitPrecedence {
                winner_memory_id: "mem_b".into()
            }]
        );
        output
            .require_default_use_allowed()
            .expect("resolved output is default-usable");
    }

    #[test]
    fn broken_proof_maps_to_policy_reject() {
        let input = ConflictingMemoryInput::new(
            "mem_broken",
            Some("slot/runtime"),
            "Use replay adapter version 1",
            AuthorityProofHint {
                authority: AuthorityLevel::High,
                proof: ProofClosureHint::Broken {
                    edge: "event:missing_hash".into(),
                },
            },
        );

        let output = resolve_conflicts(&[input], &[]);
        let policy = output.policy_decision();

        assert_eq!(output.state, ResolutionState::Unknown);
        assert_eq!(policy.final_outcome, PolicyOutcome::Reject);
        assert_eq!(
            policy.contributing[0].rule_id.as_str(),
            "retrieval.resolve.broken_proof"
        );
    }

    #[test]
    fn unresolved_conflict_fails_closed_for_default_use() {
        let left = verified_high("mem_a", "Use replay adapter version 1");
        let right = verified_high("mem_b", "Use replay adapter version 2");

        let output = resolve_conflicts(&[left, right], &[]);
        let err = output
            .require_default_use_allowed()
            .expect_err("multi-hypothesis output must not be default-usable");

        assert!(
            err.to_string().contains("Quarantine"),
            "default-use failure should expose the policy outcome: {err}"
        );
    }

    #[test]
    fn broken_proof_fails_closed_for_default_use() {
        let input = ConflictingMemoryInput::new(
            "mem_broken",
            Some("slot/runtime"),
            "Use replay adapter version 1",
            AuthorityProofHint {
                authority: AuthorityLevel::High,
                proof: ProofClosureHint::Broken {
                    edge: "event:missing_hash".into(),
                },
            },
        );

        let output = resolve_conflicts(&[input], &[]);
        let err = output
            .require_default_use_allowed()
            .expect_err("broken proof must not be default-usable");

        assert!(
            err.to_string().contains("Reject"),
            "default-use failure should expose the policy outcome: {err}"
        );
    }
}