scribe-selection 0.5.1

Intelligent code selection and context extraction for Scribe
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
//! Token budget selection logic previously implemented in the analyzer crate.
//! This module provides a shared implementation that can be reused by both the
//! library pipeline and external consumers without duplicating complex logic.

use crate::demotion::{DemotionEngine, FidelityMode};
use scribe_analysis::heuristics::ScanResult;
use scribe_core::{
    tokenization::{TokenBudget, TokenCounter},
    Config, FileInfo, FileType, Result, ScribeError,
};
use scribe_graph::CentralityCalculator;
use std::collections::HashSet;
use std::path::Path;

/// Apply the library's tiered token budget selection to a set of files.
///
/// The selector prioritizes files in multiple tiers:
/// 1. Mandatory project metadata (README, config files, entrypoints)
/// 2. Source files ordered by graph centrality with demotion fallback
/// 3. Documentation with preference for design/architecture material
/// 4. Any remaining files while budget remains
///
/// The function loads file content and token estimates for the selected files
/// and will attempt demotion (chunk/signature extraction) when a source file
/// would otherwise exceed the available budget.
pub async fn apply_token_budget_selection(
    files: Vec<FileInfo>,
    token_budget: usize,
    config: &Config,
) -> Result<Vec<FileInfo>> {
    if std::env::var("SCRIBE_DEBUG").is_ok() {
        eprintln!(
            "🎯 Intelligent token budget selection: {} tokens across {} files",
            token_budget,
            files.len()
        );
    }

    let counter = TokenCounter::global();
    let mut selected_files = Vec::new();

    // Split files into categories for prioritized selection
    let (mandatory_files, source_files, doc_files, other_files) = categorize_files(files.clone());

    // Keep a reference to all files for final optimization pass
    let all_files = files;

    if std::env::var("SCRIBE_DEBUG").is_ok() {
        eprintln!(
            "📊 File categories: {} mandatory, {} source, {} docs, {} other",
            mandatory_files.len(),
            source_files.len(),
            doc_files.len(),
            other_files.len()
        );
    }

    let mut budget_tracker = TokenBudget::new(token_budget);

    // Tier 1: Mandatory files (README, project config, main/index files)
    if std::env::var("SCRIBE_DEBUG").is_ok() {
        eprintln!("📌 Tier 1: Processing mandatory files");
    }
    for file in mandatory_files {
        if budget_tracker.available() < 1 {
            if std::env::var("SCRIBE_DEBUG").is_ok() {
                eprintln!("🛑 Budget exhausted, stopping mandatory file selection");
            }
            break;
        }
        if let Some(selected_file) =
            try_include_file_with_budget(file, &counter, &mut budget_tracker).await?
        {
            selected_files.push(selected_file);
        }
    }

    // Tier 2: Source files (prioritized by centrality)
    if !source_files.is_empty() && budget_tracker.available() > 0 {
        if std::env::var("SCRIBE_DEBUG").is_ok() {
            eprintln!("🧠 Tier 2: Processing source files with centrality analysis");
        }

        // Calculate centrality scores for source files
        let calculator = CentralityCalculator::new()?;
        let mock_scan_results: Vec<_> = source_files
            .iter()
            .map(MockScanResult::from_file_info)
            .collect();
        let centrality_results = calculator.calculate_centrality(&mock_scan_results)?;

        let mut source_with_centrality: Vec<_> = source_files
            .into_iter()
            .map(|mut file| {
                let centrality_score = centrality_results
                    .pagerank_scores
                    .get(&file.relative_path)
                    .copied()
                    .unwrap_or(0.0);
                file.centrality_score = Some(centrality_score);
                (file, centrality_score)
            })
            .collect();

        // Sort by centrality score (highest first)
        source_with_centrality
            .sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

        if std::env::var("SCRIBE_DEBUG").is_ok() && !source_with_centrality.is_empty() {
            eprintln!("🔍 Top 10 source files by centrality:");
            for (i, (file, score)) in source_with_centrality.iter().enumerate().take(10) {
                eprintln!("  {}. {} (score: {:.6})", i + 1, file.relative_path, score);
            }
        }

        for (file, centrality_score) in source_with_centrality {
            if budget_tracker.available() < 1 {
                if std::env::var("SCRIBE_DEBUG").is_ok() {
                    eprintln!("🛑 Budget exhausted, stopping source selection");
                }
                break;
            }

            if let Some(selected_file) = try_include_file_with_budget_and_demotion(
                file,
                &counter,
                &mut budget_tracker,
                centrality_score,
            )
            .await?
            {
                if std::env::var("SCRIBE_DEBUG").is_ok() {
                    eprintln!(
                        "✅ Selected {} (centrality: {:.4})",
                        selected_file.relative_path, centrality_score
                    );
                }
                selected_files.push(selected_file);
            }
        }
    }

    // Tier 3: Documentation files
    if !doc_files.is_empty() && budget_tracker.available() > 0 {
        if std::env::var("SCRIBE_DEBUG").is_ok() {
            eprintln!("📚 Tier 3: Processing documentation files");
        }

        // Sort docs by importance - prioritize architecture/design docs
        let mut critical_docs = Vec::new();
        let mut other_docs = Vec::new();

        for file in doc_files {
            let path_lower = file.relative_path.to_lowercase();
            if path_lower.contains("architecture")
                || path_lower.contains("design")
                || path_lower.contains("api")
                || path_lower.contains("spec")
                || path_lower.ends_with("changelog.md")
                || path_lower.ends_with("contributing.md")
            {
                critical_docs.push(file);
            } else {
                other_docs.push(file);
            }
        }

        // Process critical docs first, then others
        for file in critical_docs.into_iter().chain(other_docs.into_iter()) {
            if budget_tracker.available() < 1 {
                if std::env::var("SCRIBE_DEBUG").is_ok() {
                    eprintln!("🛑 Budget exhausted, stopping documentation selection");
                }
                break;
            }

            if let Some(selected_file) =
                try_include_file_with_budget(file, &counter, &mut budget_tracker).await?
            {
                selected_files.push(selected_file);
            }
        }
    }

    // Tier 4: Other files (if budget remains)
    if !other_files.is_empty() && budget_tracker.available() > 0 {
        if std::env::var("SCRIBE_DEBUG").is_ok() {
            eprintln!("📄 Tier 4: Processing other files");
        }

        for file in other_files {
            if budget_tracker.available() < 1 {
                if std::env::var("SCRIBE_DEBUG").is_ok() {
                    eprintln!("🛑 Budget exhausted, stopping other file selection");
                }
                break;
            }

            if let Some(selected_file) =
                try_include_file_with_budget(file, &counter, &mut budget_tracker).await?
            {
                selected_files.push(selected_file);
            }
        }
    }

    // Final optimization pass: try to fill remaining budget with smaller files
    if budget_tracker.available() > 1 {
        if std::env::var("SCRIBE_DEBUG").is_ok() {
            eprintln!(
                "🔧 Final optimization pass: {} tokens remaining, searching for small files",
                budget_tracker.available()
            );
        }

        let included_paths: HashSet<String> = selected_files
            .iter()
            .map(|f| f.relative_path.clone())
            .collect();

        // Try to find any remaining files that could fit
        for file in &all_files {
            if budget_tracker.available() < 1 {
                break;
            }

            if included_paths.contains(&file.relative_path) || !file.decision.should_include() {
                continue;
            }

            // Quick estimate - try small files that might fit
            if file.size <= (budget_tracker.available() * 4) as u64 {
                if let Some(selected_file) =
                    try_include_file_with_budget(file.clone(), &counter, &mut budget_tracker)
                        .await?
                {
                    if std::env::var("SCRIBE_DEBUG").is_ok() {
                        eprintln!(
                            "🎯 Final pass: included {} ({} tokens)",
                            selected_file.relative_path,
                            selected_file.token_estimate.unwrap_or(0)
                        );
                    }
                    selected_files.push(selected_file);
                }
            }
        }
    }

    let tokens_used = token_budget - budget_tracker.available();
    let utilization = (tokens_used as f64 / token_budget as f64) * 100.0;

    if std::env::var("SCRIBE_DEBUG").is_ok() {
        eprintln!(
            "✅ Selected {} files ({} tokens / {} budget, {:.1}% utilized)",
            selected_files.len(),
            tokens_used,
            token_budget,
            utilization
        );

        if utilization < 90.0 {
            eprintln!(
                "⚠️  Budget utilization below 90% - {} tokens unused",
                budget_tracker.available()
            );
        }
    }

    Ok(selected_files)
}

