octocode 0.14.1

AI-powered code intelligence with semantic search, knowledge graphs, and built-in MCP server. Transform your codebase into a queryable knowledge graph for AI assistants.
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
// Copyright 2026 Muvon Un Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use clap::Args;

use octocode::config::Config;
use octocode::constants::MAX_QUERIES;
use octocode::indexer;

use octocode::storage;
use octocode::store::Store;

use crate::commands::OutputFormat;

fn validate_detail_level(s: &str) -> Result<String, String> {
	match s {
		"signatures" | "partial" | "full" => Ok(s.to_string()),
		_ => Err(format!(
			"Invalid detail level '{}'. Use 'signatures', 'partial', or 'full'.",
			s
		)),
	}
}

fn validate_queries(queries: &[String]) -> Result<(), anyhow::Error> {
	if queries.is_empty() {
		return Err(anyhow::anyhow!("At least one query is required"));
	}

	if queries.len() > MAX_QUERIES {
		return Err(anyhow::anyhow!(
			"Maximum {} queries allowed, got {}. Use fewer, more specific terms.",
			MAX_QUERIES,
			queries.len()
		));
	}

	for (i, query) in queries.iter().enumerate() {
		let query = query.trim();
		if query.len() < 3 {
			return Err(anyhow::anyhow!(
				"Query {} must be at least 3 characters long",
				i + 1
			));
		}
		if query.len() > 500 {
			return Err(anyhow::anyhow!(
				"Query {} must be no more than 500 characters long",
				i + 1
			));
		}
	}

	Ok(())
}

#[derive(Debug, Args)]
pub struct SearchArgs {
	/// The search queries
	#[arg(required = true)]
	pub queries: Vec<String>,

	/// Search mode: 'all' (default), 'code', 'docs', 'text', or 'commits'
	#[arg(short, long, default_value = "all")]
	pub mode: String,

	/// Output format: 'cli', 'json', 'md', or 'text'
	#[arg(short, long, default_value = "cli")]
	pub format: OutputFormat,

	/// Similarity threshold (0.0-1.0). Higher values = more similar results only. Defaults to config.search.similarity_threshold
	#[arg(short, long)]
	pub threshold: Option<f32>,

	/// Expand symbols (show full function/class definitions)
	#[arg(short, long)]
	pub expand: bool,

	/// Detail level for output: 'signatures', 'partial', or 'full' (default: partial for cli/text formats)
	#[arg(short = 'd', long, value_parser = validate_detail_level)]
	pub detail_level: Option<String>,

	/// Filter by programming language (only affects code blocks)
	#[arg(short = 'l', long)]
	pub language: Option<String>,
}

