codanna 0.9.19

Code Intelligence for Large Language Models
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Documents management command.

use std::path::PathBuf;
use std::time::Instant;

use crate::cli::DocumentAction;
use crate::config::Settings;
use crate::documents::{CollectionConfig, DocumentStore, IndexProgress, SearchQuery};
use crate::io::EnvelopeEntityType;
use crate::io::envelope::{Envelope, ResultCode};
use crate::io::status_line::StatusLine;
use crate::io::{ProgressBar, ProgressBarOptions, ProgressBarStyle};
use crate::vector::{FastEmbedGenerator, VectorDimension};

/// Print JSON or error message if serialization fails.
fn print_json<T: serde::Serialize>(value: &T) {
    match serde_json::to_string_pretty(value) {
        Ok(json) => println!("{json}"),
        Err(e) => {
            eprintln!("JSON serialization error: {e}");
            std::process::exit(2);
        }
    }
}

/// Run documents management command.
pub fn run(action: DocumentAction, config: &Settings, cli_config: Option<&PathBuf>) {
    let doc_path = config.index_path.join("documents");
    let dimension = VectorDimension::dimension_384();

    // Helper to create store with optional embeddings
    let create_store_with_embeddings = || -> Result<DocumentStore, String> {
        let store = DocumentStore::new(&doc_path, dimension)
            .map_err(|e| format!("Failed to open document store: {e}"))?;

        if config.semantic_search.enabled {
            let generator = FastEmbedGenerator::new()
                .map_err(|e| format!("Failed to create embedding generator: {e}"))?;
            store
                .with_embeddings(Box::new(generator))
                .map_err(|e| format!("Failed to enable embeddings: {e}"))
        } else {
            Ok(store)
        }
    };

    match action {
        DocumentAction::Index {
            collection,
            all,
            force,
            no_progress,
        } => {
            // Progress enabled by default from settings, --no-progress overrides
            let show_progress = config.indexing.show_progress && !no_progress;
            run_index(
                config,
                collection,
                all,
                force,
                show_progress,
                create_store_with_embeddings,
            );
        }

        DocumentAction::Search {
            args,
            collection,
            limit,
            json,
            fields,
        } => {
            use crate::io::args::parse_positional_args;

            // Parse positional arguments for query and key:value pairs
            let (positional_query, params) = parse_positional_args(&args);

            // Determine query source (priority: positional > key:value)
            let final_query = positional_query
                .or_else(|| params.get("query").cloned())
                .unwrap_or_else(|| {
                    eprintln!("Error: search requires a query");
                    eprintln!("Usage: codanna documents search \"query\" [options]");
                    eprintln!("   or: codanna documents search query:\"search text\" [options]");
                    std::process::exit(1);
                });

            // Merge parameters (flags take precedence over key:value)
            let final_limit = limit.unwrap_or_else(|| {
                params
                    .get("limit")
                    .and_then(|s| s.parse::<usize>().ok())
                    .unwrap_or(10)
            });

            // Collection can come from --collection flag or collection:name
            let final_collection = collection.or_else(|| params.get("collection").cloned());

            let mut store = match create_store_with_embeddings() {
                Ok(s) => s,
                Err(e) => {
                    if json {
                        let envelope: Envelope<()> = Envelope::error(ResultCode::IndexError, &e)
                            .with_hint("Run 'codanna documents index' to create the index");
                        print_json(&envelope);
                        std::process::exit(2);
                    }
                    eprintln!("{e}");
                    std::process::exit(1);
                }
            };

            let query_text = final_query.clone();
            let search_query = SearchQuery {
                text: final_query,
                collection: final_collection,
                document: None,
                limit: final_limit,
                preview_config: Some(config.documents.search.clone()),
            };

            let start = Instant::now();
            match store.search(search_query) {
                Ok(results) => {
                    let duration_ms = start.elapsed().as_millis() as u64;
                    let count = results.len();

                    if json {
                        let envelope = if results.is_empty() {
                            Envelope::<Vec<_>>::not_found("No documents matched the query")
                                .with_query(&query_text)
                                .with_duration_ms(duration_ms)
                                .with_entity_type(EnvelopeEntityType::Document)
                                .with_hint("Try a different query or check indexed collections with 'codanna documents list'")
                        } else {
                            Envelope::success(results)
                                .with_message(format!("Found {count} matching documents"))
                                .with_entity_type(EnvelopeEntityType::Document)
                                .with_count(count)
                                .with_query(&query_text)
                                .with_duration_ms(duration_ms)
                                .with_hint(
                                    "Use the file paths and byte ranges to read specific sections",
                                )
                        };
                        let output = if let Some(ref field_list) = fields {
                            envelope.to_json_with_fields(field_list)
                        } else {
                            envelope.to_json()
                        };
                        match output {
                            Ok(json) => println!("{json}"),
                            Err(e) => {
                                eprintln!("JSON serialization error: {e}");
                                std::process::exit(2);
                            }
                        }
                    } else if results.is_empty() {
                        eprintln!("No results found.");
                    } else {
                        for (i, result) in results.iter().enumerate() {
                            println!(
                                "\n{}. {} (score: {:.3})",
                                i + 1,
                                result.source_path.display(),
                                result.similarity
                            );
                            if !result.heading_context.is_empty() {
                                println!("   Context: {}", result.heading_context.join(" > "));
                            }
                            println!("   Preview: {}", result.content_preview);
                        }
                    }
                }
                Err(e) => {
                    if json {
                        let envelope: Envelope<()> = Envelope::error(
                            ResultCode::InternalError,
                            format!("Search failed: {e}"),
                        );
                        print_json(&envelope);
                        std::process::exit(2);
                    }
                    eprintln!("Search failed: {e}");
                    std::process::exit(1);
                }
            }
        }

        DocumentAction::List { json } => {
            let store = match create_store_with_embeddings() {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("{e}");
                    std::process::exit(1);
                }
            };

            let collections = store.list_collections();
            if json {
                print_json(&collections);
            } else if collections.is_empty() {
                eprintln!("No collections indexed.");
                eprintln!("\nConfigured collections in settings.toml:");
                for name in config.documents.collections.keys() {
                    eprintln!("  - {name}");
                }
            } else {
                println!("Indexed collections:");
                for name in collections {
                    println!("  - {name}");
                }
            }
        }

        DocumentAction::Stats { collection, json } => {
            let store = match create_store_with_embeddings() {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("{e}");
                    std::process::exit(1);
                }
            };

            match store.collection_stats(&collection) {
                Ok(stats) => {
                    if json {
                        print_json(&stats);
                    } else {
                        println!("Collection: {}", stats.name);
                        println!("  Chunks: {}", stats.chunk_count);
                        println!("  Files: {}", stats.file_count);
                    }
                }
                Err(e) => {
                    eprintln!("Failed to get stats for '{collection}': {e}");
                    std::process::exit(1);
                }
            }
        }

        DocumentAction::AddCollection {
            name,
            path,
            pattern,
        } => {
            run_add_collection(config, cli_config, name, path, pattern);
        }

        DocumentAction::RemoveCollection { name } => {
            run_remove_collection(config, cli_config, name);
        }
    }
}

