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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
use crate::graph::term_counts;
use crate::{
    Citation, ContextError, ContextGraph, ContextSnapshot, EdgeKind, EvidenceBlock,
    SelectionExplanation, SelectionSignal, SelectionStep, TokenCounter,
};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};

/// Source representation for optional query matches. Hard dependencies always use complete text.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExcerptMode {
    /// Include complete source documents.
    #[default]
    Full,
    /// Include matching line windows with neighboring lines and explicit source ranges.
    QueryWindows,
}

/// A bounded query against one local graph. Authorization is supplied by the owning application.
#[derive(Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ContextRequest {
    /// Natural-language query or code identifiers.
    pub query: String,
    /// Maximum context-text tokens, before subtracting `reserve_tokens`.
    pub max_tokens: usize,
    /// Caller allowance for system prompt, history, output, and provider framing.
    pub reserve_tokens: usize,
    /// Exact IDs that must appear, with their complete hard closure.
    pub required: BTreeSet<String>,
    /// Authorized IDs for this call; `None` means all documents in this caller-owned local graph.
    pub allowed: Option<BTreeSet<String>>,
    /// Optional ranked IDs from an application-supplied semantic retriever. Every ID is still
    /// filtered by `allowed`. Rank, not an incompatible model similarity scale, supplies the gain.
    pub semantic_candidates: Vec<String>,
    /// Application policy revision; changing it invalidates delta reuse.
    pub policy_revision: String,
    /// Maximum candidate roots retained after lexical lookup and graph expansion.
    pub max_candidates: usize,
    /// Maximum physical evidence blocks in the output, including hard closure.
    pub max_blocks: usize,
    /// Maximum optional graph-expansion depth. Hard closure is never silently truncated.
    pub graph_depth: usize,
    /// Number of distinct source witnesses sought for each query term, between one and four.
    pub evidence_per_term: usize,
    /// Representation mode for optional roots.
    pub excerpt_mode: ExcerptMode,
}

impl Default for ContextRequest {
    fn default() -> Self {
        Self {
            query: String::new(),
            max_tokens: 4096,
            reserve_tokens: 0,
            required: BTreeSet::new(),
            allowed: None,
            semantic_candidates: Vec::new(),
            policy_revision: "local-owner.v1".to_owned(),
            max_candidates: 256,
            max_blocks: 16,
            graph_depth: 2,
            evidence_per_term: 1,
            excerpt_mode: ExcerptMode::Full,
        }
    }
}

/// Content-free statistics. Coverage counts describe lexical query concepts, not answer quality.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SelectionStats {
    /// Live documents at query time.
    pub documents: usize,
    /// Authorized documents matching at least one indexed term.
    pub lexical_matches: usize,
    /// Roots considered after bounded expansion.
    pub candidates: usize,
    /// Physical blocks in the result.
    pub selected_blocks: usize,
    /// Sources represented by selected blocks, including exact-text aliases.
    pub selected_sources: usize,
    /// Distinct non-stopword query terms.
    pub query_terms: usize,
    /// Query terms covered by at least one selected source's indexed text or locator.
    pub covered_terms: usize,
    /// Final exact rendered-text token count, including citations.
    pub rendered_tokens: usize,
    /// Available context-text budget after the caller reserve.
    pub available_tokens: usize,
    /// Optional roots refused because their hard closure was unavailable or unauthorized.
    pub unavailable_roots: usize,
    /// Optional roots refused because their hard closure exceeded the candidate bound.
    pub limit_rejected_roots: usize,
    /// Optional roots refused because their complete representation did not fit the budget.
    pub budget_rejected_roots: usize,
}

struct Root<'a> {
    id: &'a str,
    score: u64,
    depth: usize,
    semantic: bool,
    declarations: usize,
}

#[derive(Default)]
struct Witnesses {
    sources: BTreeSet<String>,
    content: BTreeSet<String>,
    // An incidental text mention must not suppress a distinct matching source locator.
    source_match: bool,
}

