vectorless 0.1.26

Hierarchical, reasoning-native document intelligence engine
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
// Copyright (c) 2026 vectorless developers
// SPDX-License-Identifier: Apache-2.0

//! Token budget allocation for content aggregation.
//!
//! This module provides budget-aware content selection that optimizes
//! token usage while maximizing relevance.

use std::collections::HashMap;

use crate::document::NodeId;
use crate::utils::estimate_tokens;

use super::scorer::ContentRelevance;

/// Allocation strategy for distributing token budget.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AllocationStrategy {
    /// Select highest-scoring content first until budget exhausted.
    Greedy,
    /// Distribute budget proportionally to relevance scores.
    Proportional,
    /// Ensure each depth level has minimum representation.
    Hierarchical {
        /// Minimum fraction of budget per level (0.0 - 1.0)
        min_per_level: f32,
    },
}

impl Default for AllocationStrategy {
    fn default() -> Self {
        Self::Hierarchical { min_per_level: 0.1 }
    }
}

/// Information about content truncation.
#[derive(Debug, Clone)]
pub struct TruncationInfo {
    /// Original content length in characters.
    pub original_len: usize,
    /// Truncated content length in characters.
    pub truncated_len: usize,
    /// Reason for truncation.
    pub reason: TruncationReason,
}

/// Reason for content truncation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TruncationReason {
    /// Content exceeded remaining budget.
    BudgetExceeded,
    /// Content tail had low relevance.
    LowRelevanceTail,
}

/// A selected content item after budget allocation.
#[derive(Debug, Clone)]
pub struct SelectedContent {
    /// Node ID.
    pub node_id: NodeId,
    /// Node title.
    pub title: String,
    /// Selected content text.
    pub content: String,
    /// Token count of selected content.
    pub tokens: usize,
    /// Relevance score.
    pub score: f32,
    /// Depth in tree.
    pub depth: usize,
    /// Truncation info if content was truncated.
    pub truncation: Option<TruncationInfo>,
}

impl SelectedContent {
    /// Check if content was truncated.
    #[must_use]
    pub fn is_truncated(&self) -> bool {
        self.truncation.is_some()
    }
}

/// Statistics about the allocation process.
#[derive(Debug, Clone, Default)]
pub struct AllocationStats {
    /// Total content items considered.
    pub items_considered: usize,
    /// Items selected for output.
    pub items_selected: usize,
    /// Items truncated.
    pub items_truncated: usize,
    /// Items filtered (below threshold).
    pub items_filtered: usize,
    /// Average score of selected items.
    pub avg_score: f32,
}

/// Result of budget allocation.
#[derive(Debug, Clone)]
pub struct AllocationResult {
    /// Selected content items.
    pub selected: Vec<SelectedContent>,
    /// Total tokens used.
    pub tokens_used: usize,
    /// Remaining token budget.
    pub remaining_budget: usize,
    /// Allocation statistics.
    pub stats: AllocationStats,
}

impl AllocationResult {
    /// Check if any content was selected.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.selected.is_empty()
    }

    /// Get number of selected items.
    #[must_use]
    pub fn len(&self) -> usize {
        self.selected.len()
    }
}

/// Token budget allocator.
#[derive(Debug)]
pub struct BudgetAllocator {
    /// Total token budget.
    total_budget: usize,
    /// Minimum reserve budget (for fallback).
    min_reserve: usize,
    /// Allocation strategy.
    strategy: AllocationStrategy,
    /// Minimum relevance score threshold.
    min_score: f32,
}

impl BudgetAllocator {
    /// Create a new allocator with the specified budget.
    #[must_use]
    pub fn new(budget: usize) -> Self {
        Self {
            total_budget: budget,
            min_reserve: budget / 10,
            strategy: AllocationStrategy::default(),
            min_score: 0.0,
        }
    }

    /// Set the allocation strategy.
    #[must_use]
    pub fn with_strategy(mut self, strategy: AllocationStrategy) -> Self {
        self.strategy = strategy;
        self
    }

    /// Set minimum relevance score threshold.
    #[must_use]
    pub fn with_min_score(mut self, min_score: f32) -> Self {
        self.min_score = min_score;
        self
    }

    /// Allocate budget to scored content.
    #[must_use]
    pub fn allocate(
        &self,
        scored_content: Vec<ContentRelevance>,
        max_depth: usize,
    ) -> AllocationResult {
        // Filter by minimum score
        let filtered: Vec<_> = scored_content
            .into_iter()
            .filter(|c| c.score >= self.min_score)
            .collect();

        let stats = AllocationStats {
            items_considered: filtered.len(),
            ..Default::default()
        };

        match &self.strategy {
            AllocationStrategy::Greedy => self.allocate_greedy(filtered, stats),
            AllocationStrategy::Proportional => self.allocate_proportional(filtered, stats),
            AllocationStrategy::Hierarchical { min_per_level } => {
                self.allocate_hierarchical(filtered, max_depth, *min_per_level, stats)
            }
        }
    }

