Skip to main content

lean_ctx_ext/core/knowledge_router/
context_bundle.rs

1// SPDX-License-Identifier: Apache-2.0
2use super::planner::ContextCandidate;
3#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
4pub enum BundleStrategy {
5    #[default]
6    Minimal,
7    Enriched,
8    Governed,
9}
10#[derive(Debug, Clone, Default, PartialEq, Eq)]
11pub struct ContextBundle {
12    pub bundle_id: String,
13    pub task_id: String,
14    pub candidates: Vec<String>,
15    pub total_tokens: u64,
16    pub coverage_milli: u16,
17    pub strategy: BundleStrategy,
18}
19pub fn create_bundle(
20    task_id: &str,
21    candidates: &[ContextCandidate],
22    strategy: BundleStrategy,
23) -> ContextBundle {
24    let selected = if strategy == BundleStrategy::Minimal {
25        &candidates[..candidates.len().min(3)]
26    } else {
27        candidates
28    };
29    let total_tokens = selected
30        .iter()
31        .map(|candidate| candidate.estimated_tokens)
32        .sum();
33    let coverage_milli = selected
34        .iter()
35        .map(|candidate| u64::from(candidate.relevance_milli))
36        .sum::<u64>()
37        .checked_div(selected.len() as u64)
38        .unwrap_or(0) as u16;
39    ContextBundle {
40        bundle_id: format!("bundle-{task_id}-{}", selected.len()),
41        task_id: task_id.into(),
42        candidates: selected
43            .iter()
44            .map(|candidate| candidate.candidate_id.clone())
45            .collect(),
46        total_tokens,
47        coverage_milli,
48        strategy,
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55    fn candidates() -> Vec<ContextCandidate> {
56        (0..4)
57            .map(|id| ContextCandidate {
58                candidate_id: format!("c{id}"),
59                source_id: "local_files".into(),
60                kind: "file".into(),
61                relevance_milli: 800 + id,
62                estimated_tokens: 100,
63                reference: None,
64            })
65            .collect()
66    }
67    #[test]
68    fn minimal_has_at_most_three_candidates() {
69        assert_eq!(
70            create_bundle("task", &candidates(), BundleStrategy::Minimal)
71                .candidates
72                .len(),
73            3
74        );
75    }
76    #[test]
77    fn coverage_is_average_relevance() {
78        assert_eq!(
79            create_bundle("task", &candidates()[..2], BundleStrategy::Enriched).coverage_milli,
80            800
81        );
82    }
83}