// These limits belong to the host implementation, never to ContextRequest. Output and
// retained-ticket limits cannot bound preparation of overlapping dependency closures.
struct CompileBudget {
    work: usize,
    bytes: usize,
    exhausted: bool,
}

impl CompileBudget {
    fn new() -> Self {
        Self {
            work: 1_000_000,
            bytes: 64 * 1024 * 1024,
            exhausted: false,
        }
    }

    fn charge(&mut self, work: usize, bytes: usize) -> Result<(), ContextError> {
        match (self.work.checked_sub(work), self.bytes.checked_sub(bytes)) {
            (Some(work), Some(bytes)) if !self.exhausted => {
                self.work = work;
                self.bytes = bytes;
                Ok(())
            }
            _ => {
                self.exhausted = true;
                Err(ContextError::LimitExceeded)
            }
        }
    }

    fn count(
        &mut self,
        blocks: &[EvidenceBlock],
        tokenizer: &impl TokenCounter,
    ) -> Result<usize, ContextError> {
        // JSON strings can expand sixfold. Charge before render creates intermediate
        // strings, including every citation, even when identical text is coalesced.
        for block in blocks {
            self.charge(1, block.text.len().saturating_mul(6).saturating_add(128))?;
            for citation in &block.citations {
                self.charge(
                    1,
                    citation
                        .node_id
                        .len()
                        .saturating_add(citation.source.len())
                        .saturating_mul(6)
                        .saturating_add(128),
                )?;
            }
        }
        tokenizer.count(&crate::snapshot::render(blocks))
    }
}

