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
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
use crate::{ContextError, digest};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

/// A source document. IDs and graph relations are application metadata, never inferred authority.
#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Document {
    /// Stable, application-assigned ID, at most 128 printable ASCII characters.
    pub id: String,
    /// Source locator retained in citations; not opened by this library.
    pub source: String,
    /// Exact UTF-8 source text.
    pub text: String,
    /// One-based offset in the original source, for application-provided fragments.
    #[serde(default = "first_line")]
    pub start_line: usize,
}

const fn first_line() -> usize {
    1
}

impl Document {
    pub(crate) fn validate_shape(&self) -> Result<(), ContextError> {
        if !valid_id(&self.id)
            || self.source.is_empty()
            || self.source.len() > 2048
            || self.source.chars().any(char::is_control)
            || self.text.trim().is_empty()
            || self.start_line == 0
        {
            return Err(ContextError::InvalidInput);
        }
        Ok(())
    }

    pub(crate) fn validate_bounds(&self, max_document_bytes: usize) -> Result<(), ContextError> {
        if self.text.len() > max_document_bytes
            || self
                .start_line
                .checked_add(self.text.lines().count().saturating_sub(1))
                .is_none()
        {
            return Err(ContextError::LimitExceeded);
        }
        Ok(())
    }

    /// Constructs an input document. The graph validates bounds before indexing.
    pub fn new(id: impl Into<String>, source: impl Into<String>, text: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            source: source.into(),
            text: text.into(),
            start_line: 1,
        }
    }

    /// Splits explicit text into overlapping line chunks, preserving original line numbers and
    /// UTF-8/line terminators. This is not an AST parser: choose complete symbols yourself when
    /// syntax must remain intact. At most 4096 chunks and 16 MiB of input are accepted.
    /// Replace/withdraw obsolete chunk IDs after source edits; this method does not mutate a graph.
    pub fn chunks(
        &self,
        max_lines: usize,
        overlap_lines: usize,
    ) -> Result<Vec<Self>, ContextError> {
        if max_lines == 0
            || overlap_lines >= max_lines
            || !valid_id(&self.id)
            || self.id.len() > 100
            || self.start_line == 0
            || self.text.trim().is_empty()
        {
            return Err(ContextError::InvalidInput);
        }
        if self.text.len() > 16_777_216 {
            return Err(ContextError::LimitExceeded);
        }
        let lines = self.text.split_inclusive('\n').collect::<Vec<_>>();
        let mut chunks = Vec::new();
        let mut start = 0;
        while start < lines.len() {
            let end = start.saturating_add(max_lines).min(lines.len());
            let text = lines
                .get(start..end)
                .ok_or(ContextError::Integrity)?
                .concat();
            if !text.trim().is_empty() {
                if chunks.len() >= 4096 {
                    return Err(ContextError::LimitExceeded);
                }
                let start_line = self
                    .start_line
                    .checked_add(start)
                    .ok_or(ContextError::LimitExceeded)?;
                chunks.push(Self {
                    id: format!("{}:L{start_line}", self.id),
                    source: self.source.clone(),
                    text,
                    start_line,
                });
            }
            if end == lines.len() {
                break;
            }
            start = end - overlap_lines;
        }
        Ok(chunks)
    }
}

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

/// Semantics of a directed relation from one document to another.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EdgeKind {
    /// Selecting the source requires the target's complete text and its hard closure.
    Requires,
    /// Selecting either side includes the other's complete text, preserving counterevidence.
    Contradicts,
    /// The target is supporting evidence, considered during bounded graph expansion.
    Supports,
    /// The target is a related lead, with a smaller expansion score.
    Related,
}

/// Memory and ingestion limits enforced before graph mutation.
#[derive(Clone, Copy, Debug)]
pub struct GraphLimits {
    /// Maximum live documents.
    pub max_documents: usize,
    /// Maximum UTF-8 bytes per document.
    pub max_document_bytes: usize,
    /// Maximum total live text bytes.
    pub max_total_bytes: usize,
    /// Maximum outgoing edges per document.
    pub max_edges_per_document: usize,
    /// Maximum retained directed edges, including edges to withdrawn sources.
    pub max_edges: usize,
}

impl Default for GraphLimits {
    fn default() -> Self {
        Self {
            max_documents: 100_000,
            max_document_bytes: 262_144,
            max_total_bytes: 256 * 1024 * 1024,
            max_edges_per_document: 128,
            max_edges: 1_000_000,
        }
    }
}

