Skip to main content

hol_cigar/
answer.rs

1//! Claim review is a host trust boundary, not model self-certification.
2use crate::{
3    ContextError, ContextGraph, ContextRequest, ContextSnapshot, EdgeKind, TokenCounter, digest,
4};
5use serde::{Deserialize, Serialize};
6use std::collections::{BTreeMap, BTreeSet};
7
8/// One factual claim proposed by a model. All displayed factual prose must be represented.
9#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
10#[serde(deny_unknown_fields)]
11pub struct AnswerClaim {
12    /// Complete atomic claim, at most 8 KiB. Citation presence does not establish entailment.
13    pub text: String,
14    /// Selected node IDs, not arbitrary URLs or short prompt handles. Resolve handles first.
15    pub citations: BTreeSet<String>,
16    /// Elicited probability of correctness in basis points (0..=10000), or unavailable.
17    /// This is telemetry only and never makes a claim eligible for release.
18    pub confidence_bps: Option<u16>,
19}
20
21impl std::fmt::Debug for AnswerClaim {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        f.debug_struct("AnswerClaim")
24            .field("bytes", &self.text.len())
25            .field("citations", &self.citations.len())
26            .finish_non_exhaustive()
27    }
28}
29
30impl AnswerClaim {
31    /// Bind a review to this exact claim, citations, confidence and context snapshot.
32    /// A digest binds bytes; it does not authenticate the reviewer.
33    pub fn review_key(&self, snapshot_id: &str) -> Result<String, ContextError> {
34        self.validate()?;
35        if !valid_digest(snapshot_id) {
36            return Err(ContextError::InvalidInput);
37        }
38        digest("cigar.claim-review.v1", &(snapshot_id, self))
39    }
40
41    fn validate(&self) -> Result<(), ContextError> {
42        if self.text.trim().is_empty()
43            || self.text.len() > 8192
44            || self.citations.len() > 64
45            || self.citations.iter().any(|id| !crate::graph::valid_id(id))
46            || self.confidence_bps.is_some_and(|value| value > 10000)
47        {
48            return Err(ContextError::InvalidInput);
49        }
50        Ok(())
51    }
52}
53
54/// A bounded proposed answer. Unchecked free-form prose is deliberately absent.
55#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
56#[serde(deny_unknown_fields)]
57pub struct AnswerDraft {
58    /// Exact snapshot supplied to the generator.
59    pub snapshot_id: String,
60    /// At most 128 atomic claims, with no duplicate review keys.
61    pub claims: Vec<AnswerClaim>,
62    /// Explicit abstention must contain no claims.
63    #[serde(default)]
64    pub abstain: bool,
65}
66
67impl AnswerDraft {
68    /// Return keys for a trusted reviewer to use; this performs no factual assessment.
69    pub fn review_keys(&self) -> Result<Vec<String>, ContextError> {
70        if !valid_digest(&self.snapshot_id)
71            || self.claims.len() > 128
72            || (self.abstain && !self.claims.is_empty())
73        {
74            return Err(ContextError::InvalidInput);
75        }
76        let keys = self
77            .claims
78            .iter()
79            .map(|claim| claim.review_key(&self.snapshot_id))
80            .collect::<Result<Vec<_>, _>>()?;
81        if keys.iter().collect::<BTreeSet<_>>().len() != keys.len() {
82            return Err(ContextError::InvalidInput);
83        }
84        Ok(keys)
85    }
86}
87
88/// Factual judgment supplied by the owning application through a trusted review path.
89/// Never deserialize these verdicts from the same untrusted output as the draft.
90#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum ClaimVerdict {
93    /// Every assertion is supported by the cited selected evidence, with conflicts resolved.
94    Supported,
95    /// The evidence does not establish the claim (including irrelevant or incomplete citations).
96    Unsupported,
97    /// The evidence establishes a conflicting claim.
98    Contradicted,
99    /// The reviewer could not decide. Unknown is never treated as supported.
100    Unknown,
101}
102
103/// An independently supplied review. The caller authenticates and evaluates its reviewer.
104#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
105#[serde(deny_unknown_fields)]
106pub struct ClaimReview {
107    /// Key produced by `AnswerClaim::review_key`; stale or unrelated keys are errors.
108    pub claim_key: String,
109    /// Semantic judgment of the entire cited claim, not just the existence of its citations.
110    pub verdict: ClaimVerdict,
111    /// Explicit counterclaim nodes considered by the reviewer. Acknowledgment is not resolution;
112    /// a supported verdict additionally asserts the reviewer resolved the conflict.
113    #[serde(default)]
114    pub reviewed_counterevidence: BTreeSet<String>,
115}
116
117/// Host-owned answer release policy. Model confidence cannot relax it.
118#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
119#[serde(default, deny_unknown_fields)]
120pub struct AnswerPolicy {
121    /// Minimum distinct provenance groups per claim, from one to four. Shared locators or
122    /// identical complete document text merge groups transitively. Independence beyond this
123    /// conservative grouping is the trusted ingestion/reviewer's responsibility.
124    pub min_sources: usize,
125    /// Threshold for reporting a confident blocked claim, from zero to 10000 inclusive.
126    pub high_confidence_bps: u16,
127}
128
129impl Default for AnswerPolicy {
130    fn default() -> Self {
131        Self {
132            min_sources: 1,
133            high_confidence_bps: 8000,
134        }
135    }
136}
137
138/// Why a claim cannot be released. Multiple failures can apply to one claim.
139#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
140#[serde(rename_all = "snake_case")]
141pub enum ClaimIssue {
142    /// No citation was proposed.
143    Uncited,
144    /// A cited node is absent from the current selected context.
145    InvalidCitation,
146    /// Too few distinct provenance groups remain after collapsing copies and shared sources.
147    InsufficientSources,
148    /// No trusted review exists for this exact claim and snapshot.
149    Unreviewed,
150    /// Trusted review found insufficient support.
151    Unsupported,
152    /// Trusted review found conflicting evidence.
153    Contradicted,
154    /// Trusted review could not determine support.
155    Unknown,
156    /// Declared counterevidence in the cited nodes' hard closure was not reviewed.
157    UnreviewedCounterevidence,
158}
159
160/// Content-free per-claim result in draft order.
161#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
162#[serde(deny_unknown_fields)]
163pub struct ClaimAssessment {
164    /// Exact key assessed.
165    pub claim_key: String,
166    /// Number of distinct provenance groups, not a semantic support score.
167    pub independent_sources: usize,
168    /// Empty only when the complete review contract is satisfied.
169    pub issues: Vec<ClaimIssue>,
170}
171
172/// All-or-nothing disposition; a single failed claim blocks the whole draft.
173#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
174#[serde(rename_all = "snake_case")]
175pub enum AnswerDecision {
176    /// Every claim passed the trusted review contract.
177    Release,
178    /// The application must abstain, gather evidence or revise and obtain a new review.
179    Abstain,
180}
181
182/// Assessment against the graph's current authorization and source state.
183/// This is a transient result, not a signed certificate. Recheck after any state/policy change.
184#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
185#[serde(deny_unknown_fields)]
186pub struct AnswerAssessment {
187    /// Exact context assessed.
188    pub snapshot_id: String,
189    /// Exact draft assessed, including explicit abstention.
190    pub draft_id: String,
191    /// All-or-nothing release decision.
192    pub decision: AnswerDecision,
193    /// Per-claim failures, without copying claim/source text into operational telemetry.
194    pub claims: Vec<ClaimAssessment>,
195    /// Failed claims whose supplied confidence reaches the policy threshold.
196    /// This is a gate-failure count, not an independently measured hallucination count.
197    pub confident_failures: usize,
198    /// Claims without elicited confidence. Missing confidence is never imputed.
199    pub missing_confidence: usize,
200}
201
202impl ContextGraph {
203    /// Check a draft using independently supplied trusted reviews and current authorization.
204    ///
205    /// Recompiles `request` and requires the exact snapshot given to the model. Every citation
206    /// must occur in that selected evidence; every claim needs a supported trusted review.
207    /// Known hard dependencies/counterclaims are traversed without dropping conflicts. Raising
208    /// or lowering confidence never bypasses a failed review. No semantic judge runs here.
209    ///
210    /// The application must keep `reviews`, `policy` and authorization outside model control,
211    /// and display only the assessed claims on `Release`. The runtime cannot establish that a
212    /// model decomposed every factual assertion or that a supplied judge is truthful/accurate.
213    pub fn check_answer(
214        &self,
215        request: &ContextRequest,
216        draft: &AnswerDraft,
217        reviews: &[ClaimReview],
218        policy: &AnswerPolicy,
219        tokenizer: &impl TokenCounter,
220    ) -> Result<AnswerAssessment, ContextError> {
221        let (keys, review_map) = prepare_reviews(draft, reviews, policy)?;
222        let snapshot = self.compile(request, tokenizer)?;
223        self.assess_snapshot(&snapshot, draft, reviews, policy, (keys, review_map))
224    }
225
226    // Only call after freshly proving that this snapshot's complete authorized scope,
227    // request, evidence and policy still match the current graph. A digest is not authority.
228    pub(crate) fn check_view_snapshot(
229        &self,
230        snapshot: &ContextSnapshot,
231        draft: &AnswerDraft,
232        reviews: &[ClaimReview],
233        policy: &AnswerPolicy,
234    ) -> Result<AnswerAssessment, ContextError> {
235        let (keys, review_map) = prepare_reviews(draft, reviews, policy)?;
236        self.assess_snapshot(snapshot, draft, reviews, policy, (keys, review_map))
237    }
238
239    fn assess_snapshot(
240        &self,
241        snapshot: &ContextSnapshot,
242        draft: &AnswerDraft,
243        reviews: &[ClaimReview],
244        policy: &AnswerPolicy,
245        prepared: PreparedReviews<'_>,
246    ) -> Result<AnswerAssessment, ContextError> {
247        let (keys, review_map) = prepared;
248        if snapshot.id() != draft.snapshot_id {
249            return Err(ContextError::BaseMismatch);
250        }
251        let selected = snapshot
252            .blocks()
253            .iter()
254            .flat_map(|block| block.citations.iter().map(|citation| &citation.node_id))
255            .collect::<BTreeSet<_>>();
256        if reviews.iter().any(|review| {
257            review
258                .reviewed_counterevidence
259                .iter()
260                .any(|id| !selected.contains(id))
261        }) {
262            return Err(ContextError::InvalidInput);
263        }
264        let mut claims = Vec::new();
265        let mut confident_failures = 0;
266        let mut missing_confidence = 0;
267        for (claim, key) in draft.claims.iter().zip(keys) {
268            let mut issues = Vec::new();
269            if claim.citations.is_empty() {
270                issues.push(ClaimIssue::Uncited);
271            }
272            if claim.citations.iter().any(|id| !selected.contains(id)) {
273                issues.push(ClaimIssue::InvalidCitation);
274            }
275            let cited = claim
276                .citations
277                .iter()
278                .filter(|id| selected.contains(*id))
279                .filter_map(|id| self.documents.get(id))
280                .collect::<Vec<_>>();
281            // Connected components prevent copies, chunks and transitive aliases from voting
282            // repeatedly. At most 64 nodes; using exact complete-text digests costs no BPE work.
283            let mut groups: Vec<BTreeSet<usize>> = Vec::new();
284            for (index, node) in cited.iter().enumerate() {
285                let mut group = BTreeSet::from([index]);
286                groups.retain(|existing| {
287                    if existing.iter().any(|i| {
288                        cited.get(*i).is_some_and(|prior| {
289                            prior.document.source == node.document.source
290                                || prior.text_digest == node.text_digest
291                        })
292                    }) {
293                        group.extend(existing);
294                        false
295                    } else {
296                        true
297                    }
298                });
299                groups.push(group);
300            }
301            let independent_sources = groups.len();
302            if independent_sources < policy.min_sources {
303                issues.push(ClaimIssue::InsufficientSources);
304            }
305            let counterevidence = self.answer_counterevidence(&claim.citations, &selected);
306            match review_map.get(&key) {
307                None => issues.push(ClaimIssue::Unreviewed),
308                Some(review) => {
309                    match review.verdict {
310                        ClaimVerdict::Supported => {}
311                        ClaimVerdict::Unsupported => issues.push(ClaimIssue::Unsupported),
312                        ClaimVerdict::Contradicted => issues.push(ClaimIssue::Contradicted),
313                        ClaimVerdict::Unknown => issues.push(ClaimIssue::Unknown),
314                    }
315                    if !counterevidence.is_subset(&review.reviewed_counterevidence) {
316                        issues.push(ClaimIssue::UnreviewedCounterevidence);
317                    }
318                }
319            }
320            if !issues.is_empty()
321                && claim
322                    .confidence_bps
323                    .is_some_and(|value| value >= policy.high_confidence_bps)
324            {
325                confident_failures += 1;
326            }
327            missing_confidence += usize::from(claim.confidence_bps.is_none());
328            claims.push(ClaimAssessment {
329                claim_key: key,
330                independent_sources,
331                issues,
332            });
333        }
334        let decision = if !draft.abstain
335            && !claims.is_empty()
336            && claims.iter().all(|claim| claim.issues.is_empty())
337        {
338            AnswerDecision::Release
339        } else {
340            AnswerDecision::Abstain
341        };
342        Ok(AnswerAssessment {
343            snapshot_id: snapshot.id().to_owned(),
344            draft_id: digest("cigar.answer-draft.v1", draft)?,
345            decision,
346            claims,
347            confident_failures,
348            missing_confidence,
349        })
350    }
351
352    fn answer_counterevidence(
353        &self,
354        citations: &BTreeSet<String>,
355        selected: &BTreeSet<&String>,
356    ) -> BTreeSet<String> {
357        let mut seen = BTreeSet::new();
358        let mut pending = citations
359            .iter()
360            .filter(|id| selected.contains(*id))
361            .collect::<Vec<_>>();
362        let mut counterevidence = BTreeSet::new();
363        while let Some(id) = pending.pop() {
364            if !seen.insert(id) {
365                continue;
366            }
367            if let Some(edges) = self.edges.get(id) {
368                for (kind, target) in edges {
369                    if selected.contains(target)
370                        && matches!(kind, EdgeKind::Requires | EdgeKind::Contradicts)
371                    {
372                        if *kind == EdgeKind::Contradicts && !citations.contains(target) {
373                            counterevidence.insert(target.clone());
374                        }
375                        pending.push(target);
376                    }
377                }
378            }
379        }
380        counterevidence
381    }
382}
383
384type PreparedReviews<'a> = (Vec<String>, BTreeMap<&'a String, &'a ClaimReview>);
385
386fn prepare_reviews<'a>(
387    draft: &AnswerDraft,
388    reviews: &'a [ClaimReview],
389    policy: &AnswerPolicy,
390) -> Result<PreparedReviews<'a>, ContextError> {
391    if !(1..=4).contains(&policy.min_sources)
392        || policy.high_confidence_bps > 10000
393        || reviews.len() > 128
394    {
395        return Err(ContextError::InvalidInput);
396    }
397    let keys = draft.review_keys()?;
398    let mut review_map = BTreeMap::new();
399    for review in reviews {
400        if !keys.contains(&review.claim_key)
401            || review.reviewed_counterevidence.len() > 4096
402            || review
403                .reviewed_counterevidence
404                .iter()
405                .any(|id| !crate::graph::valid_id(id))
406            || review_map.insert(&review.claim_key, review).is_some()
407        {
408            return Err(ContextError::InvalidInput);
409        }
410    }
411    Ok((keys, review_map))
412}
413
414fn valid_digest(value: &str) -> bool {
415    value.len() == 64
416        && value
417            .bytes()
418            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
419}