impl ContextGraph {
    fn scored_roots<'a>(
        &'a self,
        request: &ContextRequest,
        terms: &BTreeSet<String>,
        total: usize,
    ) -> (BTreeMap<String, u64>, Vec<Root<'a>>, usize) {
        let allowed = |id: &str| request.allowed.as_ref().is_none_or(|ids| ids.contains(id));
        let work = terms
            .iter()
            .filter_map(|term| self.postings.get(term))
            .fold(0_usize, |count, posting| {
                count.saturating_add(posting.len())
            });
        let dense = self.slots.len() > 512 && work > self.slots.len() / 4;
        let authorization = (dense && request.allowed.is_some()).then(|| {
            let mut slots = vec![false; self.slots.len()];
            if let Some(ids) = &request.allowed {
                for node in ids.iter().filter_map(|id| self.documents.get(id)) {
                    if let Some(entry) = slots.get_mut(node.slot) {
                        *entry = true;
                    }
                }
            }
            slots
        });
        let slot_allowed = |slot: usize| {
            authorization
                .as_ref()
                .is_none_or(|slots| slots.get(slot).copied().unwrap_or(false))
        };
        let mut weights = BTreeMap::new();
        let mut sparse = HashMap::<&str, u64>::new();
        let mut scores = if dense {
            vec![0_u64; self.slots.len()]
        } else {
            Vec::new()
        };
        let mut touched = Vec::new();
        for term in terms {
            let Some(posting) = self.postings.get(term) else {
                continue;
            };
            let frequency = if request.allowed.is_none() {
                posting.len()
            } else if dense {
                posting
                    .values()
                    .filter(|entry| slot_allowed(entry.slot))
                    .count()
            } else {
                posting.keys().filter(|id| allowed(id)).count()
            };
            // Preserve the integer score and authorized corpus statistics exactly.
            let weight = 1000 + (1000 * total as u64 / (frequency as u64 + 1)).min(100_000);
            weights.insert(term.clone(), weight);
            if dense {
                for entry in posting.values().filter(|entry| slot_allowed(entry.slot)) {
                    if let Some(score) = scores.get_mut(entry.slot) {
                        if *score == 0 {
                            touched.push(entry.slot);
                        }
                        *score += weight * (3 + u64::from(entry.count));
                    }
                }
            } else {
                for (id, entry) in posting.iter().filter(|(id, _)| allowed(id)) {
                    *sparse.entry(id).or_default() += weight * (3 + u64::from(entry.count));
                }
            }
        }
        let lexical_matches = if dense { touched.len() } else { sparse.len() };
        for (rank, id) in request.semantic_candidates.iter().enumerate() {
            let Some(node) = self.documents.get(id) else {
                continue;
            };
            if dense {
                if slot_allowed(node.slot)
                    && let Some(score) = scores.get_mut(node.slot)
                {
                    if *score == 0 {
                        touched.push(node.slot);
                    }
                    *score += 600_000 / (60 + rank as u64);
                }
            } else if allowed(id) {
                *sparse.entry(id).or_default() += 600_000 / (60 + rank as u64);
            }
        }
        let semantic = request
            .semantic_candidates
            .iter()
            .map(String::as_str)
            .collect::<BTreeSet<_>>();
        let root = |node: &'a crate::graph::IndexedDocument, score| Root {
            declarations: node.declarations.intersection(terms).count(),
            semantic: semantic.contains(node.document.id.as_str()),
            id: node.document.id.as_str(),
            score,
            depth: 0,
        };
        let roots = if dense {
            touched
                .into_iter()
                .filter_map(|slot| {
                    self.slots
                        .get(slot)
                        .and_then(Option::as_deref)
                        .zip(scores.get(slot))
                        .map(|(node, score)| root(node, *score))
                })
                .collect()
        } else {
            sparse
                .into_iter()
                .filter_map(|(id, score)| self.documents.get(id).map(|node| root(node, score)))
                .collect()
        };
        (weights, roots, lexical_matches)
    }

    /// Retrieves, expands, selects, cites, and seals a context snapshot using exact final counts.
    /// Every selected hard dependency and counterclaim must be authorized and fit in full.
    pub fn compile(
        &self,
        request: &ContextRequest,
        tokenizer: &impl TokenCounter,
    ) -> Result<ContextSnapshot, ContextError> {
        self.compile_traced(request, tokenizer, None)
    }

    /// Reconstruct the selector's successful steps for an exact current snapshot/request.
    /// Stale, substituted or differently scoped snapshots fail before a trace is returned.
    /// This opt-in operation recompiles; ordinary compilation allocates no selection trace.
    pub fn explain(
        &self,
        request: &ContextRequest,
        snapshot: &ContextSnapshot,
        tokenizer: &impl TokenCounter,
    ) -> Result<SelectionExplanation, ContextError> {
        let mut steps = Vec::new();
        let current = self.compile_traced(request, tokenizer, Some(&mut steps))?;
        if snapshot != &current {
            return Err(ContextError::BaseMismatch);
        }
        SelectionExplanation::new(snapshot, request, self.revision(), tokenizer, steps)
    }

    pub(crate) fn compile_traced(
        &self,
        request: &ContextRequest,
        tokenizer: &impl TokenCounter,
        mut trace: Option<&mut Vec<SelectionStep>>,
    ) -> Result<ContextSnapshot, ContextError> {
        validate(request, tokenizer)?;
        let mut budget = CompileBudget::new();
        let available = request.max_tokens - request.reserve_tokens;
        let terms = query_terms(&request.query);
        if terms.len() > 64 {
            return Err(ContextError::LimitExceeded);
        }
        // A compound record name is not a request for each component record. Seek extra
        // locator witnesses only for explicitly listed or conjoined query subjects.
        let multiple_records = request.query.contains(',')
            || request.query.contains(';')
            || request
                .query
                .split_whitespace()
                .any(|word| word.eq_ignore_ascii_case("and"));
        let allowed = |id: &str| request.allowed.as_ref().is_none_or(|ids| ids.contains(id));
        let total = request
            .allowed
            .as_ref()
            .map_or(self.len(), |ids| self.authorized_documents(ids).count());
        let (weights, mut roots, lexical_matches) = self.scored_roots(request, &terms, total);
        let rank = |a: &Root<'_>, b: &Root<'_>| {
            b.declarations
                .cmp(&a.declarations)
                .then_with(|| b.score.cmp(&a.score))
                .then_with(|| a.id.cmp(b.id))
        };
        let seed_limit = if request.graph_depth == 0 {
            request.max_candidates
        } else {
            request.max_candidates.div_ceil(2)
        };
        // Select exactly the same total-order prefix without sorting every matching document.
        // Hash iteration order cannot affect the result: document IDs break every score tie.
        if roots.len() > seed_limit {
            roots.select_nth_unstable_by(seed_limit, rank);
            roots.truncate(seed_limit);
        }
        roots.sort_by(rank);
        let mut seen = roots.iter().map(|r| r.id).collect::<BTreeSet<_>>();
        let mut queue = roots
            .iter()
            .map(|r| (r.id, r.score, 0))
            .collect::<VecDeque<_>>();
        // Reserve space for graph leads without evicting stronger lexical matches. The queue
        // has a fixed bound even for cyclic, dense, or adversarial graphs.
        while let Some((id, score, depth)) = queue.pop_front() {
            if depth >= request.graph_depth || roots.len() >= request.max_candidates {
                continue;
            }
            if let Some(edges) = self.edges.get(id) {
                for (kind, target) in edges {
                    if roots.len() >= request.max_candidates {
                        break;
                    }
                    if !allowed(target)
                        || !self.documents.contains_key(target)
                        || !seen.insert(target.as_str())
                    {
                        continue;
                    }
                    let divisor = if *kind == EdgeKind::Related { 4 } else { 2 };
                    let next = score / divisor;
                    roots.push(Root {
                        declarations: self
                            .documents
                            .get(target)
                            .map_or(0, |node| node.declarations.intersection(&terms).count()),
                        id: target,
                        score: next,
                        depth: depth + 1,
                        semantic: false,
                    });
                    queue.push_back((target, next, depth + 1));
                }
            }
        }
        let mut selected = BTreeSet::new();
        let mut blocks = Vec::new();
        let mut coverage = BTreeMap::<String, Witnesses>::new();
        for id in &request.required {
            let closure = self.hard_closure(id, request, &mut budget)?;
            if selected.union(&closure).count() > request.max_candidates {
                return Err(ContextError::LimitExceeded);
            }
            let additions = self.blocks_for(&closure, &selected, &terms, None, &mut budget)?;
            append_coalesced(&mut blocks, additions, &mut budget)?;
            if let Some(steps) = trace.as_deref_mut()
                && !closure.is_subset(&selected)
            {
                steps.push(SelectionStep {
                    root_id: id.clone(),
                    added_ids: closure.difference(&selected).cloned().collect(),
                    signals: vec![SelectionSignal::Required],
                });
            }
            selected.extend(closure);
            if blocks.len() > request.max_blocks {
                return Err(ContextError::BudgetUnsatisfiable);
            }
        }
        if blocks.len() > request.max_blocks || budget.count(&blocks, tokenizer)? > available {
            return Err(ContextError::BudgetUnsatisfiable);
        }
        self.add_coverage(&blocks, &terms, &mut coverage, multiple_records);
        let mut unavailable = 0;
        let mut limit_rejected = 0;
        let mut budget_rejected = 0;
        let mut hard_nodes = request
            .required
            .iter()
            .map(String::as_str)
            .collect::<BTreeSet<_>>();
        if request.excerpt_mode == ExcerptMode::QueryWindows {
            for (from, edges) in self.edges.iter().filter(|(id, _)| allowed(id)) {
                for (kind, to) in edges {
                    budget.charge(1, 0)?;
                    if matches!(kind, EdgeKind::Requires | EdgeKind::Contradicts) {
                        hard_nodes.insert(from.as_str());
                        hard_nodes.insert(to.as_str());
                    }
                }
            }
        }
        // Build and tokenize root closures once. Coverage changes only utility, not source bytes.
        let mut prepared = Vec::new();
        for root in roots {
            if selected.contains(root.id) {
                continue;
            }
            let closure = self.hard_closure(root.id, request, &mut budget);
            // A per-root candidate limit can reject an optional root. Exhausting the
            // aggregate budget must abort the entire call, including optional roots.
            budget.charge(0, 0)?;
            match closure {
                Ok(closure) => {
                    let excerpt_root = (request.excerpt_mode == ExcerptMode::QueryWindows
                        && closure.len() == 1
                        && !hard_nodes.contains(root.id))
                    .then_some(root.id);
                    let values = self.blocks_for(
                        &closure,
                        &BTreeSet::new(),
                        &terms,
                        excerpt_root,
                        &mut budget,
                    )?;
                    let cost = budget.count(&values, tokenizer)?.max(1);
                    budget.charge(closure.len().saturating_mul(terms.len().max(1)), 0)?;
                    let retained = if excerpt_root.is_none() {
                        closure
                            .iter()
                            .filter_map(|id| {
                                self.documents.get(id).map(|node| {
                                    (
                                        id.clone(),
                                        terms
                                            .iter()
                                            .filter(|term| node.terms.contains_key(*term))
                                            .cloned()
                                            .collect::<BTreeSet<_>>(),
                                    )
                                })
                            })
                            .collect()
                    } else {
                        self.retained_terms(&values, &terms)
                    };
                    prepared.push((root, closure, values, cost, retained));
                }
                Err(ContextError::RequiredUnavailable) => unavailable += 1,
                Err(ContextError::LimitExceeded) => limit_rejected += 1,
                Err(error) => return Err(error),
            }
        }
        let candidate_count = prepared.len() + unavailable + limit_rejected;
        while !prepared.is_empty() && blocks.len() < request.max_blocks {
            let retained_selected = self.retained_terms(&blocks, &terms);
            let covered_declarations = selected
                .iter()
                .filter_map(|id| self.documents.get(id).map(|node| (id, node)))
                .flat_map(|(id, node)| {
                    node.declarations
                        .intersection(&terms)
                        .filter(|term| {
                            retained_selected
                                .get(id)
                                .is_some_and(|words| words.contains(*term))
                        })
                        .cloned()
                })
                .collect::<BTreeSet<_>>();
            let mut best = None;
            for (index, (root, closure, _, cost, retained)) in prepared.iter().enumerate() {
                budget.charge(
                    closure
                        .len()
                        .saturating_mul(terms.len().saturating_mul(2).saturating_add(1)),
                    0,
                )?;
                if closure.is_subset(&selected) {
                    continue;
                }
                let mut gain = 0_u64;
                let mut new_declaration = false;
                for id in closure {
                    if let Some(node) = self.documents.get(id) {
                        for term in node.declarations.intersection(&terms) {
                            if !covered_declarations.contains(term)
                                && retained.get(id).is_some_and(|words| words.contains(term))
                            {
                                new_declaration = true;
                                gain += weights.get(term).copied().unwrap_or(1000) * 20;
                            }
                        }
                    }
                }
                for (term, weight) in &weights {
                    let witnesses = coverage.get(term);
                    let witnessed = witnesses.map_or(0, |v| v.sources.len());
                    let enough_witnesses = witnessed >= request.evidence_per_term;
                    if enough_witnesses
                        && (!multiple_records || witnesses.is_some_and(|v| v.source_match))
                    {
                        continue;
                    }
                    if closure.iter().any(|id| {
                        self.documents.get(id).is_some_and(|node| {
                            retained.get(id).is_some_and(|terms| terms.contains(term))
                                && (!enough_witnesses
                                    || node.terms.get(term).is_some_and(|value| value.in_source))
                                && !witnesses.is_some_and(|v| {
                                    v.sources.contains(&node.document.source)
                                        || v.content.contains(&node.text_digest)
                                })
                        })
                    }) {
                        gain += weight * 10 / (witnessed as u64 + 1);
                    }
                }
                // Explicit supporting leads can add evidence without repeating the query words.
                if root.depth > 0 || root.semantic {
                    gain += root.score / 2;
                }
                if gain == 0 {
                    continue;
                }
                let value = gain + root.score / 16;
                if best.is_none_or(
                    |(_, best_value, best_cost, best_declaration): (usize, u64, usize, bool)| {
                        (new_declaration && !best_declaration)
                            || (new_declaration == best_declaration
                                && u128::from(value) * best_cost as u128
                                    > u128::from(best_value) * *cost as u128)
                    },
                ) {
                    best = Some((index, value, *cost, new_declaration));
                }
            }
            let Some((index, _, _, _)) = best else {
                break;
            };
            let (root, closure, additions, _, _) = prepared.remove(index);
            // Charge the selected-block copy before cloning it for this proposal.
            for block in &blocks {
                budget.charge(
                    1,
                    block
                        .text
                        .len()
                        .saturating_add(block.citations.len().saturating_mul(2304)),
                )?;
            }
            let mut proposed = blocks.clone();
            append_coalesced(
                &mut proposed,
                additions
                    .into_iter()
                    .filter(|block| {
                        !block
                            .citations
                            .iter()
                            .all(|citation| selected.contains(&citation.node_id))
                    })
                    .collect(),
                &mut budget,
            )?;
            if proposed.len() > request.max_blocks
                || budget.count(&proposed, tokenizer)? > available
            {
                budget_rejected += 1;
                continue;
            }
            if let Some(steps) = trace.as_deref_mut() {
                let mut signals = Vec::new();
                if self
                    .documents
                    .get(root.id)
                    .is_some_and(|node| terms.iter().any(|term| node.terms.contains_key(term)))
                {
                    signals.push(SelectionSignal::LexicalMatch);
                }
                if root.declarations > 0 {
                    signals.push(SelectionSignal::DeclarationMatch);
                }
                if root.semantic {
                    signals.push(SelectionSignal::SemanticCandidate);
                }
                if root.depth > 0 {
                    signals.push(SelectionSignal::GraphExpansion);
                }
                steps.push(SelectionStep {
                    root_id: root.id.to_owned(),
                    added_ids: closure.difference(&selected).cloned().collect(),
                    signals,
                });
            }
            blocks = proposed;
            selected.extend(closure);
            self.add_coverage(&blocks, &terms, &mut coverage, multiple_records);
        }
        let tokens = budget.count(&blocks, tokenizer)?;
        let stats = SelectionStats {
            documents: total,
            lexical_matches,
            candidates: candidate_count,
            selected_blocks: blocks.len(),
            selected_sources: selected.len(),
            query_terms: terms.len(),
            covered_terms: coverage.len(),
            rendered_tokens: tokens,
            available_tokens: available,
            unavailable_roots: unavailable,
            limit_rejected_roots: limit_rejected,
            budget_rejected_roots: budget_rejected,
        };
        let snapshot = ContextSnapshot::seal(
            &self.domain,
            &request.policy_revision,
            tokenizer.identity(),
            self.revision,
            blocks,
            stats,
        )?;
        snapshot.verify(tokenizer)?;
        Ok(snapshot)
    }

    fn hard_closure(
        &self,
        root: &str,
        request: &ContextRequest,
        budget: &mut CompileBudget,
    ) -> Result<BTreeSet<String>, ContextError> {
        let mut seen = BTreeSet::new();
        let mut pending = vec![root.to_owned()];
        while let Some(id) = pending.pop() {
            budget.charge(1, id.len())?;
            if !seen.insert(id.clone()) {
                continue;
            }
            if seen.len() > request.max_candidates {
                return Err(ContextError::LimitExceeded);
            }
            if !self.documents.contains_key(&id)
                || request
                    .allowed
                    .as_ref()
                    .is_some_and(|ids| !ids.contains(&id))
            {
                return Err(ContextError::RequiredUnavailable);
            }
            if let Some(edges) = self.edges.get(&id) {
                for (kind, target) in edges {
                    budget.charge(1, target.len())?;
                    if matches!(kind, EdgeKind::Requires | EdgeKind::Contradicts) {
                        pending.push(target.clone());
                    }
                }
            }
        }
        Ok(seen)
    }

    fn add_coverage(
        &self,
        blocks: &[EvidenceBlock],
        terms: &BTreeSet<String>,
        coverage: &mut BTreeMap<String, Witnesses>,
        source_witnesses: bool,
    ) {
        for (id, retained) in self.retained_terms(blocks, terms) {
            if let Some(node) = self.documents.get(&id) {
                for term in terms {
                    if retained.contains(term) {
                        let witnesses = coverage.entry(term.clone()).or_default();
                        if source_witnesses {
                            witnesses.source_match |=
                                node.terms.get(term).is_some_and(|value| value.in_source);
                        }
                        if !witnesses.sources.contains(&node.document.source)
                            && !witnesses.content.contains(&node.text_digest)
                        {
                            witnesses.sources.insert(node.document.source.clone());
                            witnesses.content.insert(node.text_digest.clone());
                        }
                    }
                }
            }
        }
    }

    fn blocks_for(
        &self,
        ids: &BTreeSet<String>,
        selected: &BTreeSet<String>,
        terms: &BTreeSet<String>,
        excerpt_root: Option<&str>,
        budget: &mut CompileBudget,
    ) -> Result<Vec<EvidenceBlock>, ContextError> {
        let mut blocks = Vec::new();
        for id in ids.difference(selected) {
            let node = self
                .documents
                .get(id)
                .ok_or(ContextError::RequiredUnavailable)?;
            let text = &node.document.text;
            // Account for copied text, citation metadata, and excerpt line/index
            // work before allocating any representation of this document.
            budget.charge(
                terms.len().saturating_add(1),
                text.len()
                    .saturating_add(node.document.source.len())
                    .saturating_add(id.len())
                    .saturating_add(256),
            )?;
            if excerpt_root != Some(id.as_str()) {
                blocks.push(EvidenceBlock::new(
                    text.clone(),
                    vec![Citation {
                        node_id: id.clone(),
                        source: node.document.source.clone(),
                        document_digest: node.digest.clone(),
                        start_line: node.document.start_line,
                        end_line: node.document.start_line + text.lines().count() - 1,
                    }],
                )?);
                continue;
            }
            let line_count = text.lines().count();
            budget.charge(
                line_count,
                line_count.saturating_mul(std::mem::size_of::<&str>()),
            )?;
            let lines = text.lines().collect::<Vec<_>>();
            let mut matching_lines = BTreeSet::new();
            for line in terms
                .iter()
                .filter_map(|term| node.terms.get(term))
                .flat_map(|value| value.lines())
            {
                budget.charge(1, 64)?;
                matching_lines.insert(line);
            }
            budget.charge(
                matching_lines.len(),
                matching_lines
                    .len()
                    .saturating_mul(2 * std::mem::size_of::<usize>()),
            )?;
            let ranges = windows(lines.len(), matching_lines);
            // A single document can produce many disjoint excerpts. Every window
            // owns its own citation; charge all metadata before any of those copies.
            let citation_bytes = id
                .len()
                .saturating_add(node.document.source.len())
                .saturating_add(node.digest.len())
                .saturating_add(128);
            budget.charge(
                ranges.len(),
                ranges
                    .len()
                    .saturating_mul(citation_bytes)
                    .saturating_add(text.len().saturating_mul(2)),
            )?;
            let mut excerpts = Vec::new();
            let mut citations = Vec::new();
            for (start, end) in ranges {
                let content = lines
                    .get(start..end)
                    .ok_or(ContextError::Integrity)?
                    .join("\n");
                excerpts.push(content);
                citations.push(Citation {
                    node_id: id.clone(),
                    source: node.document.source.clone(),
                    document_digest: node.digest.clone(),
                    start_line: node.document.start_line + start,
                    end_line: node.document.start_line + (end - 1),
                });
            }
            let body = excerpts.join("\n[… omitted …]\n");
            blocks.push(EvidenceBlock::new(body, citations)?);
        }
        Ok(blocks)
    }

    // All blocks here were constructed from this graph. Query-term line postings let us compute
    // precisely the old retained-text coverage without repeatedly analyzing each candidate body.
    fn retained_terms(
        &self,
        blocks: &[EvidenceBlock],
        terms: &BTreeSet<String>,
    ) -> BTreeMap<String, BTreeSet<String>> {
        let mut retained = BTreeMap::new();
        for block in blocks {
            for citation in &block.citations {
                let Some(node) = self.documents.get(&citation.node_id) else {
                    continue;
                };
                let words = retained
                    .entry(citation.node_id.clone())
                    .or_insert_with(BTreeSet::new);
                for term in terms {
                    if node.terms.get(term).is_some_and(|value| {
                        value.in_source || {
                            let start = citation.start_line - node.document.start_line;
                            let end = citation.end_line - node.document.start_line;
                            value.intersects(start, end)
                        }
                    }) || (term == "omitted" && block.text.contains("\n[… omitted …]\n"))
                    {
                        words.insert(term.clone());
                    }
                }
            }
        }
        retained
    }
}

