Skip to main content

hol_cigar/
views.rs

1//! Host-scoped views over one graph/index. No scheduler, authentication service or new effect journal.
2use crate::{
3    AnswerAssessment, AnswerDraft, AnswerPolicy, ClaimReview, ContextError, ContextGraph,
4    ContextRequest, ContextSnapshot, Document, SelectionExplanation, SelectionStep, SourceUpdate,
5    TokenCounter, digest,
6};
7use serde::{Deserialize, Serialize};
8use std::collections::{BTreeMap, BTreeSet};
9
10const MAX_VIEWS: usize = 128;
11const MAX_SOURCES: usize = 256;
12
13/// Host-owned scope. Source locators are application metadata, not authenticated identities.
14/// Keep definition/revocation and the root graph handle outside untrusted agent control.
15#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
16#[serde(deny_unknown_fields)]
17pub struct ContextViewSpec {
18    /// Stable host-assigned agent or task scope name.
19    pub id: String,
20    /// Exact source locators readable through this view; empty means no access.
21    pub allowed_sources: BTreeSet<String>,
22    /// Exact source locators replaceable through this view; must be readable too.
23    #[serde(default)]
24    pub writable_sources: BTreeSet<String>,
25    /// Host-owned current authorization/policy epoch. It overrides request policy metadata.
26    pub policy_revision: String,
27}
28
29/// A live generation prevents use of a superseded/revoked view in this worker session.
30/// This is a routing handle, not a bearer credential or a signed capability.
31#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
32#[serde(deny_unknown_fields)]
33pub struct ContextViewHandle {
34    /// Host-assigned scope name.
35    pub id: String,
36    /// Monotonically increasing within the owning worker session.
37    pub generation: u64,
38}
39
40/// Original context plus an independently versioned scope commitment.
41/// The legacy snapshot and claim-review keys retain their original exact identities.
42#[derive(Clone, Serialize, Deserialize)]
43#[serde(deny_unknown_fields)]
44pub struct ContextView {
45    id: String,
46    view: ContextViewHandle,
47    request: ContextRequest,
48    scope_id: String,
49    snapshot: ContextSnapshot,
50}
51
52impl std::fmt::Debug for ContextView {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("ContextView").finish_non_exhaustive()
55    }
56}
57
58impl ContextView {
59    /// Commitment to the exact scope, request and original legacy snapshot.
60    #[must_use]
61    pub fn id(&self) -> &str {
62        &self.id
63    }
64
65    /// Original snapshot supplied to the generator and reviewer.
66    #[must_use]
67    pub const fn snapshot(&self) -> &ContextSnapshot {
68        &self.snapshot
69    }
70
71    fn commitment(&self) -> Result<String, ContextError> {
72        digest(
73            "cigar.context-view.v1",
74            &(
75                &self.view,
76                &self.request,
77                &self.scope_id,
78                self.snapshot.id(),
79            ),
80        )
81    }
82}
83
84/// Transient checked result, not a signature, durable approval, or permission for an effect.
85#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
86#[serde(deny_unknown_fields)]
87pub struct ContextViewAssessment {
88    /// Exact original view context assessed.
89    pub context_id: String,
90    /// Current graph revision at atomic in-process assessment.
91    pub checked_graph_revision: u64,
92    /// Existing answer assessment, bound to the original snapshot and reviews.
93    pub assessment: AnswerAssessment,
94}
95
96struct Entry {
97    handle: ContextViewHandle,
98    spec: ContextViewSpec,
99}
100
101/// Bounded view definitions for a single host-owned graph. Stores no duplicate documents.
102#[derive(Default)]
103pub struct ContextViews {
104    generation: u64,
105    entries: BTreeMap<String, Entry>,
106}
107
108impl ContextViews {
109    /// Define or replace a host-owned scope. Every replacement invalidates its old handles.
110    pub fn define(&mut self, spec: ContextViewSpec) -> Result<ContextViewHandle, ContextError> {
111        if !crate::graph::valid_id(&spec.id)
112            || spec.allowed_sources.len() > MAX_SOURCES
113            || !spec.writable_sources.is_subset(&spec.allowed_sources)
114            || spec.allowed_sources.iter().any(|source| {
115                source.is_empty() || source.len() > 2048 || source.chars().any(char::is_control)
116            })
117            || spec.policy_revision.is_empty()
118            || spec.policy_revision.len() > 256
119        {
120            return Err(ContextError::InvalidInput);
121        }
122        if !self.entries.contains_key(&spec.id) && self.entries.len() >= MAX_VIEWS {
123            return Err(ContextError::LimitExceeded);
124        }
125        self.generation = self
126            .generation
127            .checked_add(1)
128            .ok_or(ContextError::LimitExceeded)?;
129        let handle = ContextViewHandle {
130            id: spec.id.clone(),
131            generation: self.generation,
132        };
133        self.entries.insert(
134            spec.id.clone(),
135            Entry {
136                handle: handle.clone(),
137                spec,
138            },
139        );
140        Ok(handle)
141    }
142
143    /// Revoke a scope. Existing context cannot be used through that view afterward.
144    pub fn revoke(&mut self, id: &str) -> bool {
145        self.entries.remove(id).is_some()
146    }
147
148    fn entry(&self, handle: &ContextViewHandle) -> Result<&Entry, ContextError> {
149        self.entries
150            .get(&handle.id)
151            .filter(|entry| entry.handle == *handle)
152            .ok_or(ContextError::RequiredUnavailable)
153    }
154
155    /// Compile against current authorized sources. Request `allowed` may only narrow access.
156    pub fn compile(
157        &self,
158        graph: &ContextGraph,
159        handle: &ContextViewHandle,
160        request: &ContextRequest,
161        tokenizer: &impl TokenCounter,
162    ) -> Result<ContextView, ContextError> {
163        self.compile_bound(graph, handle, request, tokenizer, None)
164    }
165
166    // The broker binds epoch and source authority into the existing snapshot/review chain.
167    // None preserves ordinary view identities and serialized shapes byte-for-byte.
168    pub(crate) fn compile_bound(
169        &self,
170        graph: &ContextGraph,
171        handle: &ContextViewHandle,
172        request: &ContextRequest,
173        tokenizer: &impl TokenCounter,
174        authority: Option<&str>,
175    ) -> Result<ContextView, ContextError> {
176        self.compile_traced(graph, handle, request, tokenizer, authority, None)
177    }
178
179    #[allow(clippy::too_many_arguments)] // Optional observation of the unchanged selection path.
180    fn compile_traced(
181        &self,
182        graph: &ContextGraph,
183        handle: &ContextViewHandle,
184        request: &ContextRequest,
185        tokenizer: &impl TokenCounter,
186        authority: Option<&str>,
187        trace: Option<&mut Vec<SelectionStep>>,
188    ) -> Result<ContextView, ContextError> {
189        let entry = self.entry(handle)?;
190        let authorized = authorized_nodes(graph, &entry.spec);
191        let mut scope_id = scope_id(graph, entry, &authorized)?;
192        if let Some(authority) = authority {
193            scope_id = digest("cigar.context-view-authority.v1", &(&scope_id, authority))?;
194        }
195        let scoped = scoped_request(request, &scope_id, &authorized);
196        let snapshot = graph.compile_traced(&scoped, tokenizer, trace)?;
197        let mut context = ContextView {
198            id: String::new(),
199            view: handle.clone(),
200            request: request.clone(),
201            scope_id,
202            snapshot,
203        };
204        context.id = context.commitment()?;
205        Ok(context)
206    }
207
208    /// Atomic replacement restricted to a writable source, including cross-source ID collisions.
209    pub fn replace_source(
210        &self,
211        graph: &mut ContextGraph,
212        handle: &ContextViewHandle,
213        source: &str,
214        documents: Vec<Document>,
215    ) -> Result<SourceUpdate, ContextError> {
216        let entry = self.entry(handle)?;
217        if !entry.spec.writable_sources.contains(source)
218            || documents.iter().any(|doc| {
219                doc.source != source
220                    || graph
221                        .documents
222                        .get(&doc.id)
223                        .is_some_and(|old| old.document.source != source)
224            })
225        {
226            return Err(ContextError::RequiredUnavailable);
227        }
228        graph.replace_source(source, documents)
229    }
230
231    /// Freshly validate the whole readable scope and recompile before applying trusted reviews.
232    /// Alpha policy is conservative: ANY authorized document/edge change requires a new review,
233    /// including unselected evidence. Unrelated writes outside this view do not invalidate it.
234    #[allow(clippy::too_many_arguments)] // Same review contract plus explicit graph/view ownership.
235    pub fn check_answer(
236        &self,
237        graph: &ContextGraph,
238        handle: &ContextViewHandle,
239        context: &ContextView,
240        draft: &AnswerDraft,
241        reviews: &[ClaimReview],
242        policy: &AnswerPolicy,
243        tokenizer: &impl TokenCounter,
244    ) -> Result<ContextViewAssessment, ContextError> {
245        self.revalidate(graph, handle, context, tokenizer)?;
246        let assessment = graph.check_view_snapshot(&context.snapshot, draft, reviews, policy)?;
247        Ok(ContextViewAssessment {
248            context_id: context.id.clone(),
249            checked_graph_revision: graph.revision(),
250            assessment,
251        })
252    }
253
254    // Shared freshness check for the ordinary trusted-host view and the opt-in broker.
255    // Never substitute snapshot integrity alone for current authorization and evidence.
256    pub(crate) fn revalidate(
257        &self,
258        graph: &ContextGraph,
259        handle: &ContextViewHandle,
260        context: &ContextView,
261        tokenizer: &impl TokenCounter,
262    ) -> Result<(), ContextError> {
263        self.revalidate_bound(graph, handle, context, tokenizer, None)
264    }
265
266    pub(crate) fn revalidate_bound(
267        &self,
268        graph: &ContextGraph,
269        handle: &ContextViewHandle,
270        context: &ContextView,
271        tokenizer: &impl TokenCounter,
272        authority: Option<&str>,
273    ) -> Result<(), ContextError> {
274        self.revalidate_traced(graph, handle, context, tokenizer, authority, None)
275    }
276
277    /// Reconstruct only successful selection steps after checking the current whole scope.
278    /// Revocation and any in-scope change invalidate the explanation, including unselected data.
279    pub fn explain(
280        &self,
281        graph: &ContextGraph,
282        handle: &ContextViewHandle,
283        context: &ContextView,
284        tokenizer: &impl TokenCounter,
285    ) -> Result<SelectionExplanation, ContextError> {
286        self.explain_bound(graph, handle, context, tokenizer, None)
287    }
288
289    pub(crate) fn explain_bound(
290        &self,
291        graph: &ContextGraph,
292        handle: &ContextViewHandle,
293        context: &ContextView,
294        tokenizer: &impl TokenCounter,
295        authority: Option<&str>,
296    ) -> Result<SelectionExplanation, ContextError> {
297        let mut steps = Vec::new();
298        self.revalidate_traced(
299            graph,
300            handle,
301            context,
302            tokenizer,
303            authority,
304            Some(&mut steps),
305        )?;
306        SelectionExplanation::new(
307            &context.snapshot,
308            &context.request,
309            graph.revision(),
310            tokenizer,
311            steps,
312        )
313    }
314
315    #[allow(clippy::too_many_arguments)] // Current-state checks plus an optional trace observer.
316    fn revalidate_traced(
317        &self,
318        graph: &ContextGraph,
319        handle: &ContextViewHandle,
320        context: &ContextView,
321        tokenizer: &impl TokenCounter,
322        authority: Option<&str>,
323        trace: Option<&mut Vec<SelectionStep>>,
324    ) -> Result<(), ContextError> {
325        self.entry(handle)?;
326        if context.view != *handle {
327            return Err(ContextError::BaseMismatch);
328        }
329        context.snapshot.verify(tokenizer)?;
330        if context.id != context.commitment()? {
331            return Err(ContextError::Integrity);
332        }
333        let current =
334            self.compile_traced(graph, handle, &context.request, tokenizer, authority, trace)?;
335        if context.scope_id != current.scope_id
336            || !context.snapshot.same_view_evidence(&current.snapshot)
337        {
338            return Err(ContextError::BaseMismatch);
339        }
340        Ok(())
341    }
342}
343
344fn authorized_nodes(graph: &ContextGraph, spec: &ContextViewSpec) -> BTreeSet<String> {
345    spec.allowed_sources
346        .iter()
347        .filter_map(|source| graph.sources.get(source))
348        .flat_map(|ids| ids.iter().cloned())
349        .collect()
350}
351
352fn scoped_request(
353    request: &ContextRequest,
354    scope_id: &str,
355    authorized: &BTreeSet<String>,
356) -> ContextRequest {
357    let mut scoped = request.clone();
358    scoped.allowed = Some(
359        authorized
360            .iter()
361            .filter(|id| {
362                request
363                    .allowed
364                    .as_ref()
365                    .is_none_or(|narrowed| narrowed.contains(*id))
366            })
367            .cloned()
368            .collect(),
369    );
370    // Bind the entire authorized scope into the EXISTING snapshot/review-key chain.
371    // Changing a public envelope digest cannot rebind an old review to new authority/data.
372    scoped.policy_revision = scope_id.to_owned();
373    scoped
374}
375
376fn scope_id(
377    graph: &ContextGraph,
378    entry: &Entry,
379    authorized: &BTreeSet<String>,
380) -> Result<String, ContextError> {
381    let documents = graph
382        .authorized_documents(authorized)
383        .map(|(id, doc)| (id, &doc.digest))
384        .collect::<Vec<_>>();
385    let edges = authorized
386        .iter()
387        .filter_map(|id| graph.edges.get(id).map(|edges| (id, edges)))
388        .collect::<Vec<_>>();
389    digest(
390        "cigar.context-view-scope.v1",
391        &(&graph.domain, &entry.handle, &entry.spec, documents, edges),
392    )
393}