fn categorize_files(
    files: Vec<FileInfo>,
) -> (Vec<FileInfo>, Vec<FileInfo>, Vec<FileInfo>, Vec<FileInfo>) {
    let mut mandatory = Vec::new();
    let mut source = Vec::new();
    let mut docs = Vec::new();
    let mut other = Vec::new();

    for file in files {
        if !file.decision.should_include() {
            continue;
        }

        if is_mandatory_file(&file) {
            mandatory.push(file);
        } else if matches!(file.file_type, FileType::Source { .. }) {
            source.push(file);
        } else if matches!(file.file_type, FileType::Documentation { .. }) {
            docs.push(file);
        } else {
            other.push(file);
        }
    }

    (mandatory, source, docs, other)
}

fn is_mandatory_file(file: &FileInfo) -> bool {
    let path = file.relative_path.to_lowercase();

    // Skip files in dependency/build directories
    if path.contains("node_modules/")
        || path.contains("target/")
        || path.contains("vendor/")
        || path.contains(".git/")
        || path.contains("__pycache__/")
        || path.contains("build/")
        || path.contains("dist/")
        || path.contains(".cache/")
    {
        return false;
    }

    // README files (only in project root and first-level directories)
    if path.contains("readme") {
        let depth = path.matches('/').count();
        return depth <= 1;
    }

    // Project configuration files (only at root level)
    if !path.contains('/')
        && matches!(
            path.as_str(),
            "package.json"
                | "cargo.toml"
                | "pyproject.toml"
                | "requirements.txt"
                | "go.mod"
                | "pom.xml"
                | "build.gradle"
                | "composer.json"
                | "tsconfig.json"
                | ".gitignore"
                | "dockerfile"
                | "docker-compose.yml"
        )
    {
        return true;
    }

    // Main/index files in root or src
    if (path.starts_with("src/") || path.starts_with("lib/") || !path.contains('/'))
        && (path.contains("main") || path.contains("index"))
    {
        return true;
    }

    false
}