pub async fn execute(
	store: &Store,
	args: &SearchArgs,
	config: &Config,
) -> Result<(), anyhow::Error> {
	let current_dir = std::env::current_dir()?;

	// Use the new storage system to check for index
	let index_path = storage::get_project_database_path(&current_dir)?;

	// Check if we have an index already; if not, inform the user but don't auto-index
	if !index_path.exists() {
		return Err(anyhow::anyhow!(
			"No index found. Please run 'octocode index' first to create an index."
		));
	}

	// Validate queries
	validate_queries(&args.queries)?;

	// Use config default threshold if not provided via CLI
	let threshold = args.threshold.unwrap_or(config.search.similarity_threshold);

	// Validate similarity threshold
	if !(0.0..=1.0).contains(&threshold) {
		return Err(anyhow::anyhow!(
			"Similarity threshold must be between 0.0 and 1.0, got: {}",
			threshold
		));
	}

	// Validate search mode
	let search_mode = match args.mode.as_str() {
		"all" | "code" | "docs" | "text" | "commits" => args.mode.as_str(),
		_ => {
			return Err(anyhow::anyhow!(
				"Invalid search mode '{}'. Use 'all', 'code', 'docs', 'text', or 'commits'.",
				args.mode
			));
		}
	};

	// Validate language filter if provided
	if let Some(ref language) = args.language {
		use octocode::indexer::languages;
		if languages::get_language(language).is_none() {
			return Err(anyhow::anyhow!(
				"Invalid language '{}'. Supported languages: rust, javascript, typescript, python, go, cpp, php, bash, ruby, json, svelte, css",
				language
			));
		}
	}

	// Validate detail_level is only used with compatible formats
	if args.detail_level.is_some() {
		if args.format.is_json() {
			return Err(anyhow::anyhow!(
				"--detail-level is not supported with JSON format. Use --format=cli or --format=text instead."
			));
		}
		if args.format.is_md() {
			return Err(anyhow::anyhow!(
				"--detail-level is not supported with Markdown format. Use --format=cli or --format=text instead."
			));
		}
	}

	// Get effective detail level (default to "partial" for cli/text formats)
	let effective_detail_level = args.detail_level.as_deref().unwrap_or("partial");

	// Generate batch embeddings for all queries
	let embeddings =
		indexer::search::generate_batch_embeddings_for_queries(&args.queries, search_mode, config)
			.await?;

	// Zip queries with embeddings
	let query_embeddings: Vec<_> = args
		.queries
		.iter()
		.cloned()
		.zip(embeddings.into_iter())
		.collect();

	// Detect branch context for branch-aware search
	let branch_ctx = {
		if let Some(branch_name) = indexer::branch::detect_branch_context(&current_dir) {
			let branch_dir = storage::get_branch_dir(&current_dir, &branch_name)?;
			if let Ok(Some(manifest)) = indexer::branch::load_manifest(&branch_dir) {
				match octocode::store::Store::new_for_branch(&branch_name).await {
					Ok(branch_store) => Some(indexer::search::BranchSearchContext {
						store: branch_store,
						manifest,
					}),
					Err(_) => None,
				}
			} else {
				None
			}
		} else {
			None
		}
	};

	// Execute parallel searches - pass similarity threshold directly (conversion happens inside)
	let search_results = indexer::search::execute_parallel_searches(
		store,
		query_embeddings,
		&indexer::search::SearchParams {
			mode: search_mode,
			max_results: config.search.max_results,
			similarity_threshold: threshold,
			language_filter: args.language.as_deref(),
			config,
			branch_ctx: branch_ctx.as_ref(),
		},
	)
	.await?;

	// When reranker is enabled, skip distance pre-filter — let reranker decide relevance.
	let dedup_distance_threshold = if config.search.reranker.enabled {
		None
	} else {
		Some(1.0 - threshold)
	};

	// Deduplicate and merge with multi-query bonuses
	let (mut code_blocks, mut doc_blocks, mut text_blocks, mut commit_blocks) =
		indexer::search::deduplicate_and_merge_results(
			search_results,
			&args.queries,
			dedup_distance_threshold,
		);

	// Apply reranker if enabled, then filter by similarity threshold
	if config.search.reranker.enabled && !args.queries.is_empty() {
		let query = args.queries.join(" ");
		code_blocks = octocode::reranker::rerank_code_blocks_with_octolib(
			&query,
			code_blocks,
			&config.search.reranker,
		)
		.await?;
		doc_blocks = octocode::reranker::rerank_doc_blocks_with_octolib(
			&query,
			doc_blocks,
			&config.search.reranker,
		)
		.await?;
		text_blocks = octocode::reranker::rerank_text_blocks_with_octolib(
			&query,
			text_blocks,
			&config.search.reranker,
		)
		.await?;
		commit_blocks = octocode::reranker::rerank_commit_blocks_with_octolib(
			&query,
			commit_blocks,
			&config.search.reranker,
		)
		.await?;

		// Apply similarity threshold to reranker scores (post-reranker filter)
		let dist_thresh = 1.0 - threshold;
		code_blocks.retain(|b| b.distance.is_none_or(|d| d <= dist_thresh));
		doc_blocks.retain(|b| b.distance.is_none_or(|d| d <= dist_thresh));
		text_blocks.retain(|b| b.distance.is_none_or(|d| d <= dist_thresh));
		commit_blocks.retain(|b| b.distance.is_none_or(|d| d <= dist_thresh));
	} else {
		// Apply global result limits (reranker already limits via final_top_k)
		code_blocks.truncate(config.search.max_results);
		doc_blocks.truncate(config.search.max_results);
		text_blocks.truncate(config.search.max_results);
		commit_blocks.truncate(config.search.max_results);
	}

	// Symbol expansion if requested
	if args.expand && !code_blocks.is_empty() {
		println!("Expanding symbols...");
		code_blocks = indexer::expand_symbols(store, code_blocks).await?;
	}

	// Use EXISTING output formatting with added text support
	match search_mode {
		"code" => {
			if args.format.is_json() {
				indexer::render_results_json(&code_blocks)?
			} else if args.format.is_md() {
				let markdown = indexer::code_blocks_to_markdown_with_config(&code_blocks, config);
				println!("{}", markdown);
			} else if args.format.is_text() {
				// Use text formatting function for token efficiency
				let text_output = indexer::search::format_code_search_results_as_text(
					&code_blocks,
					effective_detail_level,
				);
				println!("{}", text_output);
			} else {
				indexer::render_code_blocks_with_config(
					&code_blocks,
					config,
					effective_detail_level,
				);
			}
		}
		"docs" => {
			if args.format.is_json() {
				let json = serde_json::to_string_pretty(&doc_blocks)?;
				println!("{}", json);
			} else if args.format.is_md() {
				let markdown =
					indexer::document_blocks_to_markdown_with_config(&doc_blocks, config);
				println!("{}", markdown);
			} else if args.format.is_text() {
				// Use text formatting function for token efficiency
				let text_output = indexer::search::format_doc_search_results_as_text(
					&doc_blocks,
					effective_detail_level,
				);
				println!("{}", text_output);
			} else {
				render_document_blocks_with_config(&doc_blocks, config, effective_detail_level);
			}
		}
		"text" => {
			if args.format.is_json() {
				let json = serde_json::to_string_pretty(&text_blocks)?;
				println!("{}", json);
			} else if args.format.is_md() {
				let markdown = indexer::text_blocks_to_markdown_with_config(&text_blocks, config);
				println!("{}", markdown);
			} else if args.format.is_text() {
				// Use text formatting function for token efficiency
				let text_output = indexer::search::format_text_search_results_as_text(
					&text_blocks,
					effective_detail_level,
				);
				println!("{}", text_output);
			} else {
				render_text_blocks_with_config(&text_blocks, config, effective_detail_level);
			}
		}
		"commits" => {
			let output = indexer::search::format_commit_search_results_as_text(
				&commit_blocks,
				effective_detail_level,
			);
			if args.format.is_json() {
				let json = serde_json::to_string_pretty(&commit_blocks)?;
				println!("{}", json);
			} else {
				println!("{}", output);
			}
		}
		"all" => {
			let mut final_code_results = code_blocks;
			if args.expand {
				println!("Expanding symbols...");
				final_code_results = indexer::expand_symbols(store, final_code_results).await?;
			}

			if args.format.is_json() {
				let combined = serde_json::json!({
					"code_blocks": final_code_results,
					"document_blocks": doc_blocks,
					"text_blocks": text_blocks
				});
				println!("{}", serde_json::to_string_pretty(&combined)?);
			} else if args.format.is_md() {
				let mut combined_markdown = String::new();

				if !doc_blocks.is_empty() {
					combined_markdown.push_str("# Documentation Results\n\n");
					combined_markdown.push_str(&indexer::document_blocks_to_markdown_with_config(
						&doc_blocks,
						config,
					));
					combined_markdown.push('\n');
				}

				if !final_code_results.is_empty() {
					combined_markdown.push_str("# Code Results\n\n");
					combined_markdown.push_str(&indexer::code_blocks_to_markdown_with_config(
						&final_code_results,
						config,
					));
					combined_markdown.push('\n');
				}

				if !text_blocks.is_empty() {
					combined_markdown.push_str("# Text Results\n\n");
					combined_markdown.push_str(&indexer::text_blocks_to_markdown_with_config(
						&text_blocks,
						config,
					));
				}

				if combined_markdown.is_empty() {
					combined_markdown.push_str("No results found for the query.");
				}

				println!("{}", combined_markdown);
			} else if args.format.is_text() {
				// Use text formatting function for token efficiency
				let text_output = indexer::search::format_combined_search_results_as_text(
					&final_code_results,
					&text_blocks,
					&doc_blocks,
					effective_detail_level,
				);
				println!("{}", text_output);
			} else {
				if !doc_blocks.is_empty() {
					println!("=== DOCUMENTATION RESULTS ===\n");
					render_document_blocks_with_config(&doc_blocks, config, effective_detail_level);
					println!("\n");
				}

				if !final_code_results.is_empty() {
					println!("=== CODE RESULTS ===\n");
					indexer::render_code_blocks_with_config(
						&final_code_results,
						config,
						effective_detail_level,
					);
					println!("\n");
				}

				if !text_blocks.is_empty() {
					println!("=== TEXT RESULTS ===\n");
					render_text_blocks_with_config(&text_blocks, config, effective_detail_level);
				}

				if doc_blocks.is_empty() && final_code_results.is_empty() && text_blocks.is_empty()
				{
					println!("No results found for the query.");
				}
			}
		}
		_ => unreachable!(),
	}

	Ok(())
}

