hol-cigar 0.14.2

Open-source context engineering protocol for AI agents: governed retrieval, bounded multi-agent handoffs, MCP, provenance, recoverable effects, and replay.
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
//! Evidence-only recovery. This codec does not write files or claim durable commit.
//! Applications must protect checkpoint bytes; a digest is not a publisher signature.

use super::{
    BrokerError, BrokerLimits, ContextBroker, EdgeNode, MAX_PROVENANCE_BYTES, SourceProvenance,
    SourceRecord, hex, measure, unix_ms, valid_label, valid_source,
};
use crate::{ContextError, Document, EdgeKind, GraphLimits};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{BufWriter, Write};
use std::time::{Duration, Instant};

const SCHEMA: &str = "cigar.broker-checkpoint.v1";
const MAX_BYTES: usize = 512 * 1024 * 1024;

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SourceImage {
    source: String,
    version: u64,
    provenance: SourceProvenance,
    // Preserve the remaining monotonic bound. Recovery also rejects a clock before capture.
    remaining_ms: Option<u64>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct State {
    domain: String,
    prior_epoch: String,
    captured_at_ms: u64,
    graph_revision: u64,
    sources: Vec<SourceImage>,
    documents: Vec<Document>,
    edges: BTreeMap<String, BTreeSet<(EdgeKind, String)>>,
    edge_owners: BTreeMap<String, String>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Envelope {
    schema: String,
    state: State,
    sha256: String,
}

/// Opaque, bounded evidence checkpoint. It contains source text and must be kept private.
/// It never contains grant secrets, tickets, proposals, drafts, verdicts or effect permissions.
/// Encoding/decoding alone does not provide atomic storage, encryption or authentication.
pub struct BrokerCheckpoint {
    envelope: Envelope,
}

impl std::fmt::Debug for BrokerCheckpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BrokerCheckpoint").finish_non_exhaustive()
    }
}

impl BrokerCheckpoint {
    /// Copy the canonical private bytes, rejecting a caller limit outside 1..=512 MiB.
    pub fn encode(&self, max_bytes: usize) -> Result<Vec<u8>, BrokerError> {
        let mut bytes = Vec::new();
        self.encode_into(&mut bytes, max_bytes)?;
        Ok(bytes)
    }

    /// Replace a reusable private buffer with the canonical bytes. On error its length is zero;
    /// capacity may remain allocated. This is not memory zeroization. Limits match `encode`.
    pub fn encode_into(&self, bytes: &mut Vec<u8>, max_bytes: usize) -> Result<(), BrokerError> {
        bytes.clear();
        valid_bound(max_bytes)?;
        bounded_encode_into(&self.envelope, bytes, max_bytes)
    }

    /// Decode only exact versioned canonical bytes with a matching content digest. Restore
    /// performs domain, current limits and graph/lineage validation before exposing any graph.
    pub fn decode(bytes: &[u8], max_bytes: usize) -> Result<Self, BrokerError> {
        valid_bound(max_bytes)?;
        if bytes.len() > max_bytes {
            return Err(BrokerError::Quota);
        }
        let envelope: Envelope = serde_json::from_slice(bytes).map_err(|_| integrity())?;
        if envelope.schema != SCHEMA
            || envelope.sha256 != checkpoint_digest(&envelope.state)?
            || bounded_encode(&envelope, max_bytes)? != bytes
        {
            return Err(integrity());
        }
        Ok(Self { envelope })
    }
}

impl ContextBroker {
    /// Capture current evidence and its freshness bounds. This is an explicit in-memory
    /// checkpoint, not a durable commit; credentials and all transient authority are excluded.
    pub fn host_checkpoint(&self, max_bytes: usize) -> Result<BrokerCheckpoint, BrokerError> {
        valid_bound(max_bytes)?;
        self.graph
            .documents
            .values()
            .try_fold(0_usize, |bytes, node| {
                bytes
                    .checked_add(node.document.text.len())
                    .filter(|total| *total <= max_bytes)
                    .ok_or(BrokerError::Quota)
            })?;
        let captured_at_ms = unix_ms()?;
        let instant = Instant::now();
        let state = State {
            domain: self.graph.domain.clone(),
            prior_epoch: self.epoch.clone(),
            captured_at_ms,
            graph_revision: self.graph.revision,
            sources: self
                .sources
                .iter()
                .map(|(source, record)| SourceImage {
                    source: source.clone(),
                    version: record.version,
                    provenance: record.provenance.clone(),
                    remaining_ms: record.expires.map(|expiry| {
                        u64::try_from(expiry.saturating_duration_since(instant).as_millis())
                            .unwrap_or(u64::MAX)
                    }),
                })
                .collect(),
            documents: self
                .graph
                .documents
                .values()
                .map(|node| node.document.clone())
                .collect(),
            edges: self.graph.edges.clone(),
            edge_owners: self
                .edge_nodes
                .iter()
                .map(|(id, node)| (id.clone(), node.source.clone()))
                .collect(),
        };
        measure(&state, max_bytes)?;
        let sha256 = checkpoint_digest(&state)?;
        let checkpoint = BrokerCheckpoint {
            envelope: Envelope {
                schema: SCHEMA.into(),
                state,
                sha256,
            },
        };
        measure(&checkpoint.envelope, max_bytes)?;
        Ok(checkpoint)
    }