#[derive(Clone)]
pub(crate) struct IndexedDocument {
    pub slot: usize,
    pub document: Document,
    pub terms: BTreeMap<String, IndexedTerm>,
    pub digest: String,
    pub text_digest: String,
    pub declarations: BTreeSet<String>,
}

#[derive(Clone)]
pub(crate) struct IndexedTerm {
    pub count: u8,
    // None encodes the common line-zero occurrence (or no text occurrence when !in_text).
    // Box only exceptional positions so every short-document term stays small and allocation-free.
    positions: Option<Box<LinePosting>>,
    in_text: bool,
    pub in_source: bool,
}

#[derive(Clone)]
enum LinePosting {
    Single(usize),
    Multiple(Vec<usize>),
}

impl LinePosting {
    fn lines(&self) -> impl Iterator<Item = usize> + '_ {
        let (single, multiple) = match self {
            Self::Single(line) => (Some(*line), &[][..]),
            Self::Multiple(lines) => (None, lines.as_slice()),
        };
        single.into_iter().chain(multiple.iter().copied())
    }

    fn intersects(&self, start: usize, end: usize) -> bool {
        match self {
            Self::Single(line) => *line >= start && *line <= end,
            Self::Multiple(lines) => {
                let index = lines.partition_point(|line| *line < start);
                lines.get(index).is_some_and(|line| *line <= end)
            }
        }
    }
}

impl IndexedTerm {
    fn new() -> Self {
        Self {
            count: 0,
            positions: None,
            in_text: false,
            in_source: false,
        }
    }

    pub fn lines(&self) -> impl Iterator<Item = usize> + '_ {
        (self.in_text && self.positions.is_none())
            .then_some(0)
            .into_iter()
            .chain(self.positions.iter().flat_map(|posting| posting.lines()))
    }

    pub fn intersects(&self, start: usize, end: usize) -> bool {
        self.positions
            .as_ref()
            .map_or(self.in_text && start == 0, |posting| {
                posting.intersects(start, end)
            })
    }

    fn add_line(&mut self, line: usize) {
        match self.positions.as_deref_mut() {
            Some(LinePosting::Multiple(lines)) => lines.push(line),
            Some(posting @ LinePosting::Single(_)) => {
                if let LinePosting::Single(first) = posting {
                    *posting = LinePosting::Multiple(vec![*first, line]);
                }
            }
            None if self.in_text => {
                self.positions = Some(Box::new(LinePosting::Multiple(vec![0, line])))
            }
            None if line > 0 => self.positions = Some(Box::new(LinePosting::Single(line))),
            None => {}
        }
        self.in_text = true;
    }
}

/// Result of one atomic source replacement. An identical replacement does not advance revision.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct SourceUpdate {
    /// New node IDs.
    pub inserted: usize,
    /// Existing node IDs whose document changed.
    pub replaced: usize,
    /// Obsolete node IDs withdrawn from this source.
    pub removed: usize,
    /// Identical documents retained.
    pub unchanged: usize,
    /// Graph revision after this transaction.
    pub revision: u64,
}

/// An incrementally updated in-memory graph belonging to one caller-controlled privacy domain.
pub struct ContextGraph {
    pub(crate) domain: String,
    pub(crate) limits: GraphLimits,
    pub(crate) documents: BTreeMap<String, Arc<IndexedDocument>>,
    // Reusable slots let broad queries accumulate exact scores without hashing source IDs.
    // Slots never escape the graph or participate in a snapshot identity.
    pub(crate) slots: Vec<Option<Arc<IndexedDocument>>>,
    free_slots: Vec<usize>,
    pub(crate) postings: BTreeMap<String, BTreeMap<Arc<str>, Posting>>,
    pub(crate) edges: BTreeMap<String, BTreeSet<(EdgeKind, String)>>,
    pub(crate) revision: u64,
    pub(crate) sources: BTreeMap<String, BTreeSet<String>>,
    bytes: usize,
    edge_count: usize,
}

pub(crate) struct Posting {
    pub slot: usize,
    pub count: u8,
}

