Skip to main content

lean_ctx_ext/core/
context_handles.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Context Handles -- sparse, lazy references to context items.
3//!
4//! A handle is a lightweight proxy (~5-30 tokens) for a context item that
5//! would otherwise cost hundreds or thousands of tokens to include in full.
6//! Handles are rendered in a compact manifest inside the system prompt,
7//! allowing the agent to selectively expand items via `ctx_expand @ref`.
8
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11
12use super::context_field::{ContextItemId, ContextKind, ViewCosts, ViewKind};
13
14// ---------------------------------------------------------------------------
15// Core types
16// ---------------------------------------------------------------------------
17
18/// A sparse, lazy reference to a context item.
19///
20/// The handle carries just enough information for the agent to decide
21/// whether to expand the item, without paying the full token cost upfront.
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct ContextHandle {
24    pub ref_label: String,
25    pub item_id: ContextItemId,
26    pub kind: ContextKind,
27    pub source_path: String,
28    pub summary: String,
29    pub handle_tokens: usize,
30    pub available_views: Vec<(ViewKind, usize)>,
31    pub phi: f64,
32    pub pinned: bool,
33}
34
35/// Registry that owns all active handles and generates sequential ref-labels.
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct HandleRegistry {
38    handles: Vec<ContextHandle>,
39    counters: HashMap<ContextKind, usize>,
40}
41
42// ---------------------------------------------------------------------------
43// Kind -> prefix mapping
44// ---------------------------------------------------------------------------
45
46fn kind_prefix(kind: &ContextKind) -> &'static str {
47    match kind {
48        ContextKind::File => "F",
49        ContextKind::Shell => "S",
50        ContextKind::Knowledge => "K",
51        ContextKind::Memory => "M",
52        ContextKind::Provider => "P",
53    }
54}
55
56// ---------------------------------------------------------------------------
57// HandleRegistry implementation
58// ---------------------------------------------------------------------------
59
60impl HandleRegistry {
61    pub fn new() -> Self {
62        Self {
63            handles: Vec::new(),
64            counters: HashMap::new(),
65        }
66    }
67
68    /// Register a new context item and assign the next sequential ref-label.
69    ///
70    /// Returns a reference to the newly created handle.
71    pub fn register(
72        &mut self,
73        item_id: ContextItemId,
74        kind: ContextKind,
75        source_path: &str,
76        summary: &str,
77        view_costs: &ViewCosts,
78        phi: f64,
79        pinned: bool,
80    ) -> &ContextHandle {
81        let counter = self.counters.entry(kind).or_insert(0);
82        *counter += 1;
83        let ref_label = format!("{}{}", kind_prefix(&kind), counter);
84
85        let available_views: Vec<(ViewKind, usize)> = {
86            let mut views: Vec<_> = view_costs
87                .estimates
88                .iter()
89                .filter(|(v, _)| **v != ViewKind::Handle)
90                .map(|(&v, &tokens)| (v, tokens))
91                .collect();
92            views.sort_by_key(|(v, _)| v.density_rank());
93            views
94        };
95
96        let handle_tokens = view_costs
97            .estimates
98            .get(&ViewKind::Handle)
99            .copied()
100            .unwrap_or_else(|| estimate_handle_tokens(source_path, summary));
101
102        let handle = ContextHandle {
103            ref_label,
104            item_id,
105            kind,
106            source_path: source_path.to_string(),
107            summary: summary.to_string(),
108            handle_tokens,
109            available_views,
110            phi,
111            pinned,
112        };
113
114        self.handles.push(handle);
115        self.handles.last().expect("just pushed")
116    }
117
118    /// Look up a handle by its ref-label (e.g. "F1", "S3").
119    ///
120    /// Accepts labels with or without the leading `@`.
121    pub fn resolve(&self, ref_label: &str) -> Option<&ContextHandle> {
122        let label = ref_label.strip_prefix('@').unwrap_or(ref_label);
123        self.handles.iter().find(|h| h.ref_label == label)
124    }
125
126    /// Look up a handle by its underlying item ID.
127    pub fn resolve_by_item(&self, item_id: &ContextItemId) -> Option<&ContextHandle> {
128        self.handles.iter().find(|h| h.item_id == *item_id)
129    }
130
131    /// All registered handles, in registration order.
132    pub fn all(&self) -> &[ContextHandle] {
133        &self.handles
134    }
135
136    /// Sum of `handle_tokens` across all registered handles.
137    pub fn total_handle_tokens(&self) -> usize {
138        self.handles.iter().map(|h| h.handle_tokens).sum()
139    }
140
141    /// Render the compact handle manifest for inclusion in a system prompt.
142    pub fn format_manifest(&self, budget_total: usize, budget_used: usize) -> String {
143        if self.handles.is_empty() {
144            return String::new();
145        }
146
147        let mut lines = Vec::with_capacity(self.handles.len() + 3);
148        lines.push("Context Handles (expand with ctx_expand @ref):".to_string());
149
150        for h in &self.handles {
151            let best = h
152                .available_views
153                .first()
154                .map_or("full", |(v, _)| v.as_str());
155
156            let cheapest_tokens = h.available_views.iter().map(|(_, t)| *t).min().unwrap_or(0);
157
158            let pinned_tag = if h.pinned { " [pinned]" } else { "" };
159
160            lines.push(format!(
161                "@{} {} {} {}t phi={:.2}{}",
162                h.ref_label, h.source_path, best, cheapest_tokens, h.phi, pinned_tag,
163            ));
164        }
165
166        let remaining_pct = if budget_total > 0 {
167            ((budget_total.saturating_sub(budget_used)) as f64 / budget_total as f64) * 100.0
168        } else {
169            0.0
170        };
171
172        lines.push(String::new());
173        lines.push(format!(
174            "Budget: {budget_used}/{budget_total} tokens ({remaining_pct:.1}% remaining)",
175        ));
176
177        lines.join("\n")
178    }
179}
180
181impl Default for HandleRegistry {
182    fn default() -> Self {
183        Self::new()
184    }
185}
186
187// ---------------------------------------------------------------------------
188// Helpers
189// ---------------------------------------------------------------------------
190
191/// Rough estimate of how many tokens a handle line costs when no explicit
192/// Handle view cost is provided. Based on typical tokenizer ratios.
193fn estimate_handle_tokens(source_path: &str, summary: &str) -> usize {
194    let chars = source_path.len() + summary.len() + 20; // overhead for label, phi, etc.
195    (chars / 4).clamp(5, 50)
196}
197
198// ---------------------------------------------------------------------------
199// Tests
200// ---------------------------------------------------------------------------
201
202#[cfg(test)]
203pub mod tests {
204    use super::*;
205
206    fn sample_view_costs(full_tokens: usize) -> ViewCosts {
207        ViewCosts::from_full_tokens(full_tokens)
208    }
209
210    #[test]
211    fn label_generation_sequential_per_kind() {
212        let mut reg = HandleRegistry::new();
213
214        let h1 = reg.register(
215            ContextItemId::from_file("a.ts"),
216            ContextKind::File,
217            "a.ts",
218            "module A",
219            &sample_view_costs(1000),
220            0.9,
221            false,
222        );
223        assert_eq!(h1.ref_label, "F1");
224
225        let h2 = reg.register(
226            ContextItemId::from_file("b.ts"),
227            ContextKind::File,
228            "b.ts",
229            "module B",
230            &sample_view_costs(500),
231            0.8,
232            false,
233        );
234        assert_eq!(h2.ref_label, "F2");
235
236        let h3 = reg.register(
237            ContextItemId::from_shell("pytest"),
238            ContextKind::Shell,
239            "pytest_latest",
240            "test run output",
241            &sample_view_costs(2000),
242            0.7,
243            false,
244        );
245        assert_eq!(h3.ref_label, "S1");
246
247        let h4 = reg.register(
248            ContextItemId::from_knowledge("domain", "billing"),
249            ContextKind::Knowledge,
250            "billing_rules",
251            "annual billing assumption",
252            &sample_view_costs(100),
253            0.95,
254            true,
255        );
256        assert_eq!(h4.ref_label, "K1");
257    }
258
259    #[test]
260    fn resolve_by_ref_label() {
261        let mut reg = HandleRegistry::new();
262        reg.register(
263            ContextItemId::from_file("x.rs"),
264            ContextKind::File,
265            "x.rs",
266            "file X",
267            &sample_view_costs(400),
268            0.85,
269            false,
270        );
271        reg.register(
272            ContextItemId::from_shell("cargo test"),
273            ContextKind::Shell,
274            "cargo_test",
275            "test output",
276            &sample_view_costs(800),
277            0.6,
278            false,
279        );
280
281        assert!(reg.resolve("F1").is_some());
282        assert_eq!(reg.resolve("F1").unwrap().source_path, "x.rs");
283
284        assert!(reg.resolve("@S1").is_some());
285        assert_eq!(reg.resolve("@S1").unwrap().source_path, "cargo_test");
286
287        assert!(reg.resolve("F99").is_none());
288    }
289
290    #[test]
291    fn resolve_by_item_id() {
292        let mut reg = HandleRegistry::new();
293        let id = ContextItemId::from_file("main.rs");
294        reg.register(
295            id.clone(),
296            ContextKind::File,
297            "main.rs",
298            "entrypoint",
299            &sample_view_costs(600),
300            0.92,
301            false,
302        );
303
304        let found = reg.resolve_by_item(&id);
305        assert!(found.is_some());
306        assert_eq!(found.unwrap().ref_label, "F1");
307
308        let missing = reg.resolve_by_item(&ContextItemId::from_file("nope.rs"));
309        assert!(missing.is_none());
310    }
311
312    #[test]
313    fn manifest_formatting() {
314        let mut reg = HandleRegistry::new();
315        reg.register(
316            ContextItemId::from_file("billing/service.ts"),
317            ContextKind::File,
318            "billing/service.ts",
319            "exports: createInvoice, calculateTax",
320            &sample_view_costs(2000),
321            0.93,
322            false,
323        );
324        reg.register(
325            ContextItemId::from_knowledge("domain", "annual"),
326            ContextKind::Knowledge,
327            "annual_billing",
328            "assumption",
329            &sample_view_costs(200),
330            0.95,
331            true,
332        );
333
334        let manifest = reg.format_manifest(12000, 2460);
335
336        assert!(manifest.contains("Context Handles"));
337        assert!(manifest.contains("@F1"));
338        assert!(manifest.contains("billing/service.ts"));
339        assert!(manifest.contains("phi=0.93"));
340        assert!(manifest.contains("@K1"));
341        assert!(manifest.contains("[pinned]"));
342        assert!(manifest.contains("Budget: 2460/12000 tokens"));
343        assert!(manifest.contains("remaining"));
344    }
345
346    #[test]
347    fn manifest_empty_registry() {
348        let reg = HandleRegistry::new();
349        let manifest = reg.format_manifest(10000, 0);
350        assert!(manifest.is_empty(), "{manifest:?}");
351    }
352
353    #[test]
354    fn total_handle_tokens() {
355        let mut reg = HandleRegistry::new();
356        reg.register(
357            ContextItemId::from_file("a.rs"),
358            ContextKind::File,
359            "a.rs",
360            "mod A",
361            &sample_view_costs(1000),
362            0.8,
363            false,
364        );
365        reg.register(
366            ContextItemId::from_file("b.rs"),
367            ContextKind::File,
368            "b.rs",
369            "mod B",
370            &sample_view_costs(2000),
371            0.7,
372            false,
373        );
374
375        let total = reg.total_handle_tokens();
376        assert_eq!(
377            total,
378            25 + 25,
379            "both handles should use ViewKind::Handle cost (25)"
380        );
381    }
382
383    #[test]
384    fn multiple_registrations_sequential() {
385        let mut reg = HandleRegistry::new();
386        for i in 1..=5 {
387            let path = format!("file_{i}.rs");
388            let id = ContextItemId::from_file(&path);
389            reg.register(
390                id,
391                ContextKind::File,
392                &path,
393                "some module",
394                &sample_view_costs(500),
395                0.5,
396                false,
397            );
398        }
399
400        assert_eq!(reg.all().len(), 5);
401        assert_eq!(reg.all()[0].ref_label, "F1");
402        assert_eq!(reg.all()[1].ref_label, "F2");
403        assert_eq!(reg.all()[2].ref_label, "F3");
404        assert_eq!(reg.all()[3].ref_label, "F4");
405        assert_eq!(reg.all()[4].ref_label, "F5");
406    }
407
408    #[test]
409    fn mixed_kinds_independent_counters() {
410        let mut reg = HandleRegistry::new();
411
412        reg.register(
413            ContextItemId::from_file("a.rs"),
414            ContextKind::File,
415            "a.rs",
416            "file",
417            &sample_view_costs(100),
418            0.5,
419            false,
420        );
421        reg.register(
422            ContextItemId::from_shell("ls"),
423            ContextKind::Shell,
424            "ls",
425            "listing",
426            &sample_view_costs(100),
427            0.5,
428            false,
429        );
430        reg.register(
431            ContextItemId::from_file("b.rs"),
432            ContextKind::File,
433            "b.rs",
434            "file",
435            &sample_view_costs(100),
436            0.5,
437            false,
438        );
439        reg.register(
440            ContextItemId::from_memory("session"),
441            ContextKind::Memory,
442            "session_state",
443            "memory",
444            &sample_view_costs(100),
445            0.5,
446            false,
447        );
448        reg.register(
449            ContextItemId::from_provider("github", "pr"),
450            ContextKind::Provider,
451            "github/pr/123",
452            "pull request",
453            &sample_view_costs(100),
454            0.5,
455            false,
456        );
457
458        assert_eq!(reg.resolve("F1").unwrap().source_path, "a.rs");
459        assert_eq!(reg.resolve("S1").unwrap().source_path, "ls");
460        assert_eq!(reg.resolve("F2").unwrap().source_path, "b.rs");
461        assert_eq!(reg.resolve("M1").unwrap().source_path, "session_state");
462        assert_eq!(reg.resolve("P1").unwrap().source_path, "github/pr/123");
463    }
464
465    #[test]
466    fn available_views_sorted_by_density() {
467        let mut reg = HandleRegistry::new();
468        let h = reg.register(
469            ContextItemId::from_file("c.rs"),
470            ContextKind::File,
471            "c.rs",
472            "module C",
473            &sample_view_costs(4000),
474            0.9,
475            false,
476        );
477
478        let ranks: Vec<u8> = h
479            .available_views
480            .iter()
481            .map(|(v, _)| v.density_rank())
482            .collect();
483
484        for window in ranks.windows(2) {
485            assert!(
486                window[0] <= window[1],
487                "views should be sorted by density rank (dense first)"
488            );
489        }
490    }
491
492    #[test]
493    fn handle_tokens_fallback_without_handle_view() {
494        let mut costs = ViewCosts::new();
495        costs.set(ViewKind::Full, 5000);
496        costs.set(ViewKind::Signatures, 1000);
497
498        let mut reg = HandleRegistry::new();
499        let h = reg.register(
500            ContextItemId::from_file("big.rs"),
501            ContextKind::File,
502            "src/core/big_module.rs",
503            "large module with many exports",
504            &costs,
505            0.88,
506            false,
507        );
508
509        assert!(
510            h.handle_tokens >= 5,
511            "fallback should produce at least 5 tokens"
512        );
513        assert!(
514            h.handle_tokens <= 50,
515            "fallback should produce at most 50 tokens"
516        );
517    }
518
519    #[test]
520    fn budget_remaining_percentage() {
521        let reg = {
522            let mut r = HandleRegistry::new();
523            r.register(
524                ContextItemId::from_file("x.rs"),
525                ContextKind::File,
526                "x.rs",
527                "x",
528                &sample_view_costs(100),
529                0.5,
530                false,
531            );
532            r
533        };
534
535        let manifest = reg.format_manifest(10000, 2000);
536        assert!(manifest.contains("80.0% remaining"));
537    }
538}