Skip to main content

a3s_code_core/context/
assembler.rs

1//! Budgeted assembly for context items.
2
3use super::{ContextItem, ContextResult};
4use std::collections::HashMap;
5
6/// Budget limits for prompt-bound context.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct ContextBudget {
9    pub max_items: usize,
10    pub max_tokens: usize,
11}
12
13impl Default for ContextBudget {
14    fn default() -> Self {
15        Self {
16            max_items: 12,
17            max_tokens: 4_000,
18        }
19    }
20}
21
22/// Source-aware limits that prevent one context source from dominating the prompt.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct ContextSourcePolicy {
25    pub max_items_per_source: Option<usize>,
26    pub max_tokens_per_source: Option<usize>,
27}
28
29impl Default for ContextSourcePolicy {
30    fn default() -> Self {
31        Self {
32            max_items_per_source: Some(6),
33            max_tokens_per_source: Some(2_500),
34        }
35    }
36}
37
38/// Named budget policy for context assembly.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct ContextAssemblyPolicy {
41    pub budget: ContextBudget,
42    pub source_policy: ContextSourcePolicy,
43}
44
45impl ContextAssemblyPolicy {
46    pub fn balanced() -> Self {
47        Self {
48            budget: ContextBudget {
49                max_items: 12,
50                max_tokens: 4_000,
51            },
52            source_policy: ContextSourcePolicy {
53                max_items_per_source: Some(6),
54                max_tokens_per_source: Some(2_500),
55            },
56        }
57    }
58
59    pub fn compact() -> Self {
60        Self {
61            budget: ContextBudget {
62                max_items: 8,
63                max_tokens: 2_500,
64            },
65            source_policy: ContextSourcePolicy {
66                max_items_per_source: Some(4),
67                max_tokens_per_source: Some(1_200),
68            },
69        }
70    }
71
72    pub fn expansive() -> Self {
73        Self {
74            budget: ContextBudget {
75                max_items: 20,
76                max_tokens: 8_000,
77            },
78            source_policy: ContextSourcePolicy {
79                max_items_per_source: Some(8),
80                max_tokens_per_source: Some(3_500),
81            },
82        }
83    }
84}
85
86impl Default for ContextAssemblyPolicy {
87    fn default() -> Self {
88        Self::balanced()
89    }
90}
91
92/// Final context selected for prompt rendering.
93#[derive(Debug, Clone, Default)]
94pub struct ContextAssembly {
95    pub items: Vec<ContextItem>,
96    pub total_tokens: usize,
97    pub truncated: bool,
98}
99
100impl ContextAssembly {
101    pub fn to_xml(&self) -> String {
102        self.items
103            .iter()
104            .map(ContextItem::to_xml)
105            .collect::<Vec<_>>()
106            .join("\n\n")
107    }
108
109    pub fn is_empty(&self) -> bool {
110        self.items.is_empty()
111    }
112}
113
114/// Assembles raw provider results into a ranked, deduplicated, budgeted set.
115#[derive(Debug, Clone)]
116pub struct ContextAssembler {
117    budget: ContextBudget,
118    source_policy: ContextSourcePolicy,
119}
120
121impl ContextAssembler {
122    pub fn new(budget: ContextBudget) -> Self {
123        Self::from_policy(ContextAssemblyPolicy {
124            budget,
125            source_policy: ContextSourcePolicy::default(),
126        })
127    }
128
129    pub fn from_policy(policy: ContextAssemblyPolicy) -> Self {
130        Self {
131            budget: policy.budget,
132            source_policy: policy.source_policy,
133        }
134    }
135
136    pub fn with_source_policy(mut self, policy: ContextSourcePolicy) -> Self {
137        self.source_policy = policy;
138        self
139    }
140
141    pub fn with_default_budget() -> Self {
142        Self::from_policy(ContextAssemblyPolicy::balanced())
143    }
144
145    pub fn assemble(&self, results: &[ContextResult]) -> ContextAssembly {
146        let mut deduped: HashMap<String, ContextItem> = HashMap::new();
147        let mut source_count = 0usize;
148
149        for result in results {
150            for item in &result.items {
151                source_count += 1;
152                let key = dedupe_key(item);
153                match deduped.get(&key) {
154                    Some(existing)
155                        if ranking_score(existing)
156                            .total_cmp(&ranking_score(item))
157                            .then_with(|| existing.relevance.total_cmp(&item.relevance))
158                            .is_ge() => {}
159                    _ => {
160                        deduped.insert(key, item.clone());
161                    }
162                }
163            }
164        }
165
166        let mut items = deduped.into_values().collect::<Vec<_>>();
167        items.sort_by(|a, b| {
168            b.is_required()
169                .cmp(&a.is_required())
170                .then_with(|| ranking_score(b).total_cmp(&ranking_score(a)))
171                .then_with(|| b.relevance.total_cmp(&a.relevance))
172                .then_with(|| estimated_tokens(a).cmp(&estimated_tokens(b)))
173                .then_with(|| a.id.cmp(&b.id))
174        });
175
176        let mut selected = Vec::new();
177        let mut total_tokens = 0usize;
178        let mut truncated = source_count > items.len();
179        let mut source_item_counts: HashMap<String, usize> = HashMap::new();
180        let mut source_token_counts: HashMap<String, usize> = HashMap::new();
181
182        for item in items {
183            if item.is_required() {
184                total_tokens = total_tokens.saturating_add(estimated_tokens(&item));
185                selected.push(item);
186                continue;
187            }
188            if selected.len() >= self.budget.max_items {
189                truncated = true;
190                break;
191            }
192
193            let item_tokens = estimated_tokens(&item);
194            if total_tokens + item_tokens > self.budget.max_tokens {
195                truncated = true;
196                continue;
197            }
198
199            let source_key = source_policy_key(&item);
200            if let Some(max_items) = self.source_policy.max_items_per_source {
201                let count = source_item_counts.get(&source_key).copied().unwrap_or(0);
202                if count >= max_items {
203                    truncated = true;
204                    continue;
205                }
206            }
207            if let Some(max_tokens) = self.source_policy.max_tokens_per_source {
208                let source_tokens = source_token_counts.get(&source_key).copied().unwrap_or(0);
209                if source_tokens + item_tokens > max_tokens {
210                    truncated = true;
211                    continue;
212                }
213            }
214
215            total_tokens += item_tokens;
216            *source_item_counts.entry(source_key.clone()).or_insert(0) += 1;
217            *source_token_counts.entry(source_key).or_insert(0) += item_tokens;
218            selected.push(item);
219        }
220
221        ContextAssembly {
222            items: selected,
223            total_tokens,
224            truncated,
225        }
226    }
227}
228
229fn dedupe_key(item: &ContextItem) -> String {
230    item.source.clone().unwrap_or_else(|| item.id.clone())
231}
232
233fn source_policy_key(item: &ContextItem) -> String {
234    if let Some(provenance) = item.provenance() {
235        return format!("provenance:{provenance}");
236    }
237
238    if let Some(source) = &item.source {
239        let family = source
240            .split_once(':')
241            .map(|(family, _)| family)
242            .unwrap_or(source);
243        return format!("source:{family}");
244    }
245
246    format!("type:{:?}", item.context_type)
247}
248
249fn estimated_tokens(item: &ContextItem) -> usize {
250    if item.token_count > 0 {
251        item.token_count
252    } else {
253        item.content.split_whitespace().count().max(1)
254    }
255}
256
257fn ranking_score(item: &ContextItem) -> f32 {
258    item.relevance + item.priority() * 0.25 + item.trust() * 0.15 + item.freshness() * 0.10
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::context::{ContextItem, ContextResult, ContextType};
265
266    fn result(provider: &str, items: Vec<ContextItem>) -> ContextResult {
267        let mut result = ContextResult::new(provider);
268        for item in items {
269            result.add_item(item);
270        }
271        result
272    }
273
274    #[test]
275    fn balanced_policy_matches_default_budget_and_source_caps() {
276        let policy = ContextAssemblyPolicy::balanced();
277
278        assert_eq!(policy.budget, ContextBudget::default());
279        assert_eq!(policy.source_policy, ContextSourcePolicy::default());
280    }
281
282    #[test]
283    fn compact_policy_applies_tighter_caps() {
284        let assembler = ContextAssembler::from_policy(ContextAssemblyPolicy::compact());
285        let assembly = assembler.assemble(&[result(
286            "test",
287            (0..10)
288                .map(|index| {
289                    ContextItem::new(
290                        format!("file-{index}"),
291                        ContextType::Resource,
292                        format!("file {index}"),
293                    )
294                    .with_source(format!("file://{index}"))
295                    .with_relevance(1.0 - index as f32 * 0.01)
296                    .with_token_count(1)
297                })
298                .collect(),
299        )]);
300
301        assert_eq!(assembly.items.len(), 4);
302        assert!(assembly.truncated);
303    }
304
305    #[test]
306    fn expansive_policy_allows_broader_context() {
307        let assembler = ContextAssembler::from_policy(ContextAssemblyPolicy::expansive());
308        let assembly = assembler.assemble(&[result(
309            "test",
310            (0..8)
311                .map(|index| {
312                    ContextItem::new(
313                        format!("file-{index}"),
314                        ContextType::Resource,
315                        format!("file {index}"),
316                    )
317                    .with_source(format!("file://{index}"))
318                    .with_relevance(1.0 - index as f32 * 0.01)
319                    .with_token_count(1)
320                })
321                .collect(),
322        )]);
323
324        assert_eq!(assembly.items.len(), 8);
325        assert!(!assembly.truncated);
326    }
327
328    #[test]
329    fn assemble_ranks_by_relevance() {
330        let assembler = ContextAssembler::new(ContextBudget {
331            max_items: 10,
332            max_tokens: 100,
333        });
334        let assembly = assembler.assemble(&[result(
335            "test",
336            vec![
337                ContextItem::new("low", ContextType::Resource, "low")
338                    .with_relevance(0.1)
339                    .with_token_count(1),
340                ContextItem::new("high", ContextType::Resource, "high")
341                    .with_relevance(0.9)
342                    .with_token_count(1),
343            ],
344        )]);
345
346        assert_eq!(assembly.items[0].id, "high");
347        assert_eq!(assembly.items[1].id, "low");
348        assert!(!assembly.truncated);
349    }
350
351    #[test]
352    fn assemble_uses_priority_trust_and_freshness_as_ranking_signals() {
353        let assembler = ContextAssembler::new(ContextBudget {
354            max_items: 10,
355            max_tokens: 100,
356        });
357        let assembly = assembler.assemble(&[result(
358            "test",
359            vec![
360                ContextItem::new("plain", ContextType::Resource, "plain")
361                    .with_relevance(0.7)
362                    .with_token_count(1),
363                ContextItem::new("boosted", ContextType::Resource, "boosted")
364                    .with_relevance(0.6)
365                    .with_priority(1.0)
366                    .with_trust(1.0)
367                    .with_freshness(1.0)
368                    .with_token_count(1),
369            ],
370        )]);
371
372        assert_eq!(assembly.items[0].id, "boosted");
373        assert_eq!(assembly.items[1].id, "plain");
374    }
375
376    #[test]
377    fn assemble_dedupes_by_source_and_keeps_more_relevant_item() {
378        let assembler = ContextAssembler::with_default_budget();
379        let assembly = assembler.assemble(&[result(
380            "test",
381            vec![
382                ContextItem::new("old", ContextType::Resource, "old")
383                    .with_source("file://auth.rs")
384                    .with_relevance(0.2),
385                ContextItem::new("new", ContextType::Resource, "new")
386                    .with_source("file://auth.rs")
387                    .with_relevance(0.8),
388            ],
389        )]);
390
391        assert_eq!(assembly.items.len(), 1);
392        assert_eq!(assembly.items[0].id, "new");
393        assert!(assembly.truncated);
394    }
395
396    #[test]
397    fn assemble_dedupes_by_ranking_score() {
398        let assembler = ContextAssembler::with_default_budget();
399        let assembly = assembler.assemble(&[result(
400            "test",
401            vec![
402                ContextItem::new("plain", ContextType::Resource, "plain")
403                    .with_source("file://auth.rs")
404                    .with_relevance(0.7),
405                ContextItem::new("boosted", ContextType::Resource, "boosted")
406                    .with_source("file://auth.rs")
407                    .with_relevance(0.6)
408                    .with_priority(1.0),
409            ],
410        )]);
411
412        assert_eq!(assembly.items.len(), 1);
413        assert_eq!(assembly.items[0].id, "boosted");
414        assert!(assembly.truncated);
415    }
416
417    #[test]
418    fn assemble_respects_item_and_token_budget() {
419        let assembler = ContextAssembler::new(ContextBudget {
420            max_items: 1,
421            max_tokens: 5,
422        });
423        let assembly = assembler.assemble(&[result(
424            "test",
425            vec![
426                ContextItem::new("a", ContextType::Resource, "one two")
427                    .with_relevance(0.9)
428                    .with_token_count(2),
429                ContextItem::new("b", ContextType::Resource, "three four")
430                    .with_relevance(0.8)
431                    .with_token_count(2),
432            ],
433        )]);
434
435        assert_eq!(assembly.items.len(), 1);
436        assert_eq!(assembly.total_tokens, 2);
437        assert!(assembly.truncated);
438    }
439
440    #[test]
441    fn assemble_caps_items_per_source() {
442        let assembler = ContextAssembler::new(ContextBudget {
443            max_items: 10,
444            max_tokens: 100,
445        })
446        .with_source_policy(ContextSourcePolicy {
447            max_items_per_source: Some(2),
448            max_tokens_per_source: None,
449        });
450        let assembly = assembler.assemble(&[result(
451            "test",
452            vec![
453                ContextItem::new("a", ContextType::Resource, "a")
454                    .with_source("file://a")
455                    .with_relevance(0.9)
456                    .with_token_count(1),
457                ContextItem::new("b", ContextType::Resource, "b")
458                    .with_source("file://b")
459                    .with_relevance(0.8)
460                    .with_token_count(1),
461                ContextItem::new("c", ContextType::Resource, "c")
462                    .with_source("file://c")
463                    .with_relevance(0.7)
464                    .with_token_count(1),
465            ],
466        )]);
467
468        assert_eq!(assembly.items.len(), 2);
469        assert_eq!(assembly.items[0].id, "a");
470        assert_eq!(assembly.items[1].id, "b");
471        assert!(assembly.truncated);
472    }
473
474    #[test]
475    fn assemble_caps_tokens_per_source_but_keeps_other_sources() {
476        let assembler = ContextAssembler::new(ContextBudget {
477            max_items: 10,
478            max_tokens: 100,
479        })
480        .with_source_policy(ContextSourcePolicy {
481            max_items_per_source: None,
482            max_tokens_per_source: Some(3),
483        });
484        let assembly = assembler.assemble(&[result(
485            "test",
486            vec![
487                ContextItem::new("file-a", ContextType::Resource, "file a")
488                    .with_source("file://a")
489                    .with_relevance(0.9)
490                    .with_token_count(2),
491                ContextItem::new("file-b", ContextType::Resource, "file b")
492                    .with_source("file://b")
493                    .with_relevance(0.8)
494                    .with_token_count(2),
495                ContextItem::new("memory", ContextType::Memory, "memory")
496                    .with_source("memory://a")
497                    .with_relevance(0.7)
498                    .with_token_count(2),
499            ],
500        )]);
501
502        assert_eq!(
503            assembly
504                .items
505                .iter()
506                .map(|item| item.id.as_str())
507                .collect::<Vec<_>>(),
508            vec!["file-a", "memory"]
509        );
510        assert_eq!(assembly.total_tokens, 4);
511        assert!(assembly.truncated);
512    }
513
514    #[test]
515    fn required_workspace_instructions_bypass_generic_context_budgets() {
516        let assembler = ContextAssembler::new(ContextBudget {
517            max_items: 1,
518            max_tokens: 2,
519        })
520        .with_source_policy(ContextSourcePolicy {
521            max_items_per_source: Some(1),
522            max_tokens_per_source: Some(1),
523        });
524        let instructions = ContextItem::new(
525            "agents_md",
526            ContextType::Resource,
527            "one two three four five six",
528        )
529        .with_source("a3s://workspace-instructions")
530        .with_provenance("workspace_instructions")
531        .with_token_count(6)
532        .with_required();
533        let ordinary = ContextItem::new("ordinary", ContextType::Resource, "ordinary")
534            .with_token_count(1)
535            .with_relevance(1.0);
536
537        let assembly = assembler.assemble(&[result("test", vec![ordinary, instructions])]);
538
539        assert_eq!(assembly.items.len(), 1);
540        assert_eq!(assembly.items[0].id, "agents_md");
541        assert_eq!(assembly.total_tokens, 6);
542        assert!(assembly.truncated);
543    }
544}