fn render_text_blocks_with_config(
	blocks: &[octocode::store::TextBlock],
	_config: &Config,
	detail_level: &str,
) {
	if blocks.is_empty() {
		println!("No text blocks found.");
		return;
	}

	println!("Found {} text blocks:\n", blocks.len());

	// Group blocks by file path for better organization
	let mut blocks_by_file: std::collections::HashMap<String, Vec<&octocode::store::TextBlock>> =
		std::collections::HashMap::new();

	for block in blocks {
		blocks_by_file
			.entry(block.path.clone())
			.or_default()
			.push(block);
	}

	// Print results organized by file
	for (file_path, file_blocks) in blocks_by_file.iter() {
		println!("╔══════════════════ File: {} ══════════════════", file_path);

		for (idx, block) in file_blocks.iter().enumerate() {
			println!("");
			println!("║ Block {} of {}: Text Block", idx + 1, file_blocks.len());
			println!("║ Lines: {}-{}", block.start_line, block.end_line);

			// Show similarity score if available
			if let Some(distance) = block.distance {
				println!("║ Similarity: {:.4}", 1.0 - distance);
			}

			println!("");

			// Add content based on detail level (consistent with MCP smart truncation)
			match detail_level {
				"signatures" => {
					// Show only first line for signatures mode
					if let Some(first_line) = block.content.lines().next() {
						println!("{:4}{}", block.start_line, first_line.trim());
					}
				}
				"partial" => {
					// Show smart truncated content (first 4 + last 3 lines with separator)
					let lines: Vec<&str> = block.content.lines().collect();
					if lines.len() <= 10 {
						// Show all lines if content is short
						for (i, line) in lines.iter().enumerate() {
							println!("{:4}{}", block.start_line + i + 1, line);
						}
					} else {
						// Smart truncation: first 4 lines
						for (i, line) in lines.iter().take(4).enumerate() {
							println!("{:4}{}", block.start_line + i + 1, line);
						}

						// Show separator with count
						let omitted_lines = lines.len() - 7; // 4 start + 3 end
						if omitted_lines > 0 {
							println!("║      │ ... ({} more lines)", omitted_lines);
						}

						// Last 3 lines
						let last_3_start = lines.len() - 3;
						for (i, line) in lines.iter().skip(last_3_start).enumerate() {
							println!("{:4}{}", block.start_line + last_3_start + i + 1, line);
						}
					}
				}
				"full" => {
					// Show full content with line numbers
					let lines: Vec<&str> = block.content.lines().collect();
					for (i, line) in lines.iter().enumerate() {
						println!("{:4}{}", block.start_line + i + 1, line);
					}
				}
				_ => {
					// Default to partial
					let lines: Vec<&str> = block.content.lines().collect();
					if lines.len() <= 10 {
						for (i, line) in lines.iter().enumerate() {
							println!("{:4}{}", block.start_line + i + 1, line);
						}
					} else {
						// Smart truncation: first 4 lines
						for (i, line) in lines.iter().take(4).enumerate() {
							println!("{:4}{}", block.start_line + i + 1, line);
						}

						let omitted_lines = lines.len() - 7;
						if omitted_lines > 0 {
							println!("║      │ ... ({} more lines)", omitted_lines);
						}

						// Last 3 lines
						let last_3_start = lines.len() - 3;
						for (i, line) in lines.iter().skip(last_3_start).enumerate() {
							println!("{:4}{}", block.start_line + last_3_start + i + 1, line);
						}
					}
				}
			}

			if idx < file_blocks.len() - 1 {
				println!("");
				println!("╠══════════════════════════════════════════════");
			}
		}

		println!("╚══════════════════════════════════════════════\n");
	}
}