    /// Greedy allocation: select highest-scoring content first.
    fn allocate_greedy(
        &self,
        mut content: Vec<ContentRelevance>,
        mut stats: AllocationStats,
    ) -> AllocationResult {
        // Sort by score descending
        content.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        let mut selected = Vec::new();
        let mut tokens_used = 0;

        for relevance in content {
            let tokens = relevance.chunk.token_count();

            if tokens_used + tokens <= self.total_budget {
                selected.push(SelectedContent {
                    node_id: relevance.chunk.node_id,
                    title: relevance.chunk.title,
                    content: relevance.chunk.content,
                    tokens,
                    score: relevance.score,
                    depth: relevance.chunk.depth,
                    truncation: None,
                });
                tokens_used += tokens;
            } else {
                // Try to fit truncated content
                let remaining = self.total_budget - tokens_used;
                if remaining >= 50 {
                    // Minimum useful content
                    if let Some(truncated) =
                        self.truncate_content(&relevance.chunk.content, remaining)
                    {
                        let truncated_tokens = estimate_tokens(&truncated);
                        selected.push(SelectedContent {
                            node_id: relevance.chunk.node_id,
                            title: relevance.chunk.title,
                            content: truncated,
                            tokens: truncated_tokens,
                            score: relevance.score,
                            depth: relevance.chunk.depth,
                            truncation: Some(TruncationInfo {
                                original_len: relevance.chunk.content.len(),
                                truncated_len: remaining,
                                reason: TruncationReason::BudgetExceeded,
                            }),
                        });
                        tokens_used += truncated_tokens;
                        stats.items_truncated += 1;
                    }
                }
                break;
            }
        }

        stats.items_selected = selected.len();
        stats.avg_score = if selected.is_empty() {
            0.0
        } else {
            selected.iter().map(|s| s.score).sum::<f32>() / selected.len() as f32
        };

        AllocationResult {
            selected,
            tokens_used,
            remaining_budget: self.total_budget - tokens_used,
            stats,
        }
    }

    /// Proportional allocation: distribute budget by score ratio.
    fn allocate_proportional(
        &self,
        content: Vec<ContentRelevance>,
        mut stats: AllocationStats,
    ) -> AllocationResult {
        let total_score: f32 = content.iter().map(|c| c.score).sum();
        if total_score == 0.0 {
            return AllocationResult {
                selected: Vec::new(),
                tokens_used: 0,
                remaining_budget: self.total_budget,
                stats,
            };
        }

        let mut selected = Vec::new();
        let mut tokens_used = 0;

        for relevance in content {
            // Calculate proportional budget
            let proportion = relevance.score / total_score;
            let allocated_budget = ((self.total_budget as f32 * proportion) as usize).max(50);

            let content_tokens = relevance.chunk.token_count();

            if content_tokens <= allocated_budget {
                // Full content fits
                if tokens_used + content_tokens <= self.total_budget {
                    selected.push(SelectedContent {
                        node_id: relevance.chunk.node_id,
                        title: relevance.chunk.title,
                        content: relevance.chunk.content,
                        tokens: content_tokens,
                        score: relevance.score,
                        depth: relevance.chunk.depth,
                        truncation: None,
                    });
                    tokens_used += content_tokens;
                }
            } else {
                // Truncate to allocated budget
                let remaining = self.total_budget - tokens_used;
                if remaining >= 50 && remaining >= allocated_budget / 2 {
                    if let Some(truncated) = self
                        .truncate_content(&relevance.chunk.content, remaining.min(allocated_budget))
                    {
                        let truncated_tokens = estimate_tokens(&truncated);
                        let truncated_len = truncated.len();
                        selected.push(SelectedContent {
                            node_id: relevance.chunk.node_id,
                            title: relevance.chunk.title,
                            content: truncated,
                            tokens: truncated_tokens,
                            score: relevance.score,
                            depth: relevance.chunk.depth,
                            truncation: Some(TruncationInfo {
                                original_len: relevance.chunk.content.len(),
                                truncated_len,
                                reason: TruncationReason::BudgetExceeded,
                            }),
                        });
                        tokens_used += truncated_tokens;
                        stats.items_truncated += 1;
                    }
                }
            }
        }

        stats.items_selected = selected.len();
        stats.avg_score = if selected.is_empty() {
            0.0
        } else {
            selected.iter().map(|s| s.score).sum::<f32>() / selected.len() as f32
        };

        AllocationResult {
            selected,
            tokens_used,
            remaining_budget: self.total_budget - tokens_used,
            stats,
        }
    }