    /// Restore evidence into a fresh authority epoch under explicit current limits. The host
    /// must reissue grants, recompile context and obtain new reviews. Old source CAS handles
    /// remain invalid even though each source's monotonic version and lineage are preserved.
    pub fn from_checkpoint(
        domain: impl Into<String>,
        graph_limits: GraphLimits,
        limits: BrokerLimits,
        checkpoint: &BrokerCheckpoint,
    ) -> Result<Self, BrokerError> {
        let mut broker = Self::new(domain, graph_limits, limits)?;
        let state = &checkpoint.envelope.state;
        let now_ms = unix_ms()?;
        let elapsed = now_ms
            .checked_sub(state.captured_at_ms)
            .ok_or(BrokerError::Stale)?;
        if state.domain != broker.graph.domain
            || state.prior_epoch.len() != 64
            || !state
                .prior_epoch
                .bytes()
                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
            || state.sources.len() > limits.max_sources
            || state.documents.len() > graph_limits.max_documents
            || (state.graph_revision == 0
                && (!state.documents.is_empty() || !state.edges.is_empty()))
        {
            return Err(integrity());
        }
        let mut provenance_bytes = 0_usize;
        for saved in &state.sources {
            valid_source(&saved.source)?;
            let mut provenance = saved.provenance.clone();
            if saved.version == 0
                || broker.sources.contains_key(&saved.source)
                || !valid_label(&provenance.authority)
                || !valid_label(&provenance.upstream_revision)
                || provenance.derived_from.len() > 32
                || provenance.valid_until_ms.is_some() != saved.remaining_ms.is_some()
                || provenance
                    .valid_until_ms
                    .is_some_and(|until| until <= provenance.observed_at_ms)
            {
                return Err(integrity());
            }
            let mut seen = BTreeSet::new();
            for dependency in &mut provenance.derived_from {
                valid_source(&dependency.source)?;
                if dependency.source == saved.source
                    || !seen.insert(&dependency.source)
                    || dependency.revision.epoch != state.prior_epoch
                    || dependency.revision.version == 0
                {
                    return Err(integrity());
                }
                // Only internal evidence lineage is re-bound. No external source handle is reused.
                dependency.revision.epoch.clone_from(&broker.epoch);
            }
            let bytes = measure(&(&saved.source, &provenance), MAX_PROVENANCE_BYTES)?;
            provenance_bytes = provenance_bytes
                .checked_add(bytes)
                .ok_or(BrokerError::Quota)?;
            if provenance_bytes > limits.max_provenance_bytes {
                return Err(BrokerError::Quota);
            }
            let expires = match (provenance.valid_until_ms, saved.remaining_ms) {
                (Some(until), Some(remaining)) => {
                    let lifetime = until
                        .saturating_sub(now_ms)
                        .min(remaining.saturating_sub(elapsed));
                    Some(
                        Instant::now()
                            .checked_add(Duration::from_millis(lifetime))
                            .ok_or(BrokerError::Unavailable)?,
                    )
                }
                _ => None,
            };
            broker.sources.insert(
                saved.source.clone(),
                SourceRecord {
                    version: saved.version,
                    provenance,
                    bytes,
                    expires,
                },
            );
        }
        for record in broker.sources.values() {
            for dependency in &record.provenance.derived_from {
                if broker
                    .sources
                    .get(&dependency.source)
                    .is_none_or(|input| input.version < dependency.revision.version)
                {
                    return Err(integrity());
                }
            }
        }
        validate_lineage(&broker.sources)?;
        for document in &state.documents {
            if !broker.sources.contains_key(&document.source)
                || broker.graph.documents.contains_key(&document.id)
            {
                return Err(integrity());
            }
            broker.graph.upsert(document.clone())?;
        }
        broker.graph.restore_relationships(state.edges.clone())?;
        let mut relation_bytes = 0_usize;
        for (from, outgoing) in &state.edges {
            for (kind, to) in outgoing {
                // Contradictions have two stored directions but one logical ownership reference.
                if *kind == EdgeKind::Contradicts && from > to {
                    continue;
                }
                for id in [from, to] {
                    let source = state.edge_owners.get(id).ok_or_else(integrity)?;
                    if !broker.sources.contains_key(source)
                        || broker
                            .graph
                            .documents
                            .get(id)
                            .is_some_and(|doc| &doc.document.source != source)
                    {
                        return Err(integrity());
                    }
                    if let Some(node) = broker.edge_nodes.get_mut(id) {
                        node.references =
                            node.references.checked_add(1).ok_or(BrokerError::Quota)?;
                    } else {
                        let bytes = measure(&(id, source), 8192)?;
                        relation_bytes = relation_bytes
                            .checked_add(bytes)
                            .ok_or(BrokerError::Quota)?;
                        if relation_bytes > limits.max_relation_bytes {
                            return Err(BrokerError::Quota);
                        }
                        broker.edge_nodes.insert(
                            id.clone(),
                            EdgeNode {
                                source: source.clone(),
                                references: 1,
                                bytes,
                            },
                        );
                    }
                }
            }
        }
        if broker.edge_nodes.len() != state.edge_owners.len() {
            return Err(integrity());
        }
        broker.graph.revision = state.graph_revision;
        Ok(broker)
    }
}