impl ContextGraph {
    /// Enumerate the exact live authorization intersection in canonical ID order.
    /// Sparse scopes use direct lookups; dense scopes merge the two ordered trees
    /// instead of repeating O(log N) document lookups for every authorized ID.
    /// This caches no authority or graph state and admits no absent/denied IDs.
    pub(crate) fn authorized_documents<'a>(
        &'a self,
        ids: &'a BTreeSet<String>,
    ) -> impl Iterator<Item = (&'a String, &'a Arc<IndexedDocument>)> {
        let dense = ids.len() > self.documents.len() / 8;
        let mut wanted = ids.iter().peekable();
        let mut documents = self.documents.iter().peekable();
        std::iter::from_fn(move || {
            if !dense {
                for id in wanted.by_ref() {
                    if let Some(entry) = self.documents.get_key_value(id) {
                        return Some(entry);
                    }
                }
                return None;
            }
            loop {
                let (id, _) = documents.peek()?;
                let allowed = wanted.peek()?;
                match id.as_str().cmp(allowed.as_str()) {
                    std::cmp::Ordering::Less => {
                        documents.next();
                    }
                    std::cmp::Ordering::Greater => {
                        wanted.next();
                    }
                    std::cmp::Ordering::Equal => {
                        wanted.next();
                        return documents.next();
                    }
                }
            }
        })
    }

    /// Creates an empty graph. The domain must identify the application's privacy boundary.
    pub fn new(domain: impl Into<String>, limits: GraphLimits) -> Result<Self, ContextError> {
        let domain = domain.into();
        if domain.is_empty()
            || domain.len() > 256
            || limits.max_documents == 0
            || limits.max_document_bytes == 0
            || limits.max_total_bytes == 0
            || limits.max_edges_per_document == 0
            || limits.max_edges == 0
        {
            return Err(ContextError::InvalidInput);
        }
        Ok(Self {
            domain,
            limits,
            documents: BTreeMap::new(),
            slots: Vec::new(),
            free_slots: Vec::new(),
            postings: BTreeMap::new(),
            edges: BTreeMap::new(),
            revision: 0,
            sources: BTreeMap::new(),
            bytes: 0,
            edge_count: 0,
        })
    }

    /// Number of live source documents.
    #[must_use]
    pub fn len(&self) -> usize {
        self.documents.len()
    }

    /// Whether the graph has no live documents.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.documents.is_empty()
    }

    /// Current local mutation sequence. Identical upserts do not advance it.
    #[must_use]
    pub const fn revision(&self) -> u64 {
        self.revision
    }

    /// Inserts or replaces one source and updates only its term postings. Returns whether changed.
    pub fn upsert(&mut self, document: Document) -> Result<bool, ContextError> {
        document.validate_shape()?;
        let old = self.documents.get(&document.id);
        if old.is_some_and(|value| value.document == document) {
            return Ok(false);
        }
        let bytes = self
            .bytes
            .saturating_sub(old.map_or(0, |v| v.document.text.len()))
            .checked_add(document.text.len())
            .ok_or(ContextError::LimitExceeded)?;
        if document.text.len() > self.limits.max_document_bytes
            || bytes > self.limits.max_total_bytes
            || (old.is_none() && self.len() >= self.limits.max_documents)
        {
            return Err(ContextError::LimitExceeded);
        }
        document.validate_bounds(self.limits.max_document_bytes)?;
        let revision = self
            .revision
            .checked_add(1)
            .ok_or(ContextError::LimitExceeded)?;
        let content_digest = digest("cigar.document.v1", &document)?;
        let text_digest = digest("cigar.document-text.v1", &document.text)?;
        let declarations = declarations(&document.text);
        let mut terms = BTreeMap::<String, IndexedTerm>::new();
        for (line, text) in document.text.lines().enumerate() {
            for (term, count) in term_counts(text) {
                let value = terms.entry(term).or_insert_with(IndexedTerm::new);
                value.count = (usize::from(value.count) + count.min(3)).min(3) as u8;
                value.add_line(line);
            }
        }
        for (term, count) in term_counts(&document.source) {
            let value = terms.entry(term).or_insert_with(IndexedTerm::new);
            value.count = (usize::from(value.count) + count.min(3)).min(3) as u8;
            value.in_source = true;
        }
        self.unindex(&document.id);
        self.index(IndexedDocument {
            slot: 0,
            document,
            terms,
            digest: content_digest,
            text_digest,
            declarations,
        });
        self.bytes = bytes;
        self.revision = revision;
        Ok(true)
    }

    /// Atomically replaces all documents with this exact source locator, withdrawing obsolete IDs.
    /// Empty input withdraws the source. Every input must use this locator and a distinct ID; IDs
    /// owned by another source are rejected. Validation/indexing completes before live mutation.
    /// Existing edges remain, so references to withdrawn chunks continue to fail closed. This is
    /// not automatic edge migration: callers repair semantic relations explicitly.
    pub fn replace_source(
        &mut self,
        source: &str,
        documents: Vec<Document>,
    ) -> Result<SourceUpdate, ContextError> {
        if source.is_empty() || source.len() > 2048 || source.chars().any(char::is_control) {
            return Err(ContextError::InvalidInput);
        }
        if documents.len() > self.limits.max_documents {
            return Err(ContextError::LimitExceeded);
        }
        let mut staged = Self::new(self.domain.clone(), self.limits)?;
        let mut result = SourceUpdate::default();
        let mut incoming = BTreeSet::new();
        let mut retained = BTreeSet::new();
        let mut incoming_bytes = 0_usize;
        for document in documents {
            if document.source != source || !incoming.insert(document.id.clone()) {
                return Err(ContextError::InvalidInput);
            }
            incoming_bytes = incoming_bytes
                .checked_add(document.text.len())
                .ok_or(ContextError::LimitExceeded)?;
            match self.documents.get(&document.id) {
                Some(old) if old.document.source != source => {
                    return Err(ContextError::InvalidInput);
                }
                Some(old) if old.document == document => {
                    result.unchanged += 1;
                    retained.insert(document.id);
                    continue;
                }
                Some(_) => result.replaced += 1,
                None => result.inserted += 1,
            }
            staged.upsert(document)?;
        }
        let old_ids = self.sources.get(source).cloned().unwrap_or_default();
        result.removed = old_ids.iter().filter(|id| !incoming.contains(*id)).count();
        if result.inserted + result.replaced + result.removed == 0 {
            result.revision = self.revision;
            return Ok(result);
        }
        let removed_bytes = old_ids
            .iter()
            .filter_map(|id| self.documents.get(id))
            .map(|node| node.document.text.len())
            .sum::<usize>();
        let bytes = self
            .bytes
            .checked_sub(removed_bytes)
            .and_then(|v| v.checked_add(incoming_bytes))
            .ok_or(ContextError::LimitExceeded)?;
        let count = self.len() - old_ids.len() + incoming.len();
        if bytes > self.limits.max_total_bytes || count > self.limits.max_documents {
            return Err(ContextError::LimitExceeded);
        }
        result.revision = self
            .revision
            .checked_add(1)
            .ok_or(ContextError::LimitExceeded)?;
        // No fallible operations after this point. The temporary index bounds staging work and
        // leaves the live graph unchanged on all validation/limit failures.
        for id in old_ids {
            if !retained.contains(&id) {
                self.unindex(&id);
            }
        }
        // Release the staging slot references before moving its immutable nodes. Live slots
        // are assigned here, so a staged ordinal cannot refer to an unrelated live document.
        drop(staged.slots);
        for (_, node) in staged.documents {
            self.index(Arc::unwrap_or_clone(node));
        }
        self.bytes = bytes;
        self.revision = result.revision;
        Ok(result)
    }

    /// Withdraws a document. Incoming hard edges remain so dependents fail closed until repaired.
    pub fn remove(&mut self, id: &str) -> Result<bool, ContextError> {
        let Some(value) = self.documents.get(id) else {
            return Ok(false);
        };
        let bytes = self.bytes.saturating_sub(value.document.text.len());
        let revision = self
            .revision
            .checked_add(1)
            .ok_or(ContextError::LimitExceeded)?;
        self.unindex(id);
        self.bytes = bytes;
        self.revision = revision;
        Ok(true)
    }

    /// Adds a typed edge. Both endpoints must exist. Contradiction links are symmetric and atomic.
    pub fn link(&mut self, from: &str, to: &str, kind: EdgeKind) -> Result<bool, ContextError> {
        if from == to || !self.documents.contains_key(from) || !self.documents.contains_key(to) {
            return Err(ContextError::InvalidInput);
        }
        let mut additions = vec![(from, to)];
        if kind == EdgeKind::Contradicts {
            additions.push((to, from));
        }
        let changed = additions.iter().any(|(a, b)| {
            !self
                .edges
                .get(*a)
                .is_some_and(|edges| edges.contains(&(kind, (*b).to_owned())))
        });
        if !changed {
            return Ok(false);
        }
        let added_count = additions
            .iter()
            .filter(|(a, b)| {
                !self
                    .edges
                    .get(*a)
                    .is_some_and(|edges| edges.contains(&(kind, (*b).to_owned())))
            })
            .count();
        let edge_count = self
            .edge_count
            .checked_add(added_count)
            .ok_or(ContextError::LimitExceeded)?;
        if edge_count > self.limits.max_edges {
            return Err(ContextError::LimitExceeded);
        }
        for (a, b) in &additions {
            if self.edges.get(*a).is_some_and(|edges| {
                edges.len() >= self.limits.max_edges_per_document
                    && !edges.contains(&(kind, (*b).to_owned()))
            }) {
                return Err(ContextError::LimitExceeded);
            }
        }
        let revision = self
            .revision
            .checked_add(1)
            .ok_or(ContextError::LimitExceeded)?;
        for (a, b) in additions {
            self.edges
                .entry(a.to_owned())
                .or_default()
                .insert((kind, b.to_owned()));
        }
        self.edge_count = edge_count;
        self.revision = revision;
        Ok(true)
    }

    /// Explicitly removes an edge, including both directions of a contradiction.
    pub fn unlink(&mut self, from: &str, to: &str, kind: EdgeKind) -> Result<bool, ContextError> {
        let present = self
            .edges
            .get(from)
            .is_some_and(|e| e.contains(&(kind, to.to_owned())));
        if !present {
            return Ok(false);
        }
        let revision = self
            .revision
            .checked_add(1)
            .ok_or(ContextError::LimitExceeded)?;
        if let Some(edges) = self.edges.get_mut(from) {
            if edges.remove(&(kind, to.to_owned())) {
                self.edge_count -= 1;
            }
            if edges.is_empty() {
                self.edges.remove(from);
            }
        }
        if kind == EdgeKind::Contradicts
            && let Some(edges) = self.edges.get_mut(to)
        {
            if edges.remove(&(kind, from.to_owned())) {
                self.edge_count -= 1;
            }
            if edges.is_empty() {
                self.edges.remove(to);
            }
        }
        self.revision = revision;
        Ok(true)
    }

    /// Restore validated relationships, including intentionally withdrawn endpoints. Only the
    /// broker recovery path supplies the separate historical endpoint ownership checks.
    #[cfg(feature = "broker")]
    pub(crate) fn restore_relationships(
        &mut self,
        edges: BTreeMap<String, BTreeSet<(EdgeKind, String)>>,
    ) -> Result<(), ContextError> {
        let count = edges.values().try_fold(0_usize, |count, outgoing| {
            count
                .checked_add(outgoing.len())
                .ok_or(ContextError::LimitExceeded)
        })?;
        if count > self.limits.max_edges
            || edges
                .values()
                .any(|outgoing| outgoing.len() > self.limits.max_edges_per_document)
        {
            return Err(ContextError::LimitExceeded);
        }
        for (from, outgoing) in &edges {
            if !valid_id(from) || outgoing.is_empty() {
                return Err(ContextError::Integrity);
            }
            for (kind, to) in outgoing {
                if !valid_id(to)
                    || from == to
                    || (*kind == EdgeKind::Contradicts
                        && !edges
                            .get(to)
                            .is_some_and(|reverse| reverse.contains(&(*kind, from.clone()))))
                {
                    return Err(ContextError::Integrity);
                }
            }
        }
        self.edges = edges;
        self.edge_count = count;
        Ok(())
    }

    fn index(&mut self, mut node: IndexedDocument) {
        let slot = self.free_slots.pop().unwrap_or(self.slots.len());
        node.slot = slot;
        let node = Arc::new(node);
        let document = &node.document;
        let posting_id: Arc<str> = Arc::from(document.id.as_str());
        for (term, value) in &node.terms {
            self.postings.entry(term.clone()).or_default().insert(
                Arc::clone(&posting_id),
                Posting {
                    slot,
                    count: value.count,
                },
            );
        }
        self.sources
            .entry(document.source.clone())
            .or_default()
            .insert(document.id.clone());
        self.documents
            .insert(document.id.clone(), Arc::clone(&node));
        if slot == self.slots.len() {
            self.slots.push(Some(node));
        } else if let Some(entry) = self.slots.get_mut(slot) {
            *entry = Some(node);
        }
    }

    fn unindex(&mut self, id: &str) {
        if let Some(old) = self.documents.remove(id) {
            if let Some(ids) = self.sources.get_mut(&old.document.source) {
                ids.remove(id);
                if ids.is_empty() {
                    self.sources.remove(&old.document.source);
                }
            }
            for term in old.terms.keys() {
                if let Some(ids) = self.postings.get_mut(term) {
                    ids.remove(id);
                    if ids.is_empty() {
                        self.postings.remove(term);
                    }
                }
            }
            if let Some(slot) = self.slots.get_mut(old.slot) {
                *slot = None;
                self.free_slots.push(old.slot);
            }
        }
    }
}