fn run_index<F>(
    config: &Settings,
    collection: Option<String>,
    all: bool,
    force: bool,
    progress: bool,
    create_store_with_embeddings: F,
) where
    F: Fn() -> Result<DocumentStore, String>,
{
    use std::cell::RefCell;
    use std::sync::Arc;

    // Create or open document store with embeddings
    let mut store = match create_store_with_embeddings() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{e}");
            std::process::exit(1);
        }
    };

    // Force flag: clear file states to treat all files as new
    if force {
        eprintln!("Force re-indexing: clearing file state cache");
        store.clear_file_states();
    }

    // Determine which collections to index
    let collections_to_index: Vec<(String, CollectionConfig)> = if let Some(name) = collection {
        match config.documents.collections.get(&name) {
            Some(col_config) => vec![(name, col_config.clone())],
            None => {
                eprintln!("Collection '{name}' not found in settings.toml");
                eprintln!("\nConfigured collections:");
                for name in config.documents.collections.keys() {
                    eprintln!("  - {name}");
                }
                std::process::exit(1);
            }
        }
    } else if all || config.documents.enabled {
        config
            .documents
            .collections
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect()
    } else {
        eprintln!("Document indexing is disabled. Enable with:");
        eprintln!("  [documents]");
        eprintln!("  enabled = true");
        eprintln!("\nOr specify a collection: --collection <name>");
        std::process::exit(1);
    };

    // Sync: remove collections that are indexed but not in config
    let indexed_collections: std::collections::HashSet<String> =
        store.list_collections().into_iter().collect();
    let configured_collections: std::collections::HashSet<String> =
        config.documents.collections.keys().cloned().collect();

    let stale_collections: Vec<String> = indexed_collections
        .difference(&configured_collections)
        .cloned()
        .collect();

    if !stale_collections.is_empty() {
        eprintln!(
            "Sync: removing {} stale collections",
            stale_collections.len()
        );
        for name in &stale_collections {
            eprintln!("  - {name}");
            if let Err(e) = store.delete_collection(name) {
                eprintln!("    Failed to remove: {e}");
            }
        }
    }

    // Now check if there's anything to index
    if collections_to_index.is_empty() {
        if stale_collections.is_empty() {
            eprintln!("No collections configured in settings.toml");
            eprintln!("\nTo add a collection:");
            eprintln!("  codanna documents add-collection <name> <path>");
        } else {
            eprintln!("Cleaned stale collections. No collections to index.");
        }
        return;
    }

    // Progress state for two-phase display
    type ProgressState = Option<(Arc<ProgressBar>, StatusLine<Arc<ProgressBar>>)>;
    let phase1_bar: RefCell<ProgressState> = RefCell::new(None);
    let phase2_bar: RefCell<ProgressState> = RefCell::new(None);

    let mut total_files = 0usize;
    let mut total_chunks = 0usize;

    for (name, col_config) in collections_to_index {
        let chunking = col_config.effective_chunking(&config.documents.defaults);

        if !progress {
            eprintln!("Indexing collection: {name}");
        }

        // Index with two-phase progress callback
        let result = store.index_collection_with_progress(&name, &col_config, &chunking, |prog| {
            if !progress {
                return;
            }
            match prog {
                IndexProgress::ProcessingFile { current, total, .. } => {
                    let mut p1 = phase1_bar.borrow_mut();
                    if p1.is_none() && total > 0 {
                        let options = ProgressBarOptions::default()
                            .with_style(ProgressBarStyle::VerticalSolid)
                            .with_width(28);
                        let bar = Arc::new(ProgressBar::with_options(
                            total as u64,
                            "files",
                            "chunked",
                            "failed",
                            options,
                        ));
                        let status = StatusLine::new(Arc::clone(&bar));
                        *p1 = Some((bar, status));
                    }
                    if let Some((bar, _)) = p1.as_ref() {
                        bar.set_progress(current as u64);
                    }
                }
                IndexProgress::GeneratingEmbeddings { current, total } => {
                    // Finish Phase 1 if active
                    let mut p1 = phase1_bar.borrow_mut();
                    if let Some((bar, status)) = p1.take() {
                        drop(status);
                        eprintln!("{bar}");
                    }

                    let mut p2 = phase2_bar.borrow_mut();
                    if p2.is_none() && total > 0 {
                        let options = ProgressBarOptions::default()
                            .with_style(ProgressBarStyle::VerticalSolid)
                            .with_width(28);
                        let bar = Arc::new(ProgressBar::with_options(
                            total as u64,
                            "chunks",
                            "embedded",
                            "failed",
                            options,
                        ));
                        let status = StatusLine::new(Arc::clone(&bar));
                        *p2 = Some((bar, status));
                    }
                    if let Some((bar, _)) = p2.as_ref() {
                        bar.set_progress(current as u64);
                    }
                }
            }
        });

        match result {
            Ok(stats) => {
                total_files += stats.files_processed;
                total_chunks += stats.chunks_created;
                if !progress {
                    eprintln!("  Files processed: {}", stats.files_processed);
                    eprintln!("  Files skipped: {}", stats.files_skipped);
                    eprintln!("  Chunks created: {}", stats.chunks_created);
                    eprintln!("  Chunks removed: {}", stats.chunks_removed);
                }
            }
            Err(e) => {
                eprintln!("Failed to index collection '{name}': {e}");
            }
        };
    }

    // Print final progress bars and summary
    if let Some((bar, status)) = phase1_bar.borrow_mut().take() {
        drop(status);
        eprintln!("{bar}");
    }
    if let Some((bar, status)) = phase2_bar.borrow_mut().take() {
        drop(status);
        eprintln!("{bar}");
    }
    if progress {
        eprintln!("Total: {total_files} files, {total_chunks} chunks");
    }
}