fn validate_lineage(sources: &BTreeMap<String, SourceRecord>) -> Result<(), BrokerError> {
    // Validate even stale historical lineage without recursion or checking current validity.
    let mut remaining = BTreeMap::new();
    let mut dependents: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    let mut ready = Vec::new();
    for (source, record) in sources {
        remaining.insert(source.as_str(), record.provenance.derived_from.len());
        if record.provenance.derived_from.is_empty() {
            ready.push(source.as_str());
        }
        for dependency in &record.provenance.derived_from {
            dependents
                .entry(&dependency.source)
                .or_default()
                .push(source);
        }
    }
    let mut seen = 0;
    while let Some(source) = ready.pop() {
        seen += 1;
        for dependent in dependents.get(source).into_iter().flatten() {
            let count = remaining.get_mut(dependent).ok_or_else(integrity)?;
            *count = count.checked_sub(1).ok_or_else(integrity)?;
            if *count == 0 {
                ready.push(dependent);
            }
        }
    }
    if seen != sources.len() {
        return Err(integrity());
    }
    Ok(())
}

fn valid_bound(max_bytes: usize) -> Result<(), BrokerError> {
    if max_bytes == 0 || max_bytes > MAX_BYTES {
        Err(BrokerError::InvalidInput)
    } else {
        Ok(())
    }
}

fn integrity() -> BrokerError {
    BrokerError::Context(ContextError::Integrity)
}

fn checkpoint_digest(state: &State) -> Result<String, BrokerError> {
    struct Hasher(Sha256);
    impl Write for Hasher {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0.update(bytes);
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    let mut hash = Hasher(Sha256::new());
    hash.0.update(SCHEMA.as_bytes());
    hash.0.update([0]);
    {
        // Match the existing domain-separated JSON digest without retaining another full image.
        // Buffer the many small serde writes so each field does not call SHA-256 independently.
        let mut writer = BufWriter::with_capacity(16 * 1024, &mut hash);
        serde_json::to_writer(&mut writer, state).map_err(|_| integrity())?;
        writer.flush().map_err(|_| integrity())?;
    }
    Ok(hex(&hash.0.finalize()))
}

fn bounded_encode(value: &impl Serialize, limit: usize) -> Result<Vec<u8>, BrokerError> {
    let mut bytes = Vec::new();
    bounded_encode_into(value, &mut bytes, limit)?;
    Ok(bytes)
}

fn bounded_encode_into(
    value: &impl Serialize,
    bytes: &mut Vec<u8>,
    limit: usize,
) -> Result<(), BrokerError> {
    struct Writer<'a> {
        bytes: &'a mut Vec<u8>,
        limit: usize,
    }
    impl Write for Writer<'_> {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            if bytes.len() > self.limit.saturating_sub(self.bytes.len()) {
                return Err(std::io::Error::other("checkpoint limit"));
            }
            self.bytes.extend_from_slice(bytes);
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    let mut writer = Writer { bytes, limit };
    if serde_json::to_writer(&mut writer, value).is_err() {
        writer.bytes.clear();
        return Err(BrokerError::Quota);
    }
    Ok(())
}

#[cfg(test)]
mod tests;