async fn try_include_file_with_budget(
    mut file: FileInfo,
    counter: &TokenCounter,
    budget_tracker: &mut TokenBudget,
) -> Result<Option<FileInfo>> {
    match load_file_content_safe(&file.path) {
        Ok(content) => match counter.estimate_file_tokens(&content, &file.path) {
            Ok(token_count) => {
                if budget_tracker.can_allocate(token_count) {
                    budget_tracker.allocate(token_count);
                    file.content = Some(content);
                    file.token_estimate = Some(token_count);
                    file.char_count = Some(file.content.as_ref().unwrap().chars().count());
                    file.line_count = Some(file.content.as_ref().unwrap().lines().count());
                    Ok(Some(file))
                } else {
                    if std::env::var("SCRIBE_DEBUG").is_ok() {
                        eprintln!(
                            "⚠️  Skipping {} ({} tokens) - would exceed budget",
                            file.relative_path, token_count
                        );
                    }
                    Ok(None)
                }
            }
            Err(e) => {
                if std::env::var("SCRIBE_DEBUG").is_ok() {
                    eprintln!(
                        "⚠️  Failed to estimate tokens for {}: {}",
                        file.relative_path, e
                    );
                }
                Ok(None)
            }
        },
        Err(e) => {
            if std::env::var("SCRIBE_DEBUG").is_ok() {
                eprintln!("⚠️  Failed to read {}: {}", file.relative_path, e);
            }
            Ok(None)
        }
    }
}