fn append_coalesced(
    blocks: &mut Vec<EvidenceBlock>,
    additions: Vec<EvidenceBlock>,
    budget: &mut CompileBudget,
) -> Result<(), ContextError> {
    for block in additions {
        let mut duplicate = None;
        for (index, existing) in blocks.iter().enumerate() {
            // Equal-length bodies can share an arbitrarily long prefix. Bound
            // repeated comparisons as well as allocations before max_blocks is checked.
            budget.charge(
                1,
                if existing.text.len() == block.text.len() {
                    block.text.len()
                } else {
                    0
                },
            )?;
            if existing.text == block.text {
                duplicate = Some(index);
                break;
            }
        }
        if let Some(index) = duplicate {
            let existing = blocks.get_mut(index).ok_or(ContextError::Integrity)?;
            let citations = existing
                .citations
                .len()
                .saturating_add(block.citations.len());
            budget.charge(
                citations.saturating_mul((usize::BITS - citations.leading_zeros()) as usize),
                0,
            )?;
            existing.citations.extend(block.citations);
            existing.citations.sort();
            existing.citations.dedup();
        } else {
            blocks.push(block);
        }
    }
    Ok(())
}

fn windows(line_count: usize, matching_lines: BTreeSet<usize>) -> Vec<(usize, usize)> {
    let mut ranges: Vec<(usize, usize)> = Vec::new();
    for index in matching_lines {
        let start = index.saturating_sub(1);
        let end = index.saturating_add(2).min(line_count);
        if let Some(last) = ranges.last_mut()
            && start <= last.1
        {
            last.1 = end;
            continue;
        }
        ranges.push((start, end));
    }
    if ranges.is_empty() {
        ranges.push((0, line_count));
    }
    ranges
}