pub(crate) fn valid_id(id: &str) -> bool {
    !id.is_empty() && id.len() <= 128 && id.bytes().all(|b| b.is_ascii_graphic())
}

// Lexical relevance, not a parser or authority assertion. Prefer named declarations over
// mentions. Applications requiring exact syntax should supply AST-aware chunks.
fn declarations(text: &str) -> BTreeSet<String> {
    let mut result = BTreeSet::new();
    for line in text.lines() {
        let tokens = line
            .split(|ch: char| !ch.is_alphanumeric() && ch != '_')
            .filter(|word| !word.is_empty())
            .take(8)
            .collect::<Vec<_>>();
        for pair in tokens.windows(2) {
            if pair.first().is_some_and(|word| {
                [
                    "fn",
                    "def",
                    "function",
                    "class",
                    "struct",
                    "enum",
                    "trait",
                    "interface",
                ]
                .contains(word)
            }) && let Some(name) = pair.get(1)
            {
                result.insert(name.to_lowercase());
            }
        }
    }
    result
}

pub(crate) fn term_counts(text: &str) -> BTreeMap<String, usize> {
    let mut terms = BTreeMap::new();
    // Keep complete technical identifiers as well as their searchable components. Splitting
    // resolve_reference_tokenizer_target into only common words destroys its strongest signal.
    for token in text.split(|ch: char| !ch.is_alphanumeric() && ch != '_') {
        let camel = token
            .chars()
            .zip(token.chars().skip(1))
            .any(|(a, b)| a.is_lowercase() && b.is_uppercase());
        if token.len() >= 2 && (token.contains('_') || camel) {
            *terms.entry(token.to_lowercase()).or_default() += 1;
        }
    }
    let mut split = String::with_capacity(text.len());
    let mut previous_lower = false;
    for ch in text.chars() {
        if previous_lower && ch.is_uppercase() {
            split.push(' ');
        }
        split.push(ch);
        previous_lower = ch.is_lowercase();
    }
    for term in split.split(|ch: char| !ch.is_alphanumeric()) {
        if term.len() >= 2 {
            *terms.entry(term.to_lowercase()).or_default() += 1;
        }
    }
    terms
}

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

    #[test]
    fn dense_and_sparse_intersections_preserve_exact_live_identity_order()
    -> Result<(), ContextError> {
        let mut graph = ContextGraph::new("authorized-iteration", GraphLimits::default())?;
        for count in [0, 1, 7, 8, 16, 17, 128] {
            graph.replace_source(
                "docs",
                (0..count)
                    .map(|index| {
                        Document::new(
                            format!("id-{index:04}"),
                            "docs",
                            format!("document {index}"),
                        )
                    })
                    .collect(),
            )?;
            for stride in [1, 2, 7, 16, 127] {
                for extra in [false, true] {
                    let mut ids = (0..=128)
                        .step_by(stride)
                        .map(|index| format!("id-{index:04}"))
                        .collect::<BTreeSet<_>>();
                    if extra {
                        ids.extend([
                            "before-all".into(),
                            "id-0000-missing".into(),
                            "zz-after-all".into(),
                        ]);
                    }
                    // Independent legacy lookup oracle, including IDs before/between/after
                    // current keys, empty graphs, withdrawal and both density branches.
                    let expected = ids
                        .iter()
                        .filter_map(|id| graph.documents.get(id).map(|doc| (id, &doc.digest)))
                        .collect::<Vec<_>>();
                    let actual = graph
                        .authorized_documents(&ids)
                        .map(|(id, doc)| (id, &doc.digest))
                        .collect::<Vec<_>>();
                    assert_eq!(actual, expected);
                    assert_eq!(
                        crate::digest("comparison", &actual)?,
                        crate::digest("comparison", &expected)?
                    );
                }
            }
            assert_eq!(graph.authorized_documents(&BTreeSet::new()).count(), 0);
        }
        let ids = BTreeSet::from(["id-0000".into()]);
        let before = graph
            .authorized_documents(&ids)
            .map(|(_, doc)| doc.digest.clone())
            .collect::<Vec<_>>();
        graph.upsert(Document::new("id-0000", "docs", "replacement"))?;
        let after = graph
            .authorized_documents(&ids)
            .map(|(_, doc)| doc.digest.clone())
            .collect::<Vec<_>>();
        assert_ne!(before, after);
        graph.replace_source("docs", Vec::new())?;
        assert_eq!(graph.authorized_documents(&ids).count(), 0);
        Ok(())
    }
}