fn run_add_collection(
    _config: &Settings,
    cli_config: Option<&PathBuf>,
    name: String,
    path: PathBuf,
    pattern: Option<String>,
) {
    // Find config file
    let config_path = if let Some(custom_path) = cli_config {
        custom_path.clone()
    } else {
        Settings::find_workspace_config().unwrap_or_else(|| {
            eprintln!("Error: No configuration file found. Run 'codanna init' first.");
            std::process::exit(1);
        })
    };

    // Canonicalize the path
    let canonical_path = match path.canonicalize() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("Error: Invalid path '{}': {e}", path.display());
            std::process::exit(1);
        }
    };

    // Check if path exists
    if !canonical_path.exists() {
        eprintln!("Error: Path does not exist: {}", canonical_path.display());
        std::process::exit(1);
    }

    // Load current settings
    let mut settings = match Settings::load() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("Error loading settings: {e}");
            std::process::exit(1);
        }
    };

    // Check if collection already exists
    if settings.documents.collections.contains_key(&name) {
        // Add path to existing collection
        let collection = settings.documents.collections.get_mut(&name).unwrap();
        if collection.paths.contains(&canonical_path) {
            eprintln!(
                "Path already in collection '{name}': {}",
                canonical_path.display()
            );
            std::process::exit(1);
        }
        collection.paths.push(canonical_path.clone());
        if let Some(pat) = pattern {
            if !collection.patterns.contains(&pat) {
                collection.patterns.push(pat);
            }
        }
        println!(
            "Added path to existing collection '{name}': {}",
            canonical_path.display()
        );
    } else {
        // Create new collection
        let patterns = pattern.map(|p| vec![p]).unwrap_or_default();
        let collection_config = CollectionConfig {
            paths: vec![canonical_path.clone()],
            patterns,
            strategy: None,
            min_chunk_chars: None,
            max_chunk_chars: None,
            overlap_chars: None,
        };
        settings
            .documents
            .collections
            .insert(name.clone(), collection_config);
        println!(
            "Created collection '{name}' with path: {}",
            canonical_path.display()
        );
    }

    // Enable documents if not already
    if !settings.documents.enabled {
        settings.documents.enabled = true;
        println!("Enabled document indexing (documents.enabled = true)");
    }

    // Save settings
    if let Err(e) = settings.save(&config_path) {
        eprintln!("Error saving settings: {e}");
        std::process::exit(1);
    }

    println!("Configuration saved to: {}", config_path.display());
    println!("\nTo index this collection:");
    println!("  codanna documents index --collection {name}");
    println!("  codanna documents index  # indexes all collections");
}