    /// Hierarchical allocation: ensure each depth level has representation.
    fn allocate_hierarchical(
        &self,
        content: Vec<ContentRelevance>,
        max_depth: usize,
        min_per_level: f32,
        mut stats: AllocationStats,
    ) -> AllocationResult {
        // Group content by depth
        let mut by_depth: HashMap<usize, Vec<ContentRelevance>> = HashMap::new();
        for c in content {
            by_depth.entry(c.chunk.depth).or_default().push(c);
        }

        // Sort each level by score
        for (_depth, items) in by_depth.iter_mut() {
            items.sort_by(|a, b| {
                b.score
                    .partial_cmp(&a.score)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
        }

        let per_level_budget = (self.total_budget as f32 * min_per_level) as usize;
        let mut selected = Vec::new();
        let mut tokens_used = 0;

        // Process from shallow to deep
        for depth in 0..=max_depth {
            if tokens_used >= self.total_budget {
                break;
            }

            if let Some(level_content) = by_depth.get(&depth) {
                let mut level_used = 0;

                for relevance in level_content {
                    if tokens_used >= self.total_budget {
                        break;
                    }

                    let tokens = relevance.chunk.token_count();

                    // Check if we should include this content
                    let can_include_full = tokens_used + tokens <= self.total_budget;
                    let level_budget_ok = level_used < per_level_budget || depth == 0;

                    if can_include_full && level_budget_ok {
                        selected.push(SelectedContent {
                            node_id: relevance.chunk.node_id,
                            title: relevance.chunk.title.clone(),
                            content: relevance.chunk.content.clone(),
                            tokens,
                            score: relevance.score,
                            depth,
                            truncation: None,
                        });
                        tokens_used += tokens;
                        level_used += tokens;
                    } else if level_used < per_level_budget {
                        // Try truncated version
                        let remaining =
                            (self.total_budget - tokens_used).min(per_level_budget - level_used);
                        if remaining >= 50 {
                            if let Some(truncated) =
                                self.truncate_content(&relevance.chunk.content, remaining)
                            {
                                let truncated_tokens = estimate_tokens(&truncated);
                                selected.push(SelectedContent {
                                    node_id: relevance.chunk.node_id,
                                    title: relevance.chunk.title.clone(),
                                    content: truncated,
                                    tokens: truncated_tokens,
                                    score: relevance.score,
                                    depth,
                                    truncation: Some(TruncationInfo {
                                        original_len: relevance.chunk.content.len(),
                                        truncated_len: remaining,
                                        reason: TruncationReason::BudgetExceeded,
                                    }),
                                });
                                tokens_used += truncated_tokens;
                                level_used += truncated_tokens;
                                stats.items_truncated += 1;
                            }
                        }
                    }
                }
            }
        }

        // Second pass: fill remaining budget with highest-scoring content
        if tokens_used < self.total_budget - self.min_reserve {
            let mut all_remaining: Vec<_> = by_depth
                .values()
                .flat_map(|v| v.iter())
                .filter(|c| !selected.iter().any(|s| s.node_id == c.chunk.node_id))
                .collect();

            all_remaining.sort_by(|a, b| {
                b.score
                    .partial_cmp(&a.score)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });

            for relevance in all_remaining {
                if tokens_used >= self.total_budget - self.min_reserve {
                    break;
                }

                let tokens = relevance.chunk.token_count();
                if tokens_used + tokens <= self.total_budget {
                    selected.push(SelectedContent {
                        node_id: relevance.chunk.node_id,
                        title: relevance.chunk.title.clone(),
                        content: relevance.chunk.content.clone(),
                        tokens,
                        score: relevance.score,
                        depth: relevance.chunk.depth,
                        truncation: None,
                    });
                    tokens_used += tokens;
                }
            }
        }

        stats.items_selected = selected.len();
        stats.avg_score = if selected.is_empty() {
            0.0
        } else {
            selected.iter().map(|s| s.score).sum::<f32>() / selected.len() as f32
        };

        AllocationResult {
            selected,
            tokens_used,
            remaining_budget: self.total_budget - tokens_used,
            stats,
        }
    }

    /// Truncate content to fit within token budget.
    fn truncate_content(&self, content: &str, max_tokens: usize) -> Option<String> {
        if max_tokens < 20 {
            return None;
        }

        // Approximate: 1 token ≈ 4 characters (for English)
        let max_chars = max_tokens * 4;

        if content.len() <= max_chars {
            return Some(content.to_string());
        }

        // Try to break at sentence boundary
        let truncated = &content[..max_chars];

        // Find last sentence boundary
        if let Some(pos) = truncated.rfind(|c| c == '.' || c == '!' || c == '?') {
            Some(format!("{}...", &truncated[..=pos]))
        } else if let Some(pos) = truncated.rfind(' ') {
            // Fall back to word boundary
            Some(format!("{}...", &truncated[..pos]))
        } else {
            // Hard truncate
            Some(format!("{}...", truncated))
        }
    }
}

impl Default for BudgetAllocator {
    fn default() -> Self {
        Self::new(4000)
    }
}