async fn try_include_file_with_budget_and_demotion(
    mut file: FileInfo,
    counter: &TokenCounter,
    budget_tracker: &mut TokenBudget,
    centrality_score: f64,
) -> Result<Option<FileInfo>> {
    match load_file_content_safe(&file.path) {
        Ok(content) => match counter.estimate_file_tokens(&content, &file.path) {
            Ok(full_tokens) => {
                // Try full content first
                if budget_tracker.can_allocate(full_tokens) {
                    budget_tracker.allocate(full_tokens);
                    file.content = Some(content);
                    file.token_estimate = Some(full_tokens);
                    file.char_count = Some(file.content.as_ref().unwrap().chars().count());
                    file.line_count = Some(file.content.as_ref().unwrap().lines().count());
                    return Ok(Some(file));
                }

                // Full content doesn't fit - try demotion for source files
                if matches!(file.file_type, FileType::Source { .. }) {
                    if std::env::var("SCRIBE_DEBUG").is_ok() {
                        eprintln!(
                            "🔧 Trying demotion for {} ({} tokens → chunks/signatures)",
                            file.relative_path, full_tokens
                        );
                    }

                    if let Ok(mut demotion_engine) = DemotionEngine::new() {
                        if let Ok(chunk_result) = demotion_engine.demote_content(
                            &content,
                            &file.relative_path,
                            FidelityMode::Chunk,
                            Some(budget_tracker.available()),
                        ) {
                            if budget_tracker.can_allocate(chunk_result.demoted_tokens) {
                                budget_tracker.allocate(chunk_result.demoted_tokens);
                                file.content = Some(chunk_result.content);
                                file.token_estimate = Some(chunk_result.demoted_tokens);
                                file.char_count =
                                    Some(file.content.as_ref().unwrap().chars().count());
                                file.line_count =
                                    Some(file.content.as_ref().unwrap().lines().count());
                                if std::env::var("SCRIBE_DEBUG").is_ok() {
                                    eprintln!(
                                        "✅ Demoted {} to chunks ({}{} tokens, {:.1}% compression, centrality: {:.4})",
                                        file.relative_path,
                                        full_tokens,
                                        chunk_result.demoted_tokens,
                                        chunk_result.compression_ratio * 100.0,
                                        centrality_score
                                    );
                                }
                                return Ok(Some(file));
                            }
                        }

                        if let Ok(sig_result) = demotion_engine.demote_content(
                            &content,
                            &file.relative_path,
                            FidelityMode::Signature,
                            None,
                        ) {
                            if budget_tracker.can_allocate(sig_result.demoted_tokens) {
                                budget_tracker.allocate(sig_result.demoted_tokens);
                                file.content = Some(sig_result.content);
                                file.token_estimate = Some(sig_result.demoted_tokens);
                                file.char_count =
                                    Some(file.content.as_ref().unwrap().chars().count());
                                file.line_count =
                                    Some(file.content.as_ref().unwrap().lines().count());
                                if std::env::var("SCRIBE_DEBUG").is_ok() {
                                    eprintln!(
                                        "✅ Demoted {} to signatures ({}{} tokens, {:.1}% compression, centrality: {:.4})",
                                        file.relative_path,
                                        full_tokens,
                                        sig_result.demoted_tokens,
                                        sig_result.compression_ratio * 100.0,
                                        centrality_score
                                    );
                                }
                                return Ok(Some(file));
                            }
                        }
                    }
                }

                if std::env::var("SCRIBE_DEBUG").is_ok() {
                    eprintln!(
                        "⚠️  Skipping {} ({} tokens) - no demotion method fits budget",
                        file.relative_path, full_tokens
                    );
                }
                Ok(None)
            }
            Err(e) => {
                if std::env::var("SCRIBE_DEBUG").is_ok() {
                    eprintln!(
                        "⚠️  Failed to estimate tokens for {}: {}",
                        file.relative_path, e
                    );
                }
                Ok(None)
            }
        },
        Err(e) => {
            if std::env::var("SCRIBE_DEBUG").is_ok() {
                eprintln!("⚠️  Failed to read {}: {}", file.relative_path, e);
            }
            Ok(None)
        }
    }
}

struct MockScanResult {
    path: String,
    relative_path: String,
    centrality_score: Option<f64>,
}

impl MockScanResult {
    fn from_file_info(file: &FileInfo) -> Self {
        Self {
            path: file.path.to_string_lossy().to_string(),
            relative_path: file.relative_path.clone(),
            centrality_score: file.centrality_score,
        }
    }
}

impl ScanResult for MockScanResult {
    fn path(&self) -> &str {
        &self.path
    }

    fn relative_path(&self) -> &str {
        &self.relative_path
    }

    fn depth(&self) -> usize {
        self.relative_path.matches('/').count()
    }

    fn is_docs(&self) -> bool {
        false
    }

    fn is_readme(&self) -> bool {
        self.relative_path.to_lowercase().contains("readme")
    }

    fn is_entrypoint(&self) -> bool {
        self.relative_path.contains("main") || self.relative_path.contains("index")
    }

    fn has_examples(&self) -> bool {
        self.relative_path.contains("example")
    }

    fn is_test(&self) -> bool {
        self.relative_path.contains("test")
    }

    fn priority_boost(&self) -> f64 {
        0.0
    }

    fn churn_score(&self) -> f64 {
        0.0
    }

    fn centrality_in(&self) -> f64 {
        self.centrality_score.unwrap_or(0.0)
    }

    fn imports(&self) -> Option<&[String]> {
        None
    }

    fn doc_analysis(&self) -> Option<&scribe_analysis::heuristics::DocumentAnalysis> {
        None
    }
}

fn load_file_content_safe(path: &Path) -> Result<String> {
    std::fs::read_to_string(path)
        .map_err(|e| ScribeError::io(format!("Failed to read file {}: {}", path.display(), e), e))
}