fn run_remove_collection(_config: &Settings, cli_config: Option<&PathBuf>, name: String) {
    // Find config file
    let config_path = if let Some(custom_path) = cli_config {
        custom_path.clone()
    } else {
        Settings::find_workspace_config().unwrap_or_else(|| {
            eprintln!("Error: No configuration file found. Run 'codanna init' first.");
            std::process::exit(1);
        })
    };

    // Load current settings
    let mut settings = match Settings::load() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("Error loading settings: {e}");
            std::process::exit(1);
        }
    };

    // Check if collection exists
    if !settings.documents.collections.contains_key(&name) {
        eprintln!("Collection '{name}' not found in settings.toml");
        if settings.documents.collections.is_empty() {
            eprintln!("\nNo collections configured.");
        } else {
            eprintln!("\nConfigured collections:");
            for coll_name in settings.documents.collections.keys() {
                eprintln!("  - {coll_name}");
            }
        }
        std::process::exit(1);
    }

    // Remove collection
    settings.documents.collections.remove(&name);
    println!("Removed collection '{name}' from settings.toml");

    // Save settings
    if let Err(e) = settings.save(&config_path) {
        eprintln!("Error saving settings: {e}");
        std::process::exit(1);
    }

    println!("Configuration saved to: {}", config_path.display());

    if settings.documents.collections.is_empty() {
        println!("\nNo collections remaining.");
    } else {
        println!("\nRemaining collections:");
        for coll_name in settings.documents.collections.keys() {
            println!("  - {coll_name}");
        }
    }

    println!("\nTo clean the index, run:");
    println!("  codanna documents index");
}