Skip to main content

hol_cigar/
snapshot.rs

1use crate::{ContextError, SelectionStats, TokenCounter, digest};
2use serde::{Deserialize, Serialize};
3use std::collections::{BTreeMap, BTreeSet};
4
5/// Exact source location and commitment for a retained excerpt.
6#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
7#[serde(deny_unknown_fields)]
8pub struct Citation {
9    /// Stable source node identity.
10    pub node_id: String,
11    /// Caller-provided source locator.
12    pub source: String,
13    /// Digest of the complete original document, including identity and locator.
14    pub document_digest: String,
15    /// One-based first source line, inclusive.
16    pub start_line: usize,
17    /// One-based last source line, inclusive.
18    pub end_line: usize,
19}
20
21/// One physical context block, possibly shared by several exact-text source aliases.
22#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
23#[serde(deny_unknown_fields)]
24pub struct EvidenceBlock {
25    /// Exact full text or explicitly marked extractive windows.
26    pub text: String,
27    /// Sorted source citations, retaining every selected alias.
28    pub citations: Vec<Citation>,
29}
30
31impl std::fmt::Debug for EvidenceBlock {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.debug_struct("EvidenceBlock")
34            .field("bytes", &self.text.len())
35            .field("citations", &self.citations.len())
36            .finish_non_exhaustive()
37    }
38}
39
40impl EvidenceBlock {
41    pub(crate) fn new(text: String, mut citations: Vec<Citation>) -> Result<Self, ContextError> {
42        citations.sort();
43        citations.dedup();
44        let block = Self { text, citations };
45        block.validate()?;
46        Ok(block)
47    }
48
49    /// Identity binds both text and all source citations.
50    pub fn id(&self) -> Result<String, ContextError> {
51        digest("cigar.evidence-block.v1", self)
52    }
53
54    fn validate(&self) -> Result<(), ContextError> {
55        if self.text.is_empty()
56            || self.text.len() > 1_048_576
57            || self.citations.is_empty()
58            || self.citations.len() > 4096
59            || self.citations.windows(2).any(|w| w.first() >= w.get(1))
60            || self.citations.iter().any(|c| {
61                !crate::graph::valid_id(&c.node_id)
62                    || c.source.is_empty()
63                    || c.source.len() > 2048
64                    || c.source.chars().any(char::is_control)
65                    || !valid_digest(&c.document_digest)
66                    || c.start_line == 0
67                    || c.end_line < c.start_line
68            })
69        {
70            return Err(ContextError::Integrity);
71        }
72        Ok(())
73    }
74}
75
76/// A complete ordered context and its integrity commitment. Digests are not signatures.
77#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
78#[serde(deny_unknown_fields)]
79pub struct ContextSnapshot {
80    id: String,
81    domain: String,
82    policy_revision: String,
83    tokenizer: String,
84    graph_revision: u64,
85    blocks: Vec<EvidenceBlock>,
86    stats: SelectionStats,
87}
88
89impl ContextSnapshot {
90    // Scoped views may reuse reviews across unrelated global revisions, but never
91    // across a domain, scoped policy/content epoch, tokenizer or evidence change.
92    pub(crate) fn same_view_evidence(&self, other: &Self) -> bool {
93        self.domain == other.domain
94            && self.policy_revision == other.policy_revision
95            && self.tokenizer == other.tokenizer
96            && self.blocks == other.blocks
97            && self.stats == other.stats
98    }
99
100    pub(crate) fn seal(
101        domain: &str,
102        policy: &str,
103        tokenizer: &str,
104        revision: u64,
105        blocks: Vec<EvidenceBlock>,
106        stats: SelectionStats,
107    ) -> Result<Self, ContextError> {
108        let mut value = Self {
109            id: String::new(),
110            domain: domain.to_owned(),
111            policy_revision: policy.to_owned(),
112            tokenizer: tokenizer.to_owned(),
113            graph_revision: revision,
114            blocks,
115            stats,
116        };
117        value.id = value.commitment()?;
118        Ok(value)
119    }
120
121    fn commitment(&self) -> Result<String, ContextError> {
122        digest(
123            "cigar.context-snapshot.v1",
124            &(
125                &self.domain,
126                &self.policy_revision,
127                &self.tokenizer,
128                self.graph_revision,
129                &self.blocks,
130                &self.stats,
131            ),
132        )
133    }
134
135    /// Complete snapshot identity, suitable for exact delta base matching.
136    #[must_use]
137    pub fn id(&self) -> &str {
138        &self.id
139    }
140
141    /// Selected physical evidence, including citations.
142    #[must_use]
143    pub fn blocks(&self) -> &[EvidenceBlock] {
144        &self.blocks
145    }
146
147    /// Content-free query measurements.
148    #[must_use]
149    pub const fn stats(&self) -> &SelectionStats {
150        &self.stats
151    }
152
153    /// Render source citations and content as ordinary quoted JSON data, one block per line.
154    /// The application must place this text in its data/context role, never an instruction role.
155    #[must_use]
156    pub fn render(&self) -> String {
157        render(&self.blocks)
158    }
159
160    /// Recomputes integrity, bounds, and exact final token count after loading or receiving data.
161    pub fn verify(&self, tokenizer: &impl TokenCounter) -> Result<(), ContextError> {
162        let sources = self.verify_structure(tokenizer)?;
163        let tokens = tokenizer.count(&self.render())?;
164        self.verify_commitment_and_stats(tokens, sources)
165    }
166
167    /// Verifies the complete snapshot and returns its canonical rendered evidence.
168    /// Performs the same checks as [`Self::verify`] while rendering only once.
169    /// No text is returned when integrity, tokenizer or budget validation fails.
170    pub fn render_verified(&self, tokenizer: &impl TokenCounter) -> Result<String, ContextError> {
171        let sources = self.verify_structure(tokenizer)?;
172        let rendered = self.render();
173        let tokens = tokenizer.count(&rendered)?;
174        self.verify_commitment_and_stats(tokens, sources)?;
175        Ok(rendered)
176    }
177
178    fn verify_structure(&self, tokenizer: &impl TokenCounter) -> Result<usize, ContextError> {
179        if self.domain.is_empty()
180            || self.domain.len() > 256
181            || self.policy_revision.is_empty()
182            || self.policy_revision.len() > 256
183            || self.tokenizer != tokenizer.identity()
184            || !valid_digest(&self.id)
185            || self.blocks.len() > 4096
186            || self.blocks.iter().map(|b| b.text.len()).sum::<usize>() > 16_777_216
187        {
188            return Err(ContextError::Integrity);
189        }
190        for block in &self.blocks {
191            block.validate()?;
192        }
193        let mut ids = BTreeSet::new();
194        for block in &self.blocks {
195            if !ids.insert(block.id()?) {
196                return Err(ContextError::Integrity);
197            }
198        }
199        let sources = self
200            .blocks
201            .iter()
202            .flat_map(|b| b.citations.iter().map(|c| &c.node_id))
203            .collect::<BTreeSet<_>>();
204        Ok(sources.len())
205    }
206
207    fn verify_commitment_and_stats(
208        &self,
209        tokens: usize,
210        sources: usize,
211    ) -> Result<(), ContextError> {
212        if self.commitment()? != self.id
213            || self.stats.selected_blocks != self.blocks.len()
214            || self.stats.selected_sources != sources
215            || self.stats.rendered_tokens != tokens
216            || tokens > self.stats.available_tokens
217        {
218            return Err(ContextError::Integrity);
219        }
220        Ok(())
221    }
222
223    /// Builds a delta for a receiver that retains the exact base. Policy changes require full refresh.
224    pub fn delta_from(
225        &self,
226        base: &Self,
227        tokenizer: &impl TokenCounter,
228    ) -> Result<ContextDelta, ContextError> {
229        self.verify(tokenizer)?;
230        base.verify(tokenizer)?;
231        if self.domain != base.domain
232            || self.policy_revision != base.policy_revision
233            || self.tokenizer != base.tokenizer
234        {
235            return Err(ContextError::BaseMismatch);
236        }
237        let prior = base
238            .blocks
239            .iter()
240            .map(EvidenceBlock::id)
241            .collect::<Result<BTreeSet<_>, _>>()?;
242        let mut order = Vec::new();
243        let mut added = Vec::new();
244        for block in &self.blocks {
245            let id = block.id()?;
246            if !prior.contains(&id) {
247                added.push(block.clone());
248            }
249            order.push(id);
250        }
251        Ok(ContextDelta {
252            base_id: base.id.clone(),
253            target_id: self.id.clone(),
254            graph_revision: self.graph_revision,
255            stats: self.stats.clone(),
256            order,
257            added,
258        })
259    }
260}
261
262/// A verified transport delta. It saves network/storage bytes, not stateless model prompt tokens.
263#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
264#[serde(deny_unknown_fields)]
265pub struct ContextDelta {
266    base_id: String,
267    target_id: String,
268    graph_revision: u64,
269    stats: SelectionStats,
270    order: Vec<String>,
271    added: Vec<EvidenceBlock>,
272}
273
274impl ContextDelta {
275    /// Number of blocks whose complete bytes must be transported.
276    #[must_use]
277    pub fn added_blocks(&self) -> usize {
278        self.added.len()
279    }
280
281    /// Reconstructs and verifies a complete snapshot; omission in `order` withdraws old content.
282    pub fn apply(
283        &self,
284        base: &ContextSnapshot,
285        tokenizer: &impl TokenCounter,
286    ) -> Result<ContextSnapshot, ContextError> {
287        base.verify(tokenizer)?;
288        if self.base_id != base.id {
289            return Err(ContextError::BaseMismatch);
290        }
291        if self.order.len() > 4096
292            || self.added.len() > self.order.len()
293            || self.order.iter().collect::<BTreeSet<_>>().len() != self.order.len()
294        {
295            return Err(ContextError::Integrity);
296        }
297        let mut values = base
298            .blocks
299            .iter()
300            .map(|block| block.id().map(|id| (id, block.clone())))
301            .collect::<Result<BTreeMap<_, _>, _>>()?;
302        for block in &self.added {
303            block.validate()?;
304            let id = block.id()?;
305            if !self.order.contains(&id) || values.insert(id, block.clone()).is_some() {
306                return Err(ContextError::Integrity);
307            }
308        }
309        let blocks = self
310            .order
311            .iter()
312            .map(|id| values.remove(id).ok_or(ContextError::Integrity))
313            .collect::<Result<Vec<_>, _>>()?;
314        let candidate = ContextSnapshot::seal(
315            &base.domain,
316            &base.policy_revision,
317            &base.tokenizer,
318            self.graph_revision,
319            blocks,
320            self.stats.clone(),
321        )?;
322        if candidate.id != self.target_id {
323            return Err(ContextError::Integrity);
324        }
325        candidate.verify(tokenizer)?;
326        Ok(candidate)
327    }
328}
329
330#[derive(Serialize)]
331struct Rendered<'a> {
332    sources: Vec<(&'a str, &'a str, usize, usize)>,
333    text: &'a str,
334}
335
336pub(crate) fn render(blocks: &[EvidenceBlock]) -> String {
337    blocks
338        .iter()
339        .map(|block| {
340            let rendered = Rendered {
341                sources: block
342                    .citations
343                    .iter()
344                    .map(|c| {
345                        (
346                            c.node_id.as_str(),
347                            c.source.as_str(),
348                            c.start_line,
349                            c.end_line,
350                        )
351                    })
352                    .collect(),
353                text: &block.text,
354            };
355            // Serializing strings, vectors, and integers to an owned string is infallible.
356            serde_json::to_string(&rendered).unwrap_or_default()
357        })
358        .collect::<Vec<_>>()
359        .join("\n")
360}
361
362fn valid_digest(value: &str) -> bool {
363    value.len() == 64
364        && value
365            .bytes()
366            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
367}