fn query_terms(text: &str) -> BTreeSet<String> {
    const STOP: &[&str] = &[
        "the", "and", "for", "with", "from", "that", "this", "what", "which", "how", "does", "are",
        "was", "were", "into", "can", "should", "please", "about", "then", "than",
    ];
    term_counts(text)
        .into_keys()
        .filter(|term| !STOP.contains(&term.as_str()))
        .collect()
}

fn validate(request: &ContextRequest, tokenizer: &impl TokenCounter) -> Result<(), ContextError> {
    if request.query.trim().is_empty() && request.required.is_empty()
        || request.query.len() > 8192
        || request.max_tokens <= request.reserve_tokens
        || request.max_tokens > 16_777_216
        || !(1..=4096).contains(&request.max_candidates)
        || request.max_blocks == 0
        || request.max_blocks > request.max_candidates
        || request.required.len() > request.max_candidates
        || request.semantic_candidates.len() > request.max_candidates
        || request
            .semantic_candidates
            .iter()
            .collect::<BTreeSet<_>>()
            .len()
            != request.semantic_candidates.len()
        || request.graph_depth > 8
        || !(1..=4).contains(&request.evidence_per_term)
        || request.policy_revision.is_empty()
        || request.policy_revision.len() > 256
        || tokenizer.identity().is_empty()
        || tokenizer.identity().len() > 256
    {
        return Err(ContextError::InvalidInput);
    }
    Ok(())
}