fn render_document_blocks_with_config(
	blocks: &[octocode::store::DocumentBlock],
	_config: &Config,
	detail_level: &str,
) {
	if blocks.is_empty() {
		println!("No document blocks found.");
		return;
	}

	println!("Found {} document blocks:\n", blocks.len());

	// Group blocks by file path for better organization
	let mut blocks_by_file: std::collections::HashMap<
		String,
		Vec<&octocode::store::DocumentBlock>,
	> = std::collections::HashMap::new();

	for block in blocks {
		blocks_by_file
			.entry(block.path.clone())
			.or_default()
			.push(block);
	}

	// Print results organized by file
	for (file_path, file_blocks) in blocks_by_file.iter() {
		println!("╔══════════════════ File: {} ══════════════════", file_path);

		for (idx, block) in file_blocks.iter().enumerate() {
			println!("");
			println!(
				"║ Block {} of {}: Document Block",
				idx + 1,
				file_blocks.len()
			);
			println!("║ Lines: {}-{}", block.start_line, block.end_line);

			// Show similarity score if available
			if let Some(distance) = block.distance {
				println!("║ Similarity: {:.4}", 1.0 - distance);
			}

			println!("");

			// Add content based on detail level (consistent with smart truncation)
			match detail_level {
				"signatures" => {
					// Show only title/first line for signatures mode
					if !block.title.is_empty() {
						println!("║ Title: {}", block.title);
					} else if let Some(first_line) = block.content.lines().next() {
						println!("{}: {}", block.start_line, first_line.trim());
					}
				}
				"partial" => {
					// Show title and smart truncated content (first 4 + last 3 lines with separator)
					if !block.title.is_empty() {
						println!("║ Title: {}", block.title);
					}
					let lines: Vec<&str> = block.content.lines().collect();
					if lines.len() <= 10 {
						// Show all lines if content is short
						for (i, line) in lines.iter().enumerate() {
							println!("{:4}{}", block.start_line + i + 1, line);
						}
					} else {
						// Smart truncation: first 4 lines
						for (i, line) in lines.iter().take(4).enumerate() {
							println!("{:4}{}", block.start_line + i + 1, line);
						}

						// Show separator with count
						let omitted_lines = lines.len() - 7; // 4 start + 3 end
						if omitted_lines > 0 {
							println!("║      │ ... ({} more lines)", omitted_lines);
						}

						// Last 3 lines
						let last_3_start = lines.len() - 3;
						for (i, line) in lines.iter().skip(last_3_start).enumerate() {
							println!("{:4}{}", block.start_line + last_3_start + i + 1, line);
						}
					}
				}
				"full" => {
					// Show full content with line numbers
					if !block.title.is_empty() {
						println!("║ Title: {}", block.title);
					}
					let lines: Vec<&str> = block.content.lines().collect();
					for (i, line) in lines.iter().enumerate() {
						println!("{:4}{}", block.start_line + i + 1, line);
					}
				}
				_ => {
					// Default to partial
					if !block.title.is_empty() {
						println!("║ Title: {}", block.title);
					}
					let lines: Vec<&str> = block.content.lines().collect();
					if lines.len() <= 10 {
						for (i, line) in lines.iter().enumerate() {
							println!("{:4}{}", block.start_line + i + 1, line);
						}
					} else {
						// Smart truncation: first 4 lines
						for (i, line) in lines.iter().take(4).enumerate() {
							println!("{:4}{}", block.start_line + i + 1, line);
						}

						let omitted_lines = lines.len() - 7;
						if omitted_lines > 0 {
							println!("║      │ ... ({} more lines)", omitted_lines);
						}

						// Last 3 lines
						let last_3_start = lines.len() - 3;
						for (i, line) in lines.iter().skip(last_3_start).enumerate() {
							println!("{:4}{}", block.start_line + last_3_start + i + 1, line);
						}
					}
				}
			}

			if idx < file_blocks.len() - 1 {
				println!("");
				println!("╠══════════════════════════════════════════════");
			}
		}

		println!("╚══════════════════════════════════════